text:
Q: I cannot modify the item after appending to array I'm developing a multiplayer api for Unity Engine. I have Room and RoomManager struct. When I want create room, I set room name, id (all of variable), after that I append this new room to allRoom array in RoomManager struct. After that when I modified to room variable, I can't change any variable. I dont know why ?
Here is my structs and methods :
RoomManager struct
type RoomManager struct {
   allRooms    []Room
   roomCounter int
}

Room struct
type Room struct {
   tag               string
   name              string
   password          string
   id                int
   cappacity         int
   maxVariableCount  int
   userList          []User
   roomVariables     []RoomVariable
   extensionHandlers []ExtensionRequest
   InitializeMethod  roomInitializeFunc
}

Room Create Method
func (roomManager *RoomManager) CreateRoom(settings RoomSettings, arwServer *ARWServer) *Room {

   var newRoom Room
   newRoom.InitializeMethod = settings.InitializeMethod

   newRoom.name = settings.name
   newRoom.password = settings.password
   newRoom.tag = settings.tag
   newRoom.cappacity = settings.cappacity
   newRoom.maxVariableCount = settings.maxRoomVariableCount

   newRoom.id = roomManager.roomCounter
   roomManager.roomCounter++

   newRoom.userList = make([]User, 0, newRoom.cappacity)
   newRoom.roomVariables = make([]RoomVariable, 0, newRoom.maxVariableCount)

   if newRoom.InitializeMethod != nil {
     newRoom.InitializeMethod(arwServer, &newRoom)
   }

   roomManager.allRooms = append(roomManager.allRooms, newRoom)
   return &newRoom
}

Add User To Room
func (room *Room) AddUserToRoom(arwServer *ARWServer, u User) {
   room.userList = append(room.userList, u)

   var arwObj ARWObject

   arwObj.requestName = Join_Room
   arwObj.eventParams.PutString("RoomName", room.name)
   arwObj.eventParams.PutString("RoomTag", room.tag)
   arwObj.eventParams.PutInt("RoomId", room.id)
   arwObj.eventParams.PutInt("RoomCappacity", room.cappacity)

   usersData := ""
   for ii := 0; ii < len(room.userList); ii++ {
     if room.userList[ii].name != u.name {
       usersData += room.userList[ii].GetDataForOtherUser(u) + "''"
     }
   }

   usersData = strings.TrimRight(usersData, "''")

   arwObj.eventParams.PutString("Users", usersData)
   arwServer.SendRequestToUser(u, arwObj)

   var arwObjforTheOthers ARWObject
   arwObjforTheOthers.requestName = User_Enter_Room
   arwObjforTheOthers.eventParams.PutString("RoomName", room.name)
   arwObjforTheOthers.eventParams.PutString("userName", u.name)
   arwObjforTheOthers.eventParams.PutInt("userId", u.id)
   arwObjforTheOthers.eventParams.PutString("isMe", "false")

   room.SendRequestAllUserWithoutMe(*arwServer, arwObjforTheOthers, u)
   fmt.Println("User join Room - User Name : ", u.name+" Room : "+u.lastRoom.name)
}

A: Your issue is that your structs have non-pointer slices. In all of your structs define your slices as slices of pointers like so
Rooms []*Room

You also need to define your functions to take pointer values, like so
func(room *Room) {}

To elaborate. Go is pass-by-value. Anytime you pull something out of one of your original slices and pass it to one of your functions, it gets a copy. Using pointers modifies the actual value in the slice.
See this example. https://play.golang.org/p/ZThHrP0pds
package main

import (
    "fmt"
)

type Thing struct {
    Name string
}

func main() {
    things := []Thing{}
    thing := Thing{"thing1"}

    // add to slice
    // note that this is a function call
    things = append(things, thing)

    // attempt to change
    thing.Name = "thing2"
    fmt.Println(things[0].Name) // prints thing1
    fmt.Println(thing.Name)     // prints thing2

    fmt.Println("------")

    // try again
    thing3 := things[0]
    thing3.Name = "thing3"
    // fail again
    fmt.Println(things[0].Name) // prints thing1
    fmt.Println(thing3.Name)     // prints thing3

    fmt.Println("------")

    // do this instead
    betterThings := []*Thing{} // slice of pointers
    betterThing := &Thing{"thing2"} // betterThing is of type *Thing

    // add to slice
    betterThings = append(betterThings, betterThing)

    // successfully change
    betterThing.Name = "thing2"

    fmt.Println(betterThings[0].Name) // prints thing2
    fmt.Println(betterThing.Name)     // prints thing2
}


text:
Q: Memory leaks in Webbrowser (COM) This snippet of code generate huge memory leaks. Could you help me to find out where it happens?
This code does the following thing:
1) It gets IHTMLDocuments2 interface
2) Requests for all tags collection
3) Iterates over whole collection
4) and adds some of the tags' data to list
IDispatch* pDisp;
pDisp = this->GetHtmlDocument();

if (pDisp != NULL )
{
    IHTMLDocument2* pHTMLDocument2;
    HRESULT hr;
    hr = pDisp->QueryInterface( IID_IHTMLDocument2,(void**)&pHTMLDocument2 );
    if (hr == S_OK)
    {
                    // I know that I could use IHTMLDocument3 interface to get collection by ID
                    // but it didn't worked and returned NULL on each call.
        IHTMLElementCollection* pColl = NULL;
                    // get all tags
        hr = pHTMLDocument2->get_all( &pColl );
        if (hr == S_OK && pColl != NULL)
        {
            LONG celem;
            hr = pColl->get_length( &celem );
            if ( hr == S_OK )
            {
                                    //iterate through all tags
                                    // if I iterate this block of code in cycle, it
                                    // uses memory available upto 2GBs and then
                                    // app crashes
                for ( int i=0; i< celem; i++ )
                {
                    VARIANT varIndex;
                    varIndex.vt = VT_UINT;
                    varIndex.lVal = i;
                    VARIANT var2;
                    VariantInit( &var2 );
                    IDispatch* pElemDisp = NULL;
                    hr = pColl->item( varIndex, var2, &pElemDisp );
                    if ( hr == S_OK && pElemDisp != NULL)
                    {
                        IHTMLElement* pElem;
                        hr = pElemDisp->QueryInterface(IID_IHTMLElement,(void **)&pElem);
                        if ( hr == S_OK)
                        {
                                                            // check INPUT tags only
                            BSTR tagNameStr = L"";
                            pElem->get_tagName(&tagNameStr);
                            CString tagname(tagNameStr);
                            SysFreeString(tagNameStr);
                            tagname.MakeLower();
                            if (tagname != "input")
                            {
                                continue;
                            }
                                                            //get ID attribute
                            BSTR bstr = L"";
                            pElem->get_id(&bstr);
                            CString idStr(bstr);
                            SysFreeString(bstr);

                            if (RequiredTag(pElem))
                            {
                                AddTagToList(pElem);
                            }
                                                            //release all objects
                            pElem->Release();
                        }
                        pElemDisp->Release();
                    }
                }
            }
                            // I looked over this code snippet many times and couldn't find what I'm missing here...
            pColl->Release();
        }
        pHTMLDocument2->Release();
    }
    pDisp->Release();
}

A: Inside your loop, for each retreived element that does not have a tagname of "input" (which will be most elements), you are not calling pElem->Release() when calling continue, so you are leaking them:
if (tagname != "input")
{
    pElem->Release(); // <-- add this
    continue;
}

With that said, you should re-write your code to use ATL's smart pointer classes (CComPtr, CComQIPtr, CComBSTR, etc) to manage the memory for you so you do not have to manually release everything yourself anymore, eg:
CComPtr<IDispatch> pDisp;
pDisp.Attach(this->GetHtmlDocument());
if (pDisp.p != NULL)
{
    CComQIPtr<IHTMLDocument2> pHTMLDocument2(pDisp);
    if (pHTMLDocument2.p != NULL)
    {
        CComPtr<IHTMLElementCollection> pColl;
        pHTMLDocument2->get_all(&pColl);
        if (pColl.p != NULL)
        {
            LONG celem;
            if (SUCCEEDED(pColl->get_length(&celem)))
            {
                for (LONG i = 0; i < celem; ++i)
                {
                    VARIANT varIndex;
                    varIndex.vt = VT_UINT;
                    varIndex.lVal = i;
                    VARIANT var2;
                    VariantInit( &var2 );
                    CComPtr<IDispatch> pElemDisp;
                    pColl->item( varIndex, var2, &pElemDisp );
                    if (pElemDisp.p != NULL)
                    {
                        CComQIPtr<IHTMLElement> pElem(pElemDisp);
                        if (pElem.p != NULL)
                        {
                            CComBSTR tagNameStr;
                            pElem->get_tagName(&tagNameStr);

                            if (lstrcmpiW(tagNameStr.m_str, L"input") != 0)
                                continue;

                            CComBSTR idStr;
                            pElem->get_id(&idStr);

                            if (RequiredTag(pElem))
                                AddTagToList(pElem);
                        }
                    }
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to set Border using pseudo :hover class I am trying to set border of textbox using css but i am unable to do it. Here is my code:
<input type="email" id="email" style="display:inline-block;margin-top:10px;width:180px;height:30px;border:1px solid #cccccc;border-radius:1px;padding-left:8;padding-right:8;">
<style>
#email:hover
{
box-shadow: inset 0 0 4px rgba(192,192,192,0.4);
border:1px solid #bbbbbb;
}
</style>

But when i specify no border in inline css and then try to set border in :hover pseudo class then it works. Like this:
<input type="email" id="email" style="display:inline-block;margintop:10px;width:180px;height:30px;border-radius:1px;padding-left:8;padding-right:8;">
<style>
#email:hover
{
box-shadow: inset 0 0 4px rgba(192,192,192,0.4);
border:1px solid #bbbbbb;
}
</style>

A: You need to use an !important in your CSS rule:
#email:hover
{
    box-shadow: inset 0 0 4px rgba(192,192,192,0.4);
    border:1px solid #bbbbbb !important;
}

As inline CSS always overwrites non-!important rules.

But I encourage you to not use such a big inline styles and write it into a <style> block or better into an external file as it makes it easier to overwrite your rules without !important:
#email {
    display:inline-block;
    margin-top:10px;
    width:180px;
    height:30px;
    border:1px solid #cccccc;
    border-radius:1px;
    padding-left:8;
    padding-right:8;
}

#email:hover
{
    box-shadow: inset 0 0 4px rgba(192,192,192,0.4);
    border:1px solid #bbbbbb;
}

A: Inline CSS has higher precedence than a stylesheet/style tag precedence. One way to work around this, which is not recommended, is to change your <style> style to this:
<style>
  #email:hover {
    box-shadow: inset 0 0 4px rgba(192,192,192,0.4);
    border: 1px solid #bbbbbb !important;
  }
</style>

!important will override any other style definition.

A: because the inline style is give most importance.
if you want any other rule to overpower your inline style, use !important
 #email:hover
   {
    box-shadow: inset 0 0 4px rgba(192,192,192,0.4);
    border:1px solid #bbbbbb;!important
  }


text:
Q: How to load navbar dropdown list content in bootstrap 4? I have created a navbar with dropdown menu. When i click navbar tab that would load the content what I

        One
        Two
        Three

          Three_A
          Three_B

1

2

3a

3b

I have mentioned in href and loaded in id. But if I click dropdown list it won't work.

A: Unfortunately, Bootstrap 4 requires jQuery to work. Instead of default Bootstrap 4 you can use NgBootstrap. They have an NgbDropdown component that I was able to implement easily in my navbar

    Open Dropdown

        Link 1
        Link 2
        Link 3


text:
Q: Syntax to add a row in a table using jquery where there are a URL and apostrophes in the field Syntax to add a row in a table using jquery where there are a URL and apostrophes
Hi guys, I'm working in a table where you can add dynamically the rows in a table using jquery, the first row of my table [row0] is in the page with html5 code and there is a script that I use to add other rows, one of the fields has a button where I need to click to open a small window like you can see in the next image:
The table:
https://imgur.com/a/tXe1I
The window when I clicked in the button of the first row:
https://imgur.com/a/cRfDn
My problem begins when I try to add the others rows, my script add the rows, but I don't know how can I add the button with the URL because when I use the URL into the jquery code I can't open the window
The code of the button inside the body [row0]

        <input type="text" name='responsable0' id="responsable0" placeholder='' class="form-control" disabled=""/>

        <button type="button" class="btn btn-info glyphicon glyphicon-user" href="/Riesgos_seleccionarResponsable.asp?nombre=responsable0&registro=registro0" onclick="window.open('Riesgos_seleccionarResponsable.asp?nombre=responsable0&registro=registro0','targetWindow','toolbar=no, location=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=600, height=500');return false;"></button>

The code of my jquery script [rowN](at the moment I only can open a new blank tab)

I need to add this to the window.open() in my jquery code, how can I do it?
'Riesgos_seleccionarResponsable.asp?nombre=responsable0&registro=registro0','targetWindow','toolbar=no, location=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=600, height=500'

Thanks for your help!
Update
I have identified more about my problem, watch this:
The code of the button for the row0
The code of the button that it's added with jquery
I rewrite my code of the button added with jquery letter for letter because I saw some strange characters multiple times in the middle of the window.open statement ("& z w n j ; & # 8 2 0 3" <-- this without spaces), probably they were there because I use SublimeText and SublimeText always completes the quotation mark, but I'm not sure. I don't have strange characters now, but if you can see in my code the quatation marks is incorrect for the link. Again my code here:


text:
Q: Пропуск оператора Знающие, подскажите в чём ошибка. Задана такая задачка, надо реализовать интерфейс домашней аудио-коллекции, создал её так
struct Songs
{
    char name_autor[50];
    char name_song[50];
    double time;
};
class Audio_Collection
{
public:
    Songs audio[N];
    void set_audio();
    void print_audio();
    void sort_name_autor();
    void sort_name_song();
    void sort_time();
};

Вот реализация ф-ии ввода данных,
void Audio_Collection::set_audio()
{
    for (int i = 0; i < N; i++)
    {
        cout << "Введите имя автора(группы): ";
        cin.getline(audio[i].name_autor, 50);
        cout << "Введите название песни: ";
        cin.getline(audio[i].name_song, 50);
        cout << "Введите продолжительность трека: ";
        cin >> audio[i].time;
    }
}

И вот в чём загвоздка, при вводе данных возникает такая ошибка

При вводе второго последующих значений не выполняется строка
cin.getline(audio[i].name_autor, 50);

как это исправить?

A: Сбросьте буфер после чтения double - в нем же остается перевод строки... Добавьте после
cin >> audio[i].time;

строчку
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');


text:
Q: How to use awk to print all lines whose third column value equals "0" instead of 0? I got a csv file has following format:
"hWcYw",1,"1","5HleiJXMsFkGEsr8Jqr3Ug",1
"hWcYw",1,"1","rCDlYd2WHJuiT05sYGxaVA",2
"m1oKE",1,"0","5HleiJXMsFkGEsr8Jqr3Ug",1
"1oKE0",1,"0","rCDlYd2WHJuiT05sYGxaVA",2

I want to get lines whose third column value is "0" notice that it is "0" with quotes not 0.
i tried
awk '$3 == 0' file.csv
awk '$3 == "0"' file.csv

but doesn't work. Any ideas? Thx ahead

A: Try this:
awk -F"," '$3 == "\"0\""' file.csv

Without specifying the FS ( field separator ) the default is for awk to use white spaces, so the first problem with your attempt is that you only have one field.  Here, I'm using the -F"," to specify the FS value from the command line.  Second, you just need to escape the double quotes as double quoting can be used to make valid awk regular expression strings for pattern matching.
You could also use a different format for the pattern match where you wouldn't need to escape the double quotes you want to match on:
awk -F"," '$3 ~ /"0"/' file.csv

A: perl version:
$ perl -F, -lane   'print $_ if $F[2]=~/^"0"/' example.txt
"m1oKE",1,"0","5HleiJXMsFkGEsr8Jqr3Ug",1
"1oKE0",1,"0","rCDlYd2WHJuiT05sYGxaVA",2


text:
Q: "react - native link error File C:\Users\pc\AppData\Roaming\npm\react-native.ps1 cannot be loaded" Error message:
react-native : File C:\Users\pc\AppData\Roaming\npm\react-native.ps1 cannot be loaded. The
file C:\Users\pc\AppData\Roaming\npm\react-native.ps1 is not digitally signed. You cannot run
this script on the current system. For more information about running scripts and setting
execution policy, see about_Execution_Policies at
https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ react-native link
+ ~~~~~~~~~~~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

How can I solve this? I have installed npm, Node.js and JDK. I have done the tutorial for Okta authentication and in the step of react-native link I get this error.

A: Nothing to worry about this just run PowerShell as admin and run command below in that
steps

*

*Go to Start Menu

*Type PowerShell

*Right Click PowerShell and run as
administrator

*And Run set-executionpolicy remotesigne in
PowerShell

A: Try setting your execution policy in PowerShell to remote
signed.
Open a new PowerShell administrator window and run Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser.
There's also a way to allow running PowerShell scripts on Windows in Settings somewhere, but I don't remember where. Probably in Developer Settings.

A: Right Click PowerShell and run as administrator
And Run set-executionpolicy remotesigne in PowerShell
it worked for me.


text:
Q: On the Norm of Eisenstein integer Let us start with the set $\mathbb{Z[w]}=\{a+bw: a,b\in\mathbb{Z}\}$ where $w=(-1+i\sqrt{3})/2$. This set lies inside the set of complex numbers. Let us define the function
$$N:\mathbb{Z[w]}\to\mathbb{Z}^+\cup\{0\}$$ by $N(a+bw)=a^2+b^2-ab$. It is easy to check that for any $\alpha,\beta\in\mathbb{Z}[w]$ we have $$N(\alpha\cdot\beta)=N(\alpha)\cdot N(\beta).$$
Now, let $\alpha=a+bw$ and $\beta=c+dw$ be two elements of $\mathbb{Z}[w]$ with $\beta\neq 0$. Then
$$\frac{\alpha}{\beta}=t+sw$$ for some $t,s\in \mathbb{Q}$. Let us choose two integers $p$ and $q$ such that $|t-p|\leq\frac{1}{2}$ and $|s-q|\leq\frac{1}{2}$. Write
$$\phi=(t-p)+(s-q)w.$$
In here (please see Proposition 1.1), he wrote that $N(\phi)=(t-p)^2+(s-q)^2-(t-p)(s-q)$. I got confused with this because $t-p$ and $s-q$ may not be integers. Is there any reason how he come up with $N(\phi)$?

A: Presumably Prof. Valmir Buçaj is still alive, so you could ask him. My guess is that he likes to avoid fractions as much as possible, and though it greatly obscures things for specific examples, it perhaps simplifies the process of working out the proof of the theorem.
Declare $$\alpha = a + b \omega = \frac{2a - b}{2} + \frac{b \sqrt{-3}}{2} = \frac{v}{2} + \frac{w \sqrt{-3}}{2}$$ and $$\beta = c + d \omega = \frac{2c - d}{2} + \frac{d \sqrt{-3}}{2} = \frac{x}{2} + \frac{y \sqrt{-3}}{2}.$$ I think I did that correctly... someone will loudly point it out whatever mistake I've made in there. (Also, there is a slight inefficiency in defining $b = w$ and $d = y$, but I wanted to make the point that $\omega \neq w$).
It is assumed that $N(\alpha) \geq N(\beta)$, but if not, the Euclidean algorithm ought to switch them so that they satisfy that loose inequality. And $N(\beta)$ is easily calculated thus: $$N(\beta) = \frac{x^2}{4} + \frac{3y^2}{4}.$$ It's definitely possible that neither of those summands are integers from $\mathbb Z$. But if $x, y \in \mathbb Z$, $N(\beta)$ will work out to an integer just the same. e.g., $$N\left(\frac{5}{2} + \frac{\sqrt{-3}}{2}\right) = \frac{5^2}{4} + \frac{3 \times 1^2}{4} = \frac{25}{4} + \frac{3}{4} = \frac{28}{4} = 7.$$ This is, in my opinion, easier than calculating $N(3 + \omega)$. It also makes it much easier to locate $\beta$ in the complex plane.
Now we wish to compute $$\frac{\alpha}{\beta}.$$ Suppose $$\alpha = \frac{3}{2} + \frac{5 \sqrt{-3}}{2},$$ and $\beta$ is the same as in the previous example. Then $$\frac{\alpha}{\beta} = \frac{\frac{3}{2} + \frac{5 \sqrt{-3}}{2}}{\frac{5}{2} + \frac{\sqrt{-3}}{2}} = \ldots$$ I'm sorry, I don't feel like working out that computation, I'd rather go with $$\frac{\alpha}{\beta} = \frac{4 + 5 \omega}{3 + \omega} = \ldots$$ Yeah, that looks a bit more manageable. I'll worry about locating them in the complex plane on another occasion.


text:
Q: Chat List Ajax Functionality I have a chatbox, so when user hits post, it calls a php script to update database, and another php script located within itself to refresh the conversation to display the newly added message.
I thought about how to do this and here is how i have come about:

*

*Have ajax call on button click to POST the data needed to the first php form to update the database (No need to return anything except whether succeed or fail)

*Have e same ajax call php script located within itself to refresh the conversation (Note that this php script is located within itself as it is a loop and i use it to echo out the reply divs) in this case, page will not refresh and data can still be sent and obtained.
However, I'm not very sure how to do the second point, being call a php loop within itself to refresh the page and update the newest entry, any suggestions or would it be overly hard to do so such that i should just manually refresh the page.
To be more specific, this is the process flow of how adding a reply will work:

*

*User types reply, clicks post.

*Ajax is already attached to post button, so detects the post and fires first POST request to addchat.php

*addchat.php contains mysqli code to update the database with the data posted from the ajax, returns success or fail

*Once Ajax receives back success request, immediately fire off a command(this is what i am not very sure), that runs the php code located within the same document to echo out the newly updated chat reply (i do have timestamps in my database, so there is the ability to compare time, but note that the function is located within the same script)

*After the php code is fired again, it updates the html automatically, since its located within the same script.
I am also not possible whether this is achievable with ajax, because many others use long polling instead to keep checking the database, but because my chat system does not need that high level functionality and the replies aren't that request, so what i am doing is just to get ajax to fire off the retrieval php script whenever somebody posts a reply to update the conversation. this should be more than enough.


text:
Q: Decode Mongo 128-bit Decimal to Go In Mongodb I have this field:
units: NumberDecimal('1'),

Mapped in Go to:
Units         float64 `json:"units"`

I'm trying to read the data from Go with:
    var result dbo.Invoice
    coll := client.Database("hobbit").Collection("customer")
    filter := bson.D{{"_id", code}}
    err = coll.FindOne(context.TODO(), filter).Decode(&result)
    if err != nil {
        if err == mongo.ErrNoDocuments {
            return model.Customer{}, fmt.Errorf("invoice %s not found", code)
        }
        return model.Customer{}, fmt.Errorf("reading invoice %s from database: %s", code, err)
    }

And I get this error
Error: error un-marshalling invoice F-3945: error decoding key lines.0.units: cannot decode 128-bit decimal into a float32 or float64 type

I tried to register the conversion with bsoncodec:
registryBuilder := bsoncodec.NewRegistryBuilder()
registryBuilder.RegisterTypeMapEntry(bsontype.Decimal128, reflect.TypeOf(float64(0)))

And still getting the same error

A: It should be
Units primitive.Decimal128 `json:"units"`

That's the data type for NumberDecimal


text:
Q: Content Query fails Could you please look at my CQ. I modified ViewFieldsOverride, ListsOverride. Only the Lists works, the ViewFieldsOverride makes it

There is a problem with the query that this Web Part is issuing. Check
  the configuration of this Web Part and try again

   <webParts>
  <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
    <metaData>
      <type name="Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart, Microsoft.SharePoint.Publishing, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
      <importErrorMessage>Cannot import this Web Part.</importErrorMessage>
    </metaData>
    <data>
      <properties>
        <property name="Filter1ChainingOperator" type="Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart+FilterChainingOperator, Microsoft.SharePoint.Publishing, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c">Or</property>
        <property name="FilterOperator1" type="Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart+FilterFieldQueryOperator, Microsoft.SharePoint.Publishing, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c">Eq</property>
        <property name="Direction" type="direction">NotSet</property>
        <property name="FilterOperator3" type="Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart+FilterFieldQueryOperator, Microsoft.SharePoint.Publishing, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c">Eq</property>
        <property name="GroupByDirection" type="Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart+SortDirection, Microsoft.SharePoint.Publishing, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c">Desc</property>
        <property name="DataSourceID" type="string" />
        <property name="ChromeState" type="chromestate">Normal</property>
        <property name="SystemViewFields" type="string" />
        <property name="ListName" type="string" />
        <property name="FilterDisplayValue3" type="string" />
        <property name="FilterDisplayValue2" type="string" />
        <property name="FilterDisplayValue1" type="string" />
        <property name="FilterField1" type="string" />
        <property name="Description" type="string">Displays a dynamic view of content from your site.</property>
        <property name="DataColumnRenames" type="string" />
        <property name="MissingAssembly" type="string">Cannot import this Web Part.</property>
        <property name="PageSize" type="int">-1</property>
        <property name="ViewContentTypeId" type="string" />
        <property name="ParameterBindings" type="string" />
        <property name="HelpUrl" type="string" />
        <property name="AdditionalFilterFields" type="string" />
        <property name="DataMappingViewFields" type="string">{94f89715-e097-4e8b-ba79-ea02aa8b7adb},Lookup;{b9e6f3ae-5632-4b13-b636-9d1a2bd67120},Computed;{543bc2cf-1f30-488e-8f25-6fe3b689d9ac},Image;{fa564e0f-0c70-4ab9-b863-0177e6ddd247},Text;{691b9a4b-512e-4341-b3f1-68914130d5b2},Text;</property>
        <property name="Title" type="string">All projects6</property>
        <property name="FeedDescription" type="string" />
        <property name="UseCache" type="bool">True</property>
        <property name="XslLink" type="string" null="true" />
        <property name="AutoRefresh" type="bool">False</property>
        <property name="Filter1IsCustomValue" type="bool">False</property>
        <property name="FireInitialRow" type="bool">True</property>
        <property name="FilterValue3" type="string" />
        <property name="SortByFieldType" type="string">DateTime</property>
        <property name="ManualRefresh" type="bool">False</property>
        <property name="HelpMode" type="helpmode">Modeless</property>
        <property name="AllowConnect" type="bool">True</property>
        <property name="ItemStyle" type="string">Default</property>
        <property name="SampleData" type="string"><dsQueryResponse>
                    <Rows>
                        <Row Title="Item 1" LinkUrl="http://Item1" Group="Group Header" __begincolumn="True" __begingroup="True" />
                        <Row Title="Item 2" LinkUrl="http://Item2" __begincolumn="False" __begingroup="False" />
                        <Row Title="Item 3" LinkUrl="http://Item3" __begincolumn="False" __begingroup="False" />
                    </Rows>
                    </dsQueryResponse></property>
        <property name="FilterIncludeChildren2" type="bool">False</property>
        <property name="XmlDefinitionLink" type="string" />
        <property name="ServerTemplate" type="string">4501</property>
        <property name="TitleUrl" type="string" />
        <property name="CommonViewFields" type="string" />
        <property name="QueryOverride" type="string" />
        <property name="DataSourcesString" type="string" />
        <property name="DisplayName" type="string" />
        <property name="ListGuid" type="string" />
        <property name="DataFields" type="string" />
        <property name="ShowWithSampleData" type="bool">False</property>
        <property name="GroupByFieldType" type="string" />
        <property name="Default" type="string" />
        <property name="ViewFlags" type="Microsoft.SharePoint.SPViewFlags, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c">None</property>
        <property name="ContentTypeBeginsWithId" type="string" />
        <property name="AllowHide" type="bool">True</property>
        <property name="FeedEnabled" type="bool">False</property>
        <property name="SortBy" type="string">{8c06beca-0777-48f7-91c7-6da68bc07b69}</property>
        <property name="FilterByContextTerm" type="bool">False</property>
        <property name="TitleIconImageUrl" type="string" />
        <property name="PlayMediaInBrowser" type="bool">True</property>
        <property name="ViewFlag" type="string">0</property>
        <property name="Xsl" type="string"><xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema" version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:cmswrt="http://schemas.microsoft.com/WebPart/v3/Publishing/runtime" exclude-result-prefixes="xsl cmswrt x" > <xsl:import href="/Style Library/XSL Style Sheets/Header.xsl" /> <xsl:import href="/Style Library/XSL Style Sheets/ItemStyle.xsl" /> <xsl:import href="/Style Library/XSL Style Sheets/ContentQueryMain.xsl" /> </xsl:stylesheet></property>
        <property name="FilterField2" type="string" />
        <property name="ChromeType" type="chrometype">TitleOnly</property>
        <property name="CacheXslTimeOut" type="int">86400</property>
        <property name="AdditionalGroupAndSortFields" type="string" />
        <property name="UseSQLDataSourcePaging" type="bool">True</property>
        <property name="Height" type="string" />
        <property name="DataMappings" type="string">Description:{691b9a4b-512e-4341-b3f1-68914130d5b2},ShortComment,Text;|ImageUrl:{b9e6f3ae-5632-4b13-b636-9d1a2bd67120},EncodedAbsThumbnailUrl,Computed;{543bc2cf-1f30-488e-8f25-6fe3b689d9ac},PublishingRollupImage,Image;|Title:{fa564e0f-0c70-4ab9-b863-0177e6ddd247},Title,Text;|LinkUrl:{94f89715-e097-4e8b-ba79-ea02aa8b7adb},FileRef,Lookup;|</property>
        <property name="ListUrl" type="string" null="true" />
        <property name="ShowUntargetedItems" type="bool">False</property>
        <property name="AllowMinimize" type="bool">True</property>
        <property name="GroupBy" type="string" />
        <property name="FilterIncludeChildren1" type="bool">False</property>
        <property name="BaseType" type="string" />
        <property name="MainXslLink" type="string" />
        <property name="AsyncRefresh" type="bool">False</property>
        <property name="FilterValue1" type="string" />
        <property name="FilterValue2" type="string" />
        <property name="InitialAsyncDataFetch" type="bool">False</property>
        <property name="AutoRefreshInterval" type="int">60</property>
        <property name="Filter3IsCustomValue" type="bool">False</property>
        <property name="GroupStyle" type="string">DefaultHeader</property>
        <property name="AllowZoneChange" type="bool">True</property>
        <property name="FilterIncludeChildren3" type="bool">False</property>
        <property name="EnableOriginalValue" type="bool">False</property>
        <property name="ItemLimit" type="int">15</property>
        <property name="FilterType1" type="string" />
        <property name="UseCopyUtil" type="bool">False</property>
        <property name="FilterType3" type="string" />
        <property name="FilterType2" type="string" />
        <property name="FilterOperator2" type="Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart+FilterFieldQueryOperator, Microsoft.SharePoint.Publishing, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c">Eq</property>
        <property name="PageType" type="Microsoft.SharePoint.PAGETYPE, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c">PAGE_NORMALVIEW</property>
        <property name="FilterByAudience" type="bool">False</property>
        <property name="ItemXslLink" type="string" />
        <property name="Hidden" type="bool">False</property>
        <property name="WebUrl" type="string" />
        <property name="HeaderXslLink" type="string" />
        <property name="CacheXslStorage" type="bool">True</property>
        <property name="ListsOverride" type="string"><![CDATA[<Lists><List ID="1D0E7508-4607-4AAF-A5E9-90ADE1E84784"/><List ID="6A279AD6-A9B8-438B-8400-292A44618BF8"/></Lists> ]]></property>
        <property name="SortByDirection" type="Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart+SortDirection, Microsoft.SharePoint.Publishing, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c">Desc</property>
        <property name="Filter2IsCustomValue" type="bool">False</property>
        <property name="AllowEdit" type="bool">True</property>
        <property name="FeedTitle" type="string" />
        <property name="FilterField3" type="string" />
        <property name="MediaPlayerStyleSource" type="string" null="true" />
        <property name="DisplayColumns" type="int">1</property>
        <property name="Filter2ChainingOperator" type="Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart+FilterChainingOperator, Microsoft.SharePoint.Publishing, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c">Or</property>
        <property name="XmlDefinition" type="string" />
        <property name="WebsOverride" type="string" />
        <property name="AllowClose" type="bool">True</property>
        <property name="ContentTypeName" type="string" />
        <property name="ListId" type="System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">00000000-0000-0000-0000-000000000000</property>
        <property name="ExportMode" type="exportmode">All</property>
        <property name="NoDefaultStyle" type="string" />
        <property name="ViewFieldsOverride" type="string"><![CDATA[
            <FieldRef Name="Title" Type="Text"/>
            <FieldRef Name="Description" Type="Note"/>
            <FieldRef Name="Estimated_x0020_hours" Type="Number"/>
            <FieldRef Name="Hours_x0020_spent" Type="Number"/>
            <FieldRef Name="Author" Type="User" />
            <ListProperty Name="Title" />
            <ProjectProperty Name="Title" />
        ]]></property>
        <property name="CatalogIconImageUrl" type="string" />
        <property name="ListDisplayName" type="string" null="true" />
        <property name="Width" type="string" />
      </properties>
    </data>
  </webPart>
</webParts>

A: Remove all the whitespace from your ViewFieldsOverride property, it should be all on one line.  The following code block is taken from the SPSiteDataQuery (which is used internally to retrieve the data) during XML validation:
            try
            {
                while (SPSiteDataQuery.ReadRootXmlElement(xmlReader))
                {
                    if (xmlReader.NodeType == XmlNodeType.Element && (strTag == null || !(xmlReader.Name != strTag) || strTag2 != null && !(xmlReader.Name != strTag2) || strTag3 != null && !(xmlReader.Name != strTag3)))
                    {
                        continue;
                    }
                    SPSiteDataQuery.ReportInvalidProperty(null, strPropertyName);
                }
            }
            catch (XmlException xmlException)
            {
                SPSiteDataQuery.ReportInvalidProperty(xmlException, strPropertyName);
            }

You can see from the above, that if the XmlReader hits a newline it returns a whitespace NodeType and the method throws an exception.
Good luck.


text:
Q: Push docker image to Nexus Hello I have Jenkins and Nexus on the same server. When Jenkins build project correctly, i want push image to Nexus 3, but every time i have the same problem (log below).
Configuration:
pom.xml
<nexus.url>http://adress/#browse/browse/components:docker-image</nexus.url>

<distributionManagement>
   <snapshotRepository>
        <id>nexus</id>
        <url>${nexus.url}</url>
    </snapshotRepository>
</distributionManagement>
...
<plugins>
        <plugin>
            <groupId>org.sonatype.plugins</groupId>
            <artifactId>nexus-staging-maven-plugin</artifactId>
            <version>1.6.4</version>
            <extensions>true</extensions>
            <configuration>
              <serverId>nexus</serverId>
              <nexusUrl>${nexus.url}</nexusUrl>
              <autoReleaseAfterClose>true</autoReleaseAfterClose>
            </configuration>
        </plugin>

And i have file settings.xml:
<servers>
 <server>
    <id>nexus</id>
    <username>login</username>
    <password>password</password>
 </server>
</servers>

Then i try "mvn clean deploy" and result is:
[INFO] Deploying remotely...
[INFO] Bulk deploying locally gathered artifacts from directory:
[INFO]  * Bulk deploying locally gathered snapshot artifacts to URL http://adress/repository/image-docker/
Downloading: http://adress/repository/image-docker/someProject/0.1-SNAPSHOT/maven-metadata.xml
Uploading: http://adress/repository/image-docker/someProject/0.1-SNAPSHOT/someProject-0.1-20161213.093022-1.jar
Uploading: http://adress/repository/image-docker/someProject//0.1-SNAPSHOT/someProject-0.1-20161213.093022-1.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:58 min
[INFO] Finished at: 2016-12-13T10:30:35+01:00
[INFO] Final Memory: 75M/748M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.sonatype.plugins:nexus-staging-maven-plugin:1.6.4:deploy (injected-nexus-deploy) on project someProject:
Failed to deploy artifacts: Could not transfer artifact someProject:jar:0.1-20161213.093022-1 from/to nexus (http://adress/repository/image-docker/):
Failed to transfer file: http://adress/repository/image-docker/someProject/someProject/0.1-SNAPSHOT/someProject-0.1-20161213.093022-1.jar.
Return code is: 502, ReasonPhrase: Bad Gateway. -> [Help 1]

Every time is the same problem with 502 - Bad Gateway.
Do you have some proposal?

A: Unfortunately this will not work for a few reasons.

*

*The URL you are using as a Nexus url is wrong, that URL is the browser URL. You need to use something more akin to https://nexusurl:portofdockerhostedrepo/repository/nameofdockerhostedrepo. You can get more information on setting up and pushing Docker images here: https://books.sonatype.com/nexus-book/reference3/docker.html#docker-push

*Unless I'm completely wrong, mvn deploy is primarily for deploying maven artifacts into Maven repositories. I don't think this will work if you are attempting to deploy a Docker image. You might take a look at using something like this: https://github.com/spotify/docker-maven-plugin
Hope this helps.


text:
Q: Reactjs : Why does Children.count(children) is always 0 I have to build a custom slider in reactjs wherein the count of child component is always 0.I'm fetching the images from the API and passing them from the parent component to the child component.When I pass the images statically the slider works fine and count of the children is exactly the same as the number of images.Here is my code
MainBanner Component
import React from "react";
import {connect} from 'react-redux';
import {Link} from 'react-router-dom';
import SlideShow from './SlideShow';
import {getBannerImages} from '../actions/landingPageActions';
import {getMainBannerImages} from '../selectors';

class MainBanner extends React.Component{

  componentDidMount(){
    this.props.getBannerImages();
  }

  render(){
    const {bannerImages} = this.props
    return(

          <SlideShow>
          {bannerImages && bannerImages.map((image,i)=>
            <img key={i} src={`${image.mainbannerimages}`} alt="main banner" width="100%" height="350px" />
          )}
          </SlideShow>

    );
  }
}

function mapStateToProps(state){
  return {
    bannerImages:getMainBannerImages(state)
  }
}

export default connect(mapStateToProps,{getBannerImages})(MainBanner);

Child Component (Slider)
import React, { Component, Children } from 'react';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';

class SlideShow extends Component {
  constructor(props){
    super(props);
    this.leftSlide=this.leftSlide.bind(this);
    this.showNext=this.showNext.bind(this);
    this.state = {
      total: 0,
      current: 0,
    }
  }

  componentDidMount() {
    const { children } = this.props;
      console.log(Children.count(children));
    this.setState({ total: Children.count(children) });
    this.interval = setInterval(this.showNext, 5000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  showNext = () => {
    const { total, current } = this.state;
    console.log(total);
    this.setState({
      current: current + 1 === total? 0 : current + 1
    });
  };

  leftSlide=()=>{
    const { total, current } = this.state;
    this.setState({
      current: current - 1 <= 0 ? 0 : current - 1
    });
    console.log(this.state.current);
  }

  render() {
    const { children } = this.props;
    const bullets = Array(this.state.total).fill("○");
    bullets[this.state.current] = "●";
    return (

        <ReactCSSTransitionGroup
          className="group"
          transitionName="bannerSlideTransistion"
          transitionEnterTimeout={800}
          transitionLeaveTimeout={800}>
          {Children.toArray(children)[this.state.current]}
        </ReactCSSTransitionGroup>

    )
  }
}

export default SlideShow;

Thanks in advance.

A: Answering the question

Why does Children.count(children) is always 0

Because it's supposed to return 0.
This is caused due to component's lifecycle. You mount the SlideShow component on render, before even having the data fetched from the API. You try to pass along with it, some images, although because you don't have them fetched yet, they simply aren't rendered. Meaning, at the moment of SlideShow mount, it has no children at all.
When you receive a response back from the server, your SlideShow component is being updated, with provided, mapped images.
If you wanna catch the moment of the update, I recommend you using componentWillReceiveProps function. Which takes an argument, new props object.
https://reactjs.org/docs/react-component.html#componentwillreceiveprops
componentWillReciveProps(newProps) {
  this.setState((state) => ({
    total: Children.count(newProps.children)
  }))
}

Although, I'm not completely convinced whether you actually would need the value, to be stored in your component's state. I'd recommend you to get the count value at the showNext. That way, it would always be up to date, and I don't really see any benefit from storing it locally.


text:
Q: Freshdesk api call returning limited number of tickets I'm trying to fetch ticket details using requests library of python. Here is the command.
r = requests.get("https://"+ domain +".freshdesk.com/api/v2/tickets?updated_since=2015-01-19T02:00:00Z", auth = (api_key, password))

But, I'm just getting latest 30 tickets details.
I tried changing the date and also tried removing it, but nothing seems to work and everytime only last 30 tickets details are coming.

A: It's due to pagination limit set by Freshdesk.
Refer: https://developers.freshdesk.com/api/#pagination
The 'link' header in the response will hold the next page URL if exists. If you have reached the last page of objects, then the link header will not be set.
Example:
Headers:
"link":< https://domain.freshdesk.com/api/v2/tickets?filter=all_tickets&page=2>;rel="next"

A: 100 per page is very less compared to 8000 that Jira Service Desk can handle. Freshdesk APIs are still primitive and when I checked with their support, I was told that we have to live with what Freshdesk provides and find our own ways to improvise.
I'm looking at fetching all tickets nearing SLA breach and apparently there is no way to get this through APIs. I have to look at all open tickets, 100 at a time to get this list.


text:
Q: In Answer Set Programming, what is the difference between a model and a least model? I'm taking an artificial intelligence class and we are working with Answer Set Programming (Clingo specifically). We're talking mostly theory at the moment and I am having some trouble differentiating between models and least models. I have the following definitions:

Satisfying rules, models, least models and answer sets of definite
  program

*

*A program is called definite if it does not have "not" in the body of its rules.

*A set S is said to satisfy a rule of the form  a :- b1, …, bm, not c1, …, not cn. if  its body is satisfied by S (I.e., b1 … bm are in S
  and none of c1 ... cn are in S) implies that its head must be
  satisfied by S (i..e, a is in S).

*A set S is said to satisfy a program if it satisfies all rules of that program.

*A set S is said to be an answer set of a definite program P if  (a) S satisfies P (also referred to as S is a model of P)  and (b)  No
  strict subset of S satisfies P (i.e., S is the least model of P).

With the question (pulled from the lecture slides, not homework):
P is defined as:
a :- b,e.
b.
c :- d,b.
d.

Which of the following are models and least models?
{}, {b}, {b,d}, {b,d,c}, {b,d,c,e}, {b,d,c,e,a}

Can anyone let me know what the answer to the above question is? I can probably figure out the difference from there, although if someone could explain the difference in common speak (rather than text-book definition), that would be wonderful. I'm not sure which forum to post this question under - please let me know if it should be posted somewhere else.
Thanks

A: First of all, note that this section of your slides is talking about the answer sets of a positive program P (also called a definite program), even though it mentions also not. The positive program is the simple case, as for a positive program P there always exists a unique least model LM(P), which is the intersection of all it's models.
Allowing not rules in the rule bodies makes things more complex. The body of a rule is the right side of :-.
The answer to the question would be, set by set:

*

*S={} is not a model, since b and d are facts b. d.

*S={b} is not a model, since d is a fact d.

*S={b,d} is not a model, since c is implied by c :- d,b. and c is not in S

*S={b,d,c} is a model

*S={b,d,c,e} is not a model, since a is implied by a :- b,e. and a is not in S

*S={b,d,c,e,a} is a model
So what is the least model? It's S={b,c,d} since no strict subset of S satisfies P.
We can arrive to the least model of a positive program P in two ways:

*

*Enumerate all models and take their intersection (here {b,c,d}∩{a,b,c,d,e}={b,c,d}).

*Starting with the facts (here b. d.) and iteratively adding implied atoms (here c :- b,d.) to S, repeating until S is a model and stopping at that point.

Like your slides say, the definition of an answer set for a positive program P is: S is an answer set of P if S is the least model of P. To be stricter, this is actually if and only if, since the least model LM(P) is unique.
As a last note, so you are not later confused by them, a constraint :- a, b is actually just shorthand for x :- not x, a, b. Thus programs containing constraints are not positive programs; though they might look like they are at first, since the body of a constraint seemingly doesn't contain a not.


text:
Q: How to resolve AWS HTTP error: cURL Error 7 CURLE_COULDNT_CONNECT I'm creating a website on Symfony 4.
I've download aws/aws-sdk-php package to connect to aws3 and league/flysystem-aws-s3-v3 to upload file.
Trying to add a picture to AWS S3 bucket I get this error :

Error executing "ListObjects" on "https://sftest-jobboard.s3.eu-west-3.amazonaws.com/?prefix=company%2Ffouquet%2Favatar%2Favatar-org-5de7c60517092.png%2F&max-keys=1&encoding-type=url"; AWS HTTP error: cURL error 7:  (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)

In Service.yaml
Aws\S3\S3Client:
        arguments:
            -
                version: 'latest'
                region: 'eu-west-3'
                credentials:
                    key: '%env(AWS_S3_ACCESS_ID)%'
                    secret: '%env(AWS_S3_ACCESS_SECRET)%'

My IAM User policy
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket",
                "s3:GetObject",
                "s3:GetObjectAcl",
                "s3:PutObject",
                "s3:PutObjectAcl",
                "s3:ReplicateObject",
                "s3:DeleteObject"
            ],
            "Resource": [
                "arn:aws:s3:::sftest-jobboard",
                "arn:aws:s3:::sftest-jobboard/*"
            ]
        }
    ]
}

This configuration works in localhost but it doesn't work anymore when I deploy my site on OVH.
I'have tried all the solutions proposed in this topic : How to resolve cURL Error (7): couldn't connect to host? but nothing works.


text:
Q: Is it MVC when the view doesn't interact with the model? I've designed an MVC (in .NET) where the View has no link to the Model.  It only knows about the Controller.  The traditional MVC pattern has all parts communicating with each other.  In my case, the Controller is basically a mediator.  This keeps any exceptions or logic out of the View.  It has zero dependency on the Model.  Is this no longer an MVC?

A: What you are describing is actually a subset of Model-View-Controller called Passive View.

Passive View is yet another variation
  on model-view-controller and
  model-view-presenter. As with these
  the UI is split between a view that
  handles display and a controller that
  responds to user gestures. The
  significant change with Passive View
  is that the view is made completely
  passive and is no longer responsible
  for updating itself from the model. As
  a result all of the view logic is in
  the controller. As a result, there is
  no dependencies in either direction
  between the view and the model.

Martin Fowler talks about it in the above link and briefly discusses other variations here.

A: I guess rather than MVC, it's just VC then, eh? ;)
In MVC implementations, the view subscribes to changes in the model, and acts on the controller; the controller makes changes on the model, which get propagated to the views by way of their reference to the model.  In your case, it sounds more like you've buried your model in your controller (after all, you've got to get your data from somewhere); that's not necessarily bad or anything, but it's also not MVC in the strict sense.

A: In the strictest of sense, no. But does it have a WAY for the view to communicate with the Model if needed without changing the architecture/interfaces?
[For instance if you have a TalkToModel() method implemented, even though you dont use it YET, its an MVC in my view.]

A: Your approach seems a lot like MVP, but I couldn't say for sure without more details.


text:
Q: PowerMockito: java.lang.NoSuchMethodError while mocking static method using PowerMickito I am trying to mock static method
PowerMockito.mockStatic(ABC.class);
Mockito.when(ABC.selectSingleValue(any(java.sql.Connection.class), any(String.class), Matchers.<Object>anyVararg())).thenReturn("TestStatic");

Below is the exception which i am getting:
java.lang.NoSuchMethodError: org.mockito.internal.matchers.LocalizedMatcher.getMatcher()Lorg/mockito/ArgumentMatcher;
    at org.powermock.api.mockito.internal.invocation.PowerMockMatchersBinder.extractArgumentMatchers(PowerMockMatchersBinder.java:60)
    at org.powermock.api.mockito.internal.invocation.PowerMockMatchersBinder.bindMatchers(PowerMockMatchersBinder.java:44)
    at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:59)
    at org.powermock.api.mockito.internal.invocation.MockitoMethodInvocationControl.performIntercept(MockitoMethodInvocationControl.java:275)
    at org.powermock.api.mockito.internal.invocation.MockitoMethodInvocationControl.invoke(MockitoMethodInvocationControl.java:201)
    at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:173)
    at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:155)
    at org.powermock.core.MockGateway.methodCall(MockGateway.java:132)
    a

A: I was using PowerMock 1.7.4, while using Mockito 2.22.0. I resolved the issue by consulting the compatibility table and seeing that I had to downgrade Mockito to 2.8.9. Once I did, the exception stopped appearing.

A: Looking at doc for latest stable release on maven central:
doc for 1.10.19
There is no getMatcher method.
It seems it has been added later in the beta version as you can see from
this doc for 2.0.40-beta
getMatcher
    public ArgumentMatcher getMatcher()

A: It's a version compatibility issue. If you're using Mockito 1.10.8 - 1.10.x, the you should use module powermock-api-mockito 1.6.2.
If you want use Mockito 2 (looks like you use it), then you should use module powermock-api-mockito2. it's recommended to use PowerMock 1.7.0RC4.
More information about version compatibility you may find here


text:
Q: Update a section of a web page with a JSON object without updating the entire page using Node.js and Express I'm using Node.js and Express along with a Chrome Browser. I'm displaying a web page that contains a table with 7 columns that is empty and a number of buttons below the table to perform different actions.
Presently I can press a button on the web page, create a route, process the route in a *.js file. In the *.js file I'm reading a file that is in JSON format. After getting the file and converting the file to a JSON object I'm extracting some of the data from the JSON object, adding the appropriate HTML (ex. td) and creating a string. Then I'm calling res.render, passing the string to TableData to update the table which redraws the entire web page with the JSON data filled in the table. This is working.
What I want to do, for a lack of a better term, is to pass (post, generate an event) the JSON object that I created in the *.js file so that the Browser could process the JSON object in the *.ejs file in a script and update the table. I really don't want to redraw the entire web page like I'm presently doing. I only want to update the table, not the web page and I can't see how I can make that work if I'm using res.render. I looked into res.send, res.write and other options and nothing seems to work.
I can't see the mechanism that would allow me to take the JSON object and somehow have a script on the *.ejs file pick up the event of the JSON object being created and processing that object. Is there any way to do this?
Below is some of the relevant code.
This is the test_data_02.ejs file for the table

                Description
                Location
                Device Class
                Node
                Slot
                Address
                Type/Tag

                Description
                Location
                Device Class
                Node
                Slot
                Address
                Type/Tag

            <%- TableData %>

                Description
                Location
                Device Class
                Node
                Slot
                Address
                Type/Tag

I'm filling in TableData with the string generated from the JSON object.
Here is the html button
        <input class="LSNButton1" type="button" style="color:black; background:green;" value="Extra A" onclick="window.location.href = '/get_extra_02a'" />

Here is the code I'm currently using to process the route and fill the table. The exports.getExta02B ... should be in the code section but every time I paste it in it doesn't get included.
exports.getExtra02B = (req, res) => {
    console.log("getExtra02B - step 1");

    let file_path = "C: ... \\BINARY_s.json";
    console.log(`file_path ${file_path}`);

    fs.readFile(file_path, (error, data) => {
        console.log("getExtra02B - step 2");

        let json_data = JSON.parse(data);

        console.log("getExtra02B - step 4");

        var testData = "";

        console.log(`Zones length: ${json_data.zones.length}`);

        for (var i = 0; i < json_data.zones.length; i++) {
            for (var j = 0; j < 7; j++) {
                switch (j) {
                    case 0:
                        testData += "
" + json_data.zones[i].description + "	";
                        break;
                    case 1:
                        testData += "" + json_data.zones[i].location + "	";
                        break;
                    case 2:
                        testData += "" + json_data.zones[i].zone_class + "	";
                        break;
                    case 3:
                        testData += "" + json_data.zones[i].zone_node + "	";
                        break;
                    case 4:
                        testData += "" + json_data.zones[i].zone_slot + "	";
                        break;
                    case 5:
                        testData += "" + json_data.zones[i].zone_address + "	";
                        break;
                    case 6:
                        testData += "" + json_data.zones[i].zone_device_type + "
";
                        break;
                    default:
                        break;
                }
            }
        }

        res.render("test_data_02", {
            TableData: testData,
            domain: "2020"
        });
    });

    console.log("getExtra02B - step 3");
}

Again, I would like to know if it's possible to pass (for a lack of a better term) the JSON object in some way to the *.ejs file and somehow a script in the *.ejs could sense an event and process the JSON object to allow the script to update the table on the web page.
Thanks for any help!


text:
Q: Мне надо чтобы окно python tkinter нельзя было свернуть Я делаю блокировку окна windows, и при нажатии на кнопку Пуск, можно закрыть программу и все будет не по плану, как можно сделать чтобы нельзя было нажать кнопку Пуск во время работы программы?
d1 = datetime.datetime.today()
root = tk.Tk()
root.overrideredirect(1)
root.protocol("WM_DELETE_WINDOW", Quit)
root.geometry("1950x1050")
root.title("Stop!")
label = tk.Label(root, text = f"Сейчас времени: {d1.hour}:{d1.minute}").pack()
root.mainloop()


text:
Q: ArrayList of ArrayLists for pegs and discs in towers of hanoi game I am building a towers of hanoi game that can be played from the console or the command line.  Note this isn't a recursive program; I am trying to build a GAME that can be played by the user.  I am using an ArrayList of ArrayLists to store the pegs(1,2,3) and the discs(N) chosen by the user.
My instance variables and constructor:
private ArrayList lists;
private ArrayList peg1 = new ArrayList<>();
private ArrayList peg2 = new ArrayList<>();
private ArrayList peg3 = new ArrayList<>();

//Constructor
public TowersOfHanoi() {

   ArrayList<Integer>[] lists = new ArrayList[3];
   lists[0]= this.peg1;
   lists[1]= this.peg2;
   lists[2]= this.peg3;

}

How I initialize the game
public ArrayList initializeGame(int n) {

    for (int i = 1; i < n; i++) {
        peg1.add(i);
        }
}

I am trying to make a move method that will take two INTS as parameters for the from and to posts.  I.E. user moves disc from post N to post N, and checks if that move is legal.
I have tried to figure this out for the last couple hours but I can't even figure out how to get the appropriate peg and move the disk from one peg to another let alone check to see that a larger disk isn't being moved on top of a smaller disk.  This is the method I came up with and I am getting a null pointer exception which makes me think that lists is not initialized correctly.  This is the method I have which is obviously wrong.
public void move(int moveFrom, int moveTo){

    lists.get(moveTo)
    lists.add(0, moveTo);
}

So can anyone help me understand how to use an int as an index to get the appropriate peg (int is entered by user) and move a disc?

A: lists is not being initialized because you declare an instance object of type ArrayList
private ArrayList lists;

Which is null.  Then, in your constructor, you declare and initialize a local object of type ArrayList[] - as in an array of ArrayLists
ArrayList<Integer>[] lists = new ArrayList[3];

You then put your pegs into this array of ArrayList's
lists[0]= this.peg1;
lists[1]= this.peg2;
lists[2]= this.peg3;

and then you exit the constructor without doing anything with the array.  You need to either:
private ArrayList[] lists;
private ArrayList peg1 = new ArrayList<>();
private ArrayList peg2 = new ArrayList<>();
private ArrayList peg3 = new ArrayList<>();

//Constructor
public TowersOfHanoi() {

   lists = new ArrayList[3];
   lists[0]= this.peg1;
   lists[1]= this.peg2;
   lists[2]= this.peg3;

}

OR
private ArrayList<ArrayList> lists = new ArrayList<>(3);
private ArrayList peg1 = new ArrayList<>();
private ArrayList peg2 = new ArrayList<>();
private ArrayList peg3 = new ArrayList<>();

//Constructor
public TowersOfHanoi() {

   lists.add(this.peg1);
   lists.add(this.peg2);
   lists.add(this.peg3);

}

OR most likely
private ArrayList[] lists = new ArrayList[3];
private ArrayList peg1 = new ArrayList<>();
private ArrayList peg2 = new ArrayList<>();
private ArrayList peg3 = new ArrayList<>();

//Constructor
public TowersOfHanoi() {

   lists[0]= this.peg1;
   lists[1]= this.peg2;
   lists[2]= this.peg3;

}


text:
Q: Django multiple queries with foreign keys Let's say I have two different apps :
teacher/models.py:

  Teacher(models.Model):
     name = models.CharField(max_length=300)

class/models.py:

  Class(models.Model):
     name = models.CharField(max_length=300)
     teacher = models.ForeignKey(Teacher)
     students = models.ManyToManyField(Student)

I want to get all the teachers with classes and all classes attached.
The result I want:
{[
   teacher: '3L' #Teachers Id
   classes: ['20L','14L','30L'] #list of Class objects or ids with the above teacher
],
[# similar to above]

}

Is this possible to do? This is what I am currently doing:
classes = Class.objects.all()
teachers = Teacher.objects.filter(id__in=classes.value_list('teacher',flat=True).distinct())
for teacher in teachers:
    classes_for_teachers = classes.objects.filter(teacher=teacher)

In the above code, there are four queries made with a loop which certainly increases the time complexity. Is there a better solution to this? Thanks in advance.

A: Use prefetch_related:
teachers = Teacher.objects.prefetch_related('class_set')

# what you want is not a valid Python structure (set of lists (looking like dicts))
# list of dicts makes more sense
result = [
    {'teacher': t.pk, 'classes': t.class_set.all()}
    for t in teachers
]

This will only trigger 2 db queries regardless of how many teachers and classes there are.


text:
Q: How do extract multiple words on one line in sys.stdin in Python? Suppose I have the following:
>>> import sys
>>> a = []
>>> for line in sys.stdin.readline():
...     a.append(line.strip())
...
hello jerry!
>>> a
['h', 'e', 'l', 'l', 'o', '', 'j', 'e', 'r', 'r', 'y', '!', '']

But I would like to end up with is a list like this:
>>> a
['hello', 'jerry!']

A: sys.stdin.readline() returns a string not list of lines. So you are iterating over characters of that string not lines. Change your code to this:
>>> import sys
>>> a = []
>>> for word in sys.stdin.readline().split():
...     a.append(word)
...
hello jerry!
>>> a
['hello', 'jerry!']


text:
Q: QGIS rotate CRS around a new centre I've been given some NetCDF data in a Mercator projection with a centre longitude of 173.9581, centre latitude of -41.0870 and rotation of 40 degrees. I have tried to create a new CRS based on Mercator41 (a NZ equivalent) and rotate it using the PROJ option in QGIS 3.16.11 but I get an error saying CRS matches the world Mercator EPSG. I have then tried using WKT script, and found reference to affine transformations, but the answers I have found here use a corner reference not a central pole. How would I rotate it by 40 deg? And is the lat long of natural origin where I set the central coordinates?
PROJCRS["WGS 84 / Mercator 41",
    BASEGEOGCRS["WGS 84",
        ENSEMBLE["World Geodetic System 1984 ensemble",
            MEMBER["World Geodetic System 1984 (Transit)"],
            MEMBER["World Geodetic System 1984 (G730)"],
            MEMBER["World Geodetic System 1984 (G873)"],
            MEMBER["World Geodetic System 1984 (G1150)"],
            MEMBER["World Geodetic System 1984 (G1674)"],
            MEMBER["World Geodetic System 1984 (G1762)"],
            ELLIPSOID["WGS 84",6378137,298.257223563,
                LENGTHUNIT["metre",1]],
            ENSEMBLEACCURACY[2.0]],
        PRIMEM["Greenwich",0,
            ANGLEUNIT["degree",0.0174532925199433]],
        ID["EPSG",4326]],
    CONVERSION["Mercator 41",
        METHOD["Mercator (variant A)",
            ID["EPSG",9804]],
        PARAMETER["Latitude of natural origin",-41.0870,
            ANGLEUNIT["degree",0.0174532925199433],
            ID["EPSG",8801]],
        PARAMETER["Longitude of natural origin",173.9581,
            ANGLEUNIT["degree",0.0174532925199433],
            ID["EPSG",8802]],
        PARAMETER["Scale factor at natural origin",1,
            SCALEUNIT["unity",1],
            ID["EPSG",8805]],
        PARAMETER["False easting",0,
            LENGTHUNIT["metre",1],
            ID["EPSG",8806]],
        PARAMETER["False northing",0,
            LENGTHUNIT["metre",1],
            ID["EPSG",8807]]],
    CS[Cartesian,2],
        AXIS["easting (X)",east,
            ORDER[1],
            LENGTHUNIT["metre",1]],
        AXIS["northing (Y)",north,
            ORDER[2],
            LENGTHUNIT["metre",1]],
    USAGE[
        SCOPE["Topographic mapping (medium and small scale)."],
        AREA["Southwestern Pacific Ocean and Southern Ocean areas surrounding New Zealand."],
        BBOX[-60,155,-25,-170]],

A: I suggest to use a hotine oblique mercator
WKT
PROJCRS["WGS 84 / NZ Oblique Mercator",
BASEGEOGCRS["WGS 84",
    DATUM["World Geodetic System 1984",
        ELLIPSOID["WGS 84",6378137,298.257223563,
            LENGTHUNIT["metre",1]],
        ID["EPSG",6326]],
    PRIMEM["Greenwich",0,
        ANGLEUNIT["degree",0.0174532925199433],
        ID["EPSG",8901]]],
CONVERSION["NZ Oblique Mercator",
    METHOD["Hotine Oblique Mercator (variant B)",
        ID["EPSG",9815]],
    PARAMETER["Latitude of projection centre",-41.087,
        ANGLEUNIT["degree",0.0174532925199433],
        ID["EPSG",8811]],
    PARAMETER["Longitude of projection centre",173.9581,
        ANGLEUNIT["degree",0.0174532925199433],
        ID["EPSG",8812]],
    PARAMETER["Azimuth of initial line",40,
        ANGLEUNIT["degree",0.0174532925199433],
        ID["EPSG",8813]],
    PARAMETER["Angle from Rectified to Skew Grid",40,
        ANGLEUNIT["degree",0.0174532925199433],
        ID["EPSG",8814]],
    PARAMETER["Scale factor on initial line",1,
        SCALEUNIT["unity",1],
        ID["EPSG",8815]],
    PARAMETER["Easting at projection centre",0,
        LENGTHUNIT["metre",1],
        ID["EPSG",8816]],
    PARAMETER["Northing at projection centre",0,
        LENGTHUNIT["metre",1],
        ID["EPSG",8817]]],
CS[Cartesian,2],
    AXIS["(E)",east,
        ORDER[1],
        LENGTHUNIT["metre",1,
            ID["EPSG",9001]]],
    AXIS["(N)",north,
        ORDER[2],
        LENGTHUNIT["metre",1,
            ID["EPSG",9001]]]]


text:
Q: In AngularJS, how do you find all the scopes on a page? Once we have a scope in hand, we can navigate to its root and explore the scope hierarchy.
But is there a direct way to find all the scopes on a page?
Likewise given an HTML element, is there a direct way to find its enclosing scope?

A: you can see all of the scopes on the page using this CSS selector
.ng-scope { border: 1px solid red; }

and all of the bindings:
.ng-binding { border: 1px solid red; }

You can then retrieve them by converting the DOM element into selector
var selector = angular.element(some_dom_element);

Then use the selector to retrive the scope/controller/injector
var scope = selector.scope();
var controller = selector.controller();
var injector = selector.injector();

A: You can find out a scope for element using:
$(element).scope()

or
angular.element(element).scope()

I don't think there is a way to get all scopes on a page easily (other than navigating down from root scope).

A: You should develop your application in Google Chrome browser (if you are not using it already) and than you can use awesome Batarang extension that adds new dedicated AngularJS panel to the Developer tools.
You can see all the scopes there, what is the relationships between them and what value have all its attributes.
http://blog.angularjs.org/2012/07/introducing-angularjs-batarang.html

A: Not all scopes are bound to elements. If you want all scopes on the page, walk the scope tree like this:
function getScopes(root) {
    var scopes = [];

    function visit(scope) {
        scopes.push(scope);
    }
    function traverse(scope) {
        visit(scope);
        if (scope.$$nextSibling)
            traverse(scope.$$nextSibling);
        if (scope.$$childHead)
            traverse(scope.$$childHead);
    }

    traverse(root);
    return scopes;
}

getScopes($rootScope)

A: I don't know why this would be useful to you, but you can do this:
scopeElements = document.getElementsByClassName('ng-scope');
scopes = [].map.call(scopeElements, function(e){ return angular.element(e).scope(); })

The other option is to traverse the scope tree starting at the root scope using our private apis: $$childHead and $$nextSibling.
It's more likely that you just want to see where the scope boundaries are and you can do it with this:
scopeElements = document.getElementsByClassName('ng-scope');
angular.element(scopeElements).css('border', '1px solid red');

Then you can just use web inspector to select an element of interest and get its scope by:
angular.element($0).scope();

A: I recommend AngularJS Batarang.  It's a debugging tool that lets you visualize all the scopes on the page (among other things).
https://github.com/angular/angularjs-batarang

A: In Chrome, using developer tools.  I use the console command line.
Pick an element in the HTML panel of the developer tools and type this in the console:
angular.element($0).scope()

or just right click on a page element and select: inspect element.
$($0).scope() will return the scope associated with the element. You can see its properties right away.
To view an elements parent scope:
$($0).scope().$parent

You can chain this also:
$($0).scope().$parent.$parent

You can look at the root scope:
$($0).scope().$root

If you highlighted a directive with isolate scope, you can look at it with:
$($0).isolateScope()

If available, you can do the same with child scope and sibling scope.
$($0).scope().$sibling

I can walk up and down the scopes to verify what scope has what controllers, objects, etc and when you are working with custom directives, it's essential. In a large code base, it's not so easy to find things like this.
Recently, I had two controllers with the same name, save for one uppercase letter attached to a view.  I was using the wrong controller and it took a while before I realized that was the issue with my bindings.

A: In Angulars there is $rootScope, which is the root of every scope.It has child field and whole hierarchy is inside $rootScope.If you want to find a scope with html element,you will probably have a problems,because that scope can be Isolated scope.Maybe you have a directive there,which scope is isolated.If you have anything like that,try to use el.isolatedScope()


text:
Q: 'memcpy' was not declared in this scope when using gcc compiler Actually I'm trying to compile a c/c++ project with mingw. The same project is actually compiled with visual studio compiler. For this purpose, I have written a makefile and everything works so far.
During compiling I get error regarding functions which are declared withing string.h and stdio.h like memcpy() , printf()..., with following error:
error: 'memcpy' was not declared in this scope

That's  because the compiler didn't find the functions. When compiling within visual studio, this error didn't appear, logically, because of compiler include paths like:
c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\

My question now is:
What should I do in my makefile to tell the compiler to use the "string.h" and "stdio.h" functions from the mingw. I tried to put the include path in the makefile, like:
 INCLUDE_DIRS =\
 C:\MinGW\include

but it has no effect.
And also, there is a difference between the string.h and stdio.h from visual studio and string.h and stdio.h used by gcc. Can this be a problem?

A: The correct way would be to add these includes to the source files where you use methods which are defined in them.
But if you insist to include it through the makefile, you can use force include.
Visual studio link.

To set this compiler option in the Visual Studio development
  environment Open the project's Property Pages dialog box.
Open Project Property Pages.
Click the C/C++ folder.
Click the Advanced property page.
Modify the Force Includes property.

or use -include path_to_the_header for gcc
Just add this option to the compilation command line. Good luck.


text:
Q: Use NPM with zsh shell in ubuntu windows 10 So I recently started using the zsh to code in python, i had to configure the environment variables for it and now im trying to start a small project in javascript and it won't let me use npm.
Trying to initialize the repo will throw this error at me:
npm init -y
zsh: /mnt/c/program files/nodejs//npm: bad interpreter: /bin/sh^M: no such file or directory

And of course it won't let me install packages.
Any suggestions? as I didn't find anything that could help me solve the problem.

A: Ok looks like what i had to do is install nodejs back again as this is a new shell, zsh didn't have it installed: If anyone has a similar issue you might wanna try the following :
curl -sL https://deb.nodesource.com/setup_15.x | sudo -E bash -
sudo apt-get install -y nodejs

and then

sudo apt-get install -y nodejs


text:
Q: What listbox event should I use to set scroll position on my page, I have a listbox in an update panel.  I am successfully trapping the scroll position, however when the update panel refreshes, I'm having trouble finding a suitable javascript event in which to call my function to set the scroll position.  Any ideas?
i had really hoped that "onAfterUpdate" was going to work, but no...

A: After the request and UpdatePanel is finished you can tap into the PageRequestManager and fire your own delegate:
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

function EndRequestHandler(sender, args)
{
   //your code here
}
</script>


text:
Q: Using jQuery function inside AngularJS controller I needed to initialize a jQuery plugin on all elements with a certain class name which comes inside an ng-repeat loop. These elements are loaded via angularjs $http get method.
var app = angular.module('myApp', []);

app.controller('myController', function($scope, $http) {
    $http.get('get_item.php').success(function(response) {
        $scope.items = response;
        angular.element('.make-switch').bootstrapSwitch(); // jQuery plugin code
    });
});

But this doesn't work.
I tried $('.make-switch').bootstrapSwitch(); also. Please help.

A: Create a directive and so you can initialize the plugin in your markup:

I think you creates your elements dynamicly with the scope variable $scope.items, something like that:

...just add the attribute bootstrapswitch to initialize the switch on your loaded elements.
...your directive could look like that:
app.directive('bootstrapswitch', [function() {
   return {
      restrict: 'A',
      link: function(scope, elem, attrs) {
         $(elem).bootstrapSwitch();
      }
   };
}]);

A: Actually, if you want to call any jQuery plugins inside angular code you can do this also with angular. It has built in jQuery called jqLite, and you can call this as angular.element("selector") which returns you a jQuery element. As a selector you can use any jQuery/css selectors you like.
By the way, calling jQuery directly in angular code like $("selector").method() is a bad practise. You should use only your angular jqLite functionallity

A: It not a pretty good idea to manipulate view using jQuery library inside Angular controller.
Actually jQuery is grabbing or injecting into your DOM based on events.But Angular doesn't act the same way, it manipulate view based on true/false nature.
Best alternative way is try to make directive or use angular-bootstrap-switch library.


text:
Q: if-else statement undefined object Some weird stuff is happening:
JSON:
{
    "all": {
        "id": [
            "64",
            "65"
        ],
        "code": [
            "AqCeTZ3Q",
            "CTRtldIw"
        ],
        "file_match": [
            "voorbeeld.php",
            "Handeler.rar"
        ],
        "file_size": [
            "30",
            "146693"
        ],
        "expire": [
            "1386543600",
            "1386543600"
        ],
        "ip": [
            "dada",
            ""
        ],
        "can_used": [
            "0",
            "1"
        ],
        "opmerking": [
            "",
            ""
        ]
    },
    "id": [
        "65"
    ],
    "active": {
        "code": [
            "CTRtldIw"
        ],
        "file_match": [
            "Handeler.rar"
        ],
        "file_size": [
            "146693"
        ],
        "expire": [
            "1386543600"
        ],
        "ip": [
            ""
        ],
        "can_used": [
            "1"
        ],
        "opmerking": [
            ""
        ]
    },
    "expired": {
        "id": [
            "64"
        ],
        "code": [
            "AqCeTZ3Q"
        ],
        "file_match": [
            "voorbeeld.php"
        ],
        "file_size": [
            "30"
        ],
        "expire": [
            "1386543600"
        ],
        "ip": [
            "dada"
        ],
        "can_used": [
            "0"
        ],
        "opmerking": [
            ""
        ]
    }
}

Script 1 (works):
function update() {
    var value = document.getElementById("chooser").value;
    $.ajax({
    url: "./json.php",
    dataType: 'json',
    success: function(data, value) {

                alert(data.all.id);

            }
        });
    }

Output: alert with a value: 64,65. Correct!
Script 2: (works not, I dont know why.)
function update() {
    var value = document.getElementById("chooser").value;
    $.ajax({
    url: "./json.php",
    dataType: 'json',
    success: function(data, value) {
            if(value == all) {
                alert(data.all.id);
            } else if (value == active) {
                alert(data.active.id);
            } else { // expired
                alert(data.expired.id);
                }
            }
        });
    }

Error: Uncaught ReferenceError: all is not defined. (when value == all)
So, I have no idea why the script is broken when I add an statement. Does anybody know why this is not working and how to fix it?

A: If you want to use the value retrieved before the ajax in the ajax handler you have to not have any other variables with the same name in its scope to override it, i.e. remove the value parameter from the success handler.
function update() {
    var value = document.getElementById("chooser").value;
    $.ajax({
    url: "./json.php",
    dataType: 'json',
    success: function(data) {
            if(value == "all") {
                alert(data.all.id);
            } else if (value == "active") {
                alert(data.active.id);
            } else { // else expired
                alert(data.expired.id);
                }
            }
    });
}

A: based on your json. 'all' can only be referenced through 'data.all' otherwise script is treating it as a  variable, which is undeclared.


text:
Q: How To Insert images into 1 table and other Data in another Table Using last insert id from 1 form in Codeigniter **this my whole Code And To Insert images into 1 table and other Data in another Table Using last insert id 1 form in Codeigniter **
Create.php (This is View File)

<?= form_open('Packages/save') ?>
Package Name:<?= form_input('name') ?>

Package Name:<?= form_input('price') ?>

Descriptione:<?= form_textarea('description') ?>

Image 1:<?= form_upload('image1') ?>

Image 2:<?= form_upload('image2') ?>

Image 3:<?= form_upload('image3') ?>

<?= form_submit('', 'Create Package')?>
<?= form_close()?>

Packages.php (This is Controller)

function save()
{
    $this->package->create($this->input->post());
    redirect('packages/');

}
function image_upload(){
    $config = array(
        'upload_path' => "/Images/",
        'allowed_types' => "gif|jpg|png|jpeg|pdf",
        'overwrite' => TRUE,
    );
    $lst_id=$this->package->create($this->input->post());
    $this->load->library('upload', $config);
    if($this->upload->do_upload())
    {
        $image_data = array(
            'id'=> $lst_id,
            'upload_data' => $this->upload->data());
        $this->load->view('upload_success',$image_data);
    }
    $this->package->create($this->input->post());
}

Package.php (this is model)

function create($post)
{
    $this->db->insert($this->table, $post);
    return $this->db->insert_id();
}
function upload($image_data){
    $this->db->insert('images', $image_data);
}


text:
Q: How to enable intellisense in package.json In this video is shown how WebStorm provides intellisense support in package.json. I tried the same but it doesn't work for my version. How do I enable it?
My version is:
WebStorm 2016.3.3
Build #WS-163.12024.17, built on January 31, 2017
Licensed to Maximus Koretskyi
You have a perpetual fallback license for this version
Subscription is active until October 16, 2018
JRE: 1.8.0_73-b02 amd64
JVM: Java HotSpot(TM) 64-Bit Server VM by Oracle Corporation

A: For that you need to use WebStorm 2017.1 (build 171.2272 or newer) which is currently in EAP stage (the video shows IDE version that was used).
https://blog.jetbrains.com/webstorm/2017/01/webstorm-2017-1-eap-171-2272/
Latest EAP build can be downloaded here.


text:
Q: How do I display RVM's current Ruby and gemset in the Terminal prompt? I'm using rvm-prompt. It seems the interpreter, the version, the patchlevel, and the gemset should all displayed by default.
If I call the prompt, it accurately returns the current ruby and gemset:
$ rvm-prompt
ruby-1.8.7-p302@rails125

But my gemset isn't reflected in my prompt:
ruby-1.8.7-p302 MacBook:~ subpixel$

I tried calling the gemset explicitly in .bash_profile with:
PS1="\$(~/.rvm/bin/rvm-prompt i v p g) $PS1"

but it doesn't change the prompt.

A: If you look at the documentation for rvm-prompt, at the bottom of the page you'll find the following:

ps1_functions
Recently there has been a pair programming session that turned out a useful bit of prompt setting code. It now resides in contrib/ so you can require it in your profiles as follows after sourcing RVM itself.
source "$rvm_path/contrib/ps1_functions"

Immediately after that you can customize your prompt by adding the following line
ps1_set

There is an article and screen cast associated with this in the community resources section.

I copied the ps1_functions file, changed it to suit my needs and source that in my .bash_profile. Then I just have a line that calls
ps1_set

Now my prompt changes when I change gemsets

A: You might have discovered a bug, because I see the same behavior. I'd recommend running it past RVM's author. You can find his email address by running rvm -v.


text:
Q: How to Encode an  to base64 in AngularJs? I need to save an image into Drupal, through the drupal service/file. For what i understand i need to decode the file into a base64 and send this as a payload for the service/file. How can i get to encode the  in order to do this???? I want to do this in javascript.

A: I would recommend you to use https://github.com/ninjatronic/angular-base64.
After following instructions for using this library, you can simply call:
var imageData=$base64.encode(image);

Don't forget to inject in your module:
.module('myApp', ['base64'])

A: I am the author of angular-base64-upload as mentioned by @GrimurD. This directive works perfectly for this scenario. It parses image(or any other file types) into base64-encoding and attach the file info to a model in your scope.
Sample usage:
<input type='file' ng-model='yourModel' base-sixty-four-input>

Once you selected a file, yourModel will have a value of something like:
{
  "filetype": "text/plain",
  "filename": "textfile.txt",
  "base64": "/asdjfo4sa]f57as]fd42sdf354asdf2as35fd4"
}

It also has sample code for decoding the base64 file in your server, using PHP or ruby.

A: I know it's quite old, but I came here for a solution.
In the end I found out that (if you don't want to use external libraries) loading an image in base 64 is as simple as using javascript FileReader.readAsDataURL()
Hopefully my final code will help others beginners like me. It features:

*

*Input file with HTML5 input type='file' (inspired by this answer)

*Trigger input from other html elements (inspired by this answer)

*Check if browser supports input type='file' (inspired by this answer)

It is also on codepen

angular.module('starter', [])
  .controller('Ctrl', function($scope) {
    $scope.data = {}; //init variable
    $scope.click = function() { //default function, to be override if browser supports input type='file'
      $scope.data.alert = "Your browser doesn't support HTML5 input type='File'"
    }

    var fileSelect = document.createElement('input'); //input it's not displayed in html, I want to trigger it form other elements
    fileSelect.type = 'file';

    if (fileSelect.disabled) { //check if browser support input type='file' and stop execution of controller
      return;
    }

    $scope.click = function() { //activate function to begin input file on click
      fileSelect.click();
    }

    fileSelect.onchange = function() { //set callback to action after choosing file
      var f = fileSelect.files[0],
        r = new FileReader();

      r.onloadend = function(e) { //callback after files finish loading
        $scope.data.b64 = e.target.result;
        $scope.$apply();
        console.log($scope.data.b64.replace(/^data:image\/(png|jpg);base64,/, "")); //replace regex if you want to rip off the base 64 "header"

        //here you can send data over your server as desired
      }

      r.readAsDataURL(f); //once defined all callbacks, begin reading the file

    };

  });

  <button ng-click='click()'>click to select and get base64</button>

BASE 64 data:

  {{data.alert}}

    {{data.b64}}

A: You don't need AngularJs for that. There is a thread here explaining how to do it using Javascript and canvas: How to convert image into base64 string using javascript

A: i found some websites,browser like chrome,ie10..may be support this
https://developer.mozilla.org/en-US/docs/Web/API/FileReader?redirectlocale=en-US&redirectslug=DOM%2FFileReader
http://www.pjhome.net/web/html5/encodeDataUrl.htm

A: I was having the same problem and ran into this repository on github. Tried it out and it worked perfectly.


text:
Q: Find $\frac{dI}{da}$ and $\frac{dI}{db}$ for the integral $I=\int_a^{b} {1\over log(x)} dx$ I've tried using the fundamental theorem of calculus, but it just doesn't seem correct. Any help would be appreciated as I don't know how to approach this.

A: The fundamental theorem of calculus states that if $a > 0$ and $$I(t) = \int_a^t \frac{1}{\log x} \, dx, \quad t > 0$$ then $I'(t) = \dfrac{1}{\log t}$ for all $t > 0$. You can apply this directly.
It will be useful to remember that $\displaystyle \int_t^b \frac{1}{\log x} \, dx = - \int_b^t \frac{1}{\log x} \, dx.$


text:
Q: Wrong result comparing GETDATE() to stored GETDATE() in SQL Server I would expect the result to always be 1:
DECLARE @x datetime2
SELECT @x=GETDATE()
SELECT CASE WHEN @x>GETDATE() THEN 0 ELSE 1 END

But it is sometimes 1 and sometimes 0.
How is that possible?

A: It takes time for code to execute. Sometimes a tick happens in between lines two and three, and sometimes (usually) not. In the latter case (no tick), @x is still equal to (not greater than) the GETDATE() value in the third line and you end up with 0. What surprised me at first is you ever see 1. When a tick does happen, @x should now be less than the new GETDATE() value in line 3 and you'd still see 0.
But it makes more sense when you run this code:
DECLARE @x datetime2
SELECT @x=GETDATE()
SELECT @x, GETDATE(), CASE WHEN @x>GETDATE() THEN 0 ELSE 1 END

Now we can see what's going on better. Here's a sample result on my machine:
2018-01-19 23:32:21.3833333   |  2018-01-19 23:32:21.383   |    1

Ahhh... @x is a datetime2 with more precision than the older datetime used by GETDATE(). And you can see in the documentation for GETDATE() that it does return a datetime rather than datetime2. So we have some rounding error going on between the two values.
For the 0 values, I ran the altered code 30 or 40 times (hitting F5 for refresh), and ALL of the 0's I saw looked like this:
2018-01-19 23:36:29.0366667   |   2018-01-19 23:36:29.037   |   0

Where the last digit in the second column was a 7 and the first column had repeating 6's with a rounded 7 at the end.
One thing still confuses me. The GETDATE() function returns a datetime value, but somehow it assigns datetime2 precision to @x. I'd expect to just see extra zeros that always match the original GETDATE() result.


text:
Q: Backbone SPA: Best practice for loading new routes? What is the 'best practice' way to load a new route in a backbone single page app?
Right now, my app has a mix of these two methods:
1) In my html
Some Route

Or I can define an event in my view:
2) In my view
Backbone.View.extend({
  //init code
  events: {
    'click a':'fooNav'
  },

  fooNav: function(e) {
    e.preventDefault();
    window.location.replace('#/foo');
  }

});

Both work fine, with the router cleaning up zombies and loading the associated view.
I'm not sure if I should be always using method two (which gives me more flexibility to do other things in the function and make non  tag click events load routes), or whether I should only use method two when it is absolutely necessary. Is one method much faster than the other? Any gotchas?
Many thanks.

A: I prefer method two because, for example, if i want to change something in the url, i can do it in the view. You can use method two like this:
Backbone.View.extend({
//init code
events: {
'click a':'fooNav'
},

fooNav: function(e) {
e.preventDefault();
Backbone.history.navigate('#/foo');
}
});

In this way, you can add id's to the url and keep track of pages in the browser history


text:
Q: How to generate a very big BigInt I want to implement RSA, and for that I need to generate e which should be gcd(e, ø(n)) = 1 and 1 < e < ø(n) and also should be very close in size to  ø(n). My alg. below respects the first two steps, but the generated number is pretty small. How can I generate a bigger one?
    // generate random p,q,r on 512 bits
    p = new BigInteger(512, 15, new Random());
    q = new BigInteger(512, 15, new Random());
    r = new BigInteger(512, 15, new Random());

    // calculate n = p*q*r
    n = p.multiply(q);
    n = n.multiply(r);

    //calculate ø(n) = (p - 1)*(q - 1)*(r - 1)
    ø_n = p.subtract(BigInteger.valueOf(1));
    ø_n = ø_n.multiply(q.subtract(BigInteger.ONE));
    ø_n = ø_n.multiply(r.subtract(BigInteger.ONE));

    do {
    e = new BigInteger(2 * 512, new Random());

} while //while e >= ø_n
        ((e.compareTo(ø_n) >= 0)
        || //while gcd(e, ø(n)) != 1
        (e.gcd(ø_n).compareTo(BigInteger.ONE) != 0));

Check the while loop, everything else is just initialisations.

A: Consider using BigInteger.probablePrime() with SecureRandom.


text: Q: Using scikit-learn for mixed L1, L2 penalized regressions Is there a nice way to include more general combinations of L1 and L2 penalties in scikit-learn? For example, input some of the parameters for L1 penalty and others for L2?


text:
Q: Does restricting the number of links for new users do any good? New users with 1 rep face the following restrictions on all SE sites:

What are the new user restrictions?
New users cannot:

*

*post images

*post more than two hyperlinks at a time, either in a post or their user profile

*contribute answers to protected questions

*ask or answer questions too rapidly

  Why are restrictions placed on new users?
Because we allow participation from anonymous internet users, we must
  take some precautions to ensure that the rare malicious or spammy
  anonymous user doesn't ruin the experience for everyone else.

I understand the reasoning for disallowing images, protecting questions and for rate-limiting new users. I don't understand how restricting the number of links for new users does anything useful. The privileges page suggests that it is meant to limit the damage malicious users or spammers can do.
For spammers, I don't see the difference whether they link one time to their site, or a dozen times. The spam post will be deleted shortly in any case, I can't really see any advantage to restricting the number of links.
For malicious users you don't really need more than one link to a NSFW site to cause trouble, I also fail to see how the restriction should help there.
I unsuccessfully lobbied to remove this restriction on Skeptics, I'd like to understand how this restriction is supposed to help SE sites. It's a significant annoyance for new users, especially on sites like Skeptics, and I'm doubting whether this restriction is useful at all.
I'm thinking about requesting to remove this restriction everywhere on the SE network, but I'd like to understand the reasons behind it and it's effectiveness better before I do that. My perception of the usefulness of this restriction seems to me vastly different to what the SE team thinks of it.
Update:
The link restriction has been removed on Skeptics for a while now, and I haven't seen any increase in spam.