text:
Q: How to preserve tabs in Github for Makefiles Github automatically converts tabs to multiple spaces. So, every time I create a Makefile in Github, I need to clone the repository in my Linux box and edit th Makefile using vim and then push the changes back to my Github repository to avoid the following error while executing make install|clean:
Makefile:  : *** missing separator (did you mean TAB instead of 8 spaces?).  Stop.
Is there an elegant way to preserve tabs in Github website especially for Makefiles?

A: You can write a smudge/clean filters to "clean" up the file every commit/checkout of files.
The script will replace any spaces/tabs with the desired format.
The smudge/clean are filters which are runs whenever you commit file (clean) and checkout file to a working directory (smudge).

Smudge / clean
Read all about it and to set it up here:
https://git-scm.com/book/en/v2/Customizing-Git-Git-Attributes

It turns out that you can write your own filters for doing substitutions in files on commit/checkout.
These are called clean and smudge filters.
In the .gitattributes file, you can set a filter for particular paths and then set up scripts that will process files just before they're checked out ("smudge") and just before they're staged ("clean").
These filters can be set to do all sorts of fun things.


text:
Q: How can 'the nested renamer error' be solved from this jupyter notebook I'm trying to replicate the next notebook for a class, specifically the line Input [32]
In[32] bin_stats = joined.groupby('bins_index')['offset'].agg({'fold': len, 'min_offset': np.min})

but I get the error SpecificationError: nested renamer is not supported

A: You can use named aggregation:
bin_stats = (joined.groupby('bins_index')
                   .agg(fold = ('offset', len),
                        min_offset = ('offset', np.min)))

redpajama_set_name: RedPajamaStackExchange


text:
Q: CUDA 5.0: checkCudaErrors fails to find correct "check" method if class has a "check" method As the cutil.h header is removed from CUDA Samples, some new headers are introduced like helper_cuda.h, helper_functions.h.
One of the main keywords that is used by me was CUDA_CHECK_ERROR, and I think it is replaced with checkCudaErrors.
In most of my code the macro compiles and works well. However when I use it in a class which has a function named check(..), checkCudaErrors function gives compile errors.
Here is an example:
#include <stdio.h>

#include <cuda_runtime.h>
#include <helper_cuda.h>
#include <helper_functions.h>

template<typename T>
class Trivial {

public:

    void check()
    {

    }

    void initialize()
    {
        checkCudaErrors(cudaMalloc(NULL, 1));
    }

    T val;

};

int main(int argc, char **argv)
{

    Trivial<int> tt;

    tt.initialize();

    return 0;
}

and the result of compilation: (the same error is seen when compiled with GCC 4.5 also!)
1>------ Build started: Project: ZERO_CHECK, Configuration: Release x64 ------
2>------ Build started: Project: massivecc, Configuration: Release x64 ------
2>  trivial_main.cpp
2>..\src\trivial_main.cpp(19): error C2660: 'Trivial<T>::check' : function does not     take 4 arguments
2>          with
2>          [
2>              T=int
2>          ]
2>          ..\src\trivial_main.cpp(18) : while compiling class template member         function 'void Trivial<T>::initialize(void)'
2>          with
2>          [
2>              T=int
2>          ]
2>          ..\src\trivial_main.cpp(29) : see reference to class template         instantiation 'Trivial<T>' being compiled
2>          with
2>          [
2>              T=int
2>          ]
3>------ Skipped Build: Project: ALL_BUILD, Configuration: Release x64 ------
3>Project not selected to build for this solution configuration
========== Build: 1 succeeded, 1 failed, 1 up-to-date, 1 skipped ==========

The same error is taken when I removed the template parameter.

A: I had to copy the check(..) function's definition from helper_functions.h into my class's header to be able to compile the class.
#include <stdio.h>
#include <cuda_runtime.h>
#include <helper_cuda.h>
#include <helper_functions.h>
class Trivial {
public:
    template< typename T >
    bool check(T result, char const *const func, const char *const file, int const line)
    {
        if (result) {
            fprintf(stderr, "CUDA error at %s:%d code=%d(%s) \"%s\" \n",
            file, line, static_cast<unsigned int>(result), _cudaGetErrorEnum(result), func);
            return true;
        } else {
            return false;
        }
    }

    void check() {  }

    void initialize()
    {
        checkCudaErrors(cudaMalloc(NULL, 1));
    }
};

int main(int argc, char **argv)
{
    Trivial tt;
    tt.initialize();
    return 0;
}

So, this mainly solved my problem and my code compiled successfully.

A: with reference to the source code found in helper_cuda.h on line 680
https://github.com/pathscale/nvidia_sdk_samples/blob/master/vectorAdd/common/inc/helper_cuda.h
you find checkCudaErrors declares a #define checkCudaErrors(val)           check ( (val), #val, FILE, LINE ) which takes in a single argument and calls check with 3 other arguments based on config.Note that it is also defined in line 680
Whereas in your case, you define a check that does not take any argument. case of different declaration and definition, multiple definitions.


text:
Q: spring boot unit testing using testng How to write a POST method test case if the return type of a particular create method in the service layer is ResponseEntity<Object>?
This is my createOffer method:
public ResponseEntity<Object> createOffer(Offer offer) {
    Offer uoffer = offerRepository.save(offer);

    URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{jobTitle}").
                    buildAndExpand(uoffer.getJobTitle()).toUri();

    return ResponseEntity.created(location).build();

}

and this is its corresponding test class method:
@Test
public void testCreateOffer() {
    Offer offer = new Offer("SE",new Date(),5);
    Mockito.when( offerRepository.save(offer)).thenReturn( offer);
    assertThat(offerServiceImpl.createOffer(offer)).isEqualTo(offer);
}

Here I am getting an error while running this test case which is no current servlet request attributes and exception is:

java.lang.IllegalStateException

Why is it coming

A: This answers the above question.
Hope it helps when someone finds the same issue !!!
@Test
public void testCreateOffer() {
    Offer offer = new Offer("SE",new Date(),5);

    MockHttpServletRequest request = new MockHttpServletRequest();
    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));

    URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{jobTitle}").
            buildAndExpand(offer.getJobTitle()).toUri();

    ResponseEntity<Object> response = ResponseEntity.created(location).build();
    Mockito.when( offerRepository.save(offer)).thenReturn(offer);
    assertThat( offerServiceImpl.createOffer(offer)).isEqualTo(response);
}

A: Problem is that in your method you want to get infromation from class ServletUriComponentsBuilder. When you open this class in comment is

UriComponentsBuilder with additional static factory methods to create
  links based on the current HttpServletRequest.

So it means when your application is running on server (e.g. tomcat) you have context and you can read information from HttpServletRequest. But in junit you don't have context and you can't get this iformation. So when your code is runnig and reach the ServletUriComponentsBuilder.fromCurrentRequest() then the code is done. So you have to mock it.  Look at this link it can help you.
ServletUriComponentsBuilderTests

A: Kotlin.
I was getting java.lang.IllegalStateException: No current ServletRequestAttributes cause I had this line in my service:
val location = ServletUriComponentsBuilder.fromCurrentRequest().build().toUri()
I have put the following into my setUp() function:
   @BeforeEach
    fun setup() {
        MockitoAnnotations.openMocks(this)
        val request = MockHttpServletRequest()
        RequestContextHolder.setRequestAttributes(ServletRequestAttributes(request))
    }


text:
Q: How should I punctuate a sentence beginning with 'I was wondering'? How do we use wondering sentences that have a question it by comma , interrogative,question mark...
I was wondering when he rejected him do John got upset ?
I was wondering do you love me.
I was wondering you love me.

A: Statements such as "I wonder why he is late" are called indirect questions. They do not ordinarily get a question mark in formal standard English, but you might see someone use a question mark there in less formal/non-standard registers (like in an email).
They would typically end in a period (or even exclamation mark if emphasized)

A: The punctuation depends on whether it is a statement or a question.
"I wonder if John got upset." is a statement about what you are thinking, so it ends in a period.
"I wonder, did John get upset?" is a question, with "I wonder" serving as more of a supplementary personalization that isn't really essential to the meaning.  It would end in a question mark.

A: A question mark would be the correct punctuation here, however it would be helpful to use correct tenses. I was wondering, when he rejected him did John get upset. the English language needs you to stay in the tense you started in. for example when you say "when he rejected him", did would would be the correct tense as you are referring to an event that has already happened.


text:
Q: Applying Seperate Rotations to Multiple Quads Using Old OpenGL Functionality I want to render a quad with a certain rotation, additionally this quad has "leaf" quads rendered below it similar to a binary tree structure. Each of the children has their own rotation to be applied to them in addition to that of their parents. In other words, if the root quad rotates, the entire tree rotates with it but each sub-tree can rotate individually as well. So my recursive render function looks a little like this...
RenderNode(Node current_node){
    glRotate(current_node->rotation);
    glBegin(GL_QUADS);
      // supply 4 vertices and texture mapping
    glEnd();

    RenderNode(current_node->leftChild);
    RenderNode(current_node->rightChild);
}

Now I would expect my child nodes to have slightly different rotations compared to their parents but unfortunately this is not the case. The more times glRotate() is called during a single frame the faster the rotation animation but all the plates stay on the same plane. It seems like none of the quads are being rendered until the very end and the latest transformation matrix is being applied to all of them. As a test I tried putting glPushMatrix() before each transformation and glPopMatrix() after each call to glEnd(), this completely stops the rotation of all of the plates.
Could someone enlighten me as to what's happening here?

A: Kind of hackish because of the recursion, but this is the best base case I can come up with short notice:
Try this:
RenderNode(Node current_node, GLfloat parentRotation){
    if(current_node->leftChild != null) RenderNode(current_node->leftChild, parentRotation + current_node->rotation);
    if(current_node->rightChild != null) RenderNode(current_node->rightChild, parentRotation + current_node->rotation);
    glLoadIdentity();
    glRotate(current_node->rotation);
    glBegin(GL_QUADS);
      // supply 4 vertices and texture mapping
    glEnd();
}

This way you won't have to pop or push any matrices, it will just reset to the identity matrix for each actual geometry render. Just remember to call glLoadIdentity() again after rendering the mesh if you want to render anything else.


text:
Q: How do I compare two values from two vectors and then update the vector values in C++? Thanks for the help on the previous code, guys! I am now expanding the previous query to include this code: I am having the issue of no output from the for loops and if statements. I have to compare strings in two vectors and find if one is a subset of the other; if there is a subset, I must remove it. (the two vectors are actually identical...this is essentially comparing all elements within a vector against each other). Any guidance would be very much appreciated!
 //headers: iostream, vector
 //namespace std
 //main function

//each vector already has content (read from a file) stored in them. Both vectors hold         the same elements.

int c,j; string first_sequence, second_sequence;
vector<string>::iterator ivector1; vector<string>::iterator ivector2;
vector<string> sequence_1; vector<string> sequence_2; vector<string> header;

 //comparison of sequences within each element of vectors

size_t location,x,y,k,s;

k = sequence_1.size();
s = sequence_2.size();
for(ivector1 = sequence_1.begin(); ivector1< sequence_1.end(); ivector1++){
 for(ivector2= sequence_2.begin();ivector2<sequence_2.end(); ivector2++){
    *ivector1 = first_sequence; *ivector2 = second_sequence;

    if(ivect1 != ivect2){
        x = first_sequence.size();
        y = second_sequence.size();

        if(x > y){
            location = first_sequence.find(second_sequence);
                                if (location != -1){
                                    cout << "Deleting the sequence with id: <"     << *ivector2 << endl;
                    sequence_2.erase(ivector2); *ivector2 = "gone";
                                     }

                }   else if (y > x) {
            location = second_sequence.find(first_sequence);
                                if (location != -1){
                    cout << "Deleting the sequence with id: <"<< *ivector1 << endl;
                    sequence_1.erase(ivector1); *ivector1 = "gone";

                                    }

                         }
    }
 }
}

return 0;
}

A: You get no output because none of the elements in vector1 are larger than the lowest value you have inserted into vector2. Therefore this if condition that you test
  if (*ilist1 > *ilist2)

is never satisfied, hence no cout statement will run. I am willing to bet that if you change it to
 if (*ilist1 < *ilist2)

you will see output to the terminal/screen. 3 is always < 4.

A: You are only ever testing if values from vector 1 are bigger than values from vector 2.
Your code is testing:
1 > 4
1 > 5
1 > 6
2 > 4
2 > 5
2 > 6
3 > 4
3 > 5
3 > 6

None of these are true, so nothing's getting displayed.

A: In every single loop, you're assigning the value of the iterators to the strings first_sequence and second_sequence. You're not ever using the values in the vectors themselves.


text:
Q: Mass Email Acknowledgement Options Business has a need to send out mass communications/emails to internal staff. With these emails, they would like a button or signature option to appear in these emails that the recipient would have to "sign" essentially stating that they acknowledge the email. Any suggestions on what tool to use to accomplish this? We have some apps currently such as DocuSign and Exact Target, but just looking for any opinions on what works best. Thanks as always.

A: If you have ET landing pages and you're sending the email from ET you can have an "Accept" button or link in the email that will link to a landing page.  If you use the MicrositeBaseUrl AMPscript function for the link in the email you can grab the email of the person who clicks the link with some AMPscript on the landing page and add their name to a data extension or update a field in an existing data extension.  The code to grab the email address in the landing page would go at the top of the page and look something like this:
%%[ VAR @emailaddress
        SET @emailaddress = emailaddr
        /* Code to add or update DE goes here */
]%%
HTML of page goes here

If you're not using ET to send the email but you have access to ET landing pages you can put the email or other identifier in the query string of the link and pull it out using AMPscript.
The link would look something like this:
Accept

The AMPscript on the page would look something like this:
%%[ VAR @emailaddress
        SET @emailaddress = RequestParameter("email")
        /* Code to add or update DE goes here */
]%%
HTML of page goes here


text:
Q: Блок не выравнивается Делаю окно регистрации на сайте, и на рисунке видно, что первый текст и поле ввода смещены влево, а также слова "повтор" и "пароля" расположены на одной строчке, хоть стоит text-algin: center.

#title {
  margin-top: 40px;
  position: absolute;
  margin-left: 50%;
  transform: translateX(-50%);
  font-family: 'Russo One', sans-serif;
  font-size: 60px;
}

.ps {
  font-family: 'Russo One', sans-serif;
  margin-left: 50%;
  transform: translateX(-50%);
  position: absolute;
  margin-top: 160px;
}

.login {
  text-align: center;
  position: absolute;
  margin-top: 170px;
  margin-left: 50%;
  transform: translateX(-50%);
}

.password2 {
  text-align: center;
  position: absolute;
  margin-top: 40px;
  margin-left: 50%;
  transform: translateX(-50%);
}

.password1 {
  text-align: center;
  position: absolute;
  margin-top: 40px;
  margin-left: 50%;
  transform: translateX(-50%);
}

.d1 {
  font-size: 25px;
  font-family: 'Russo One', sans-serif;
}

.d1 input {
  display: block;
  border-color: black;
  border-style: solid;
  border-width: 3px;
}

  РЕГИСТРАЦИЯ

    Повтор пароля
    <input type="text">

      Пароль
      <input type="text">

        Повтор пароля
        <input type="text">

A: Зачем весь этот огород?

#title {
  font-size: 60px;
}

.d1 {
  font-size: 25px;
  font-family: 'Russo One', sans-serif;
  text-align: center;
}

.d1 input {
  border-color: black;
  border-style: solid;
  border-width: 3px;
}

    РЕГИТРАЦИЯ

      Повтор пароля

      <input type="text">

        Пароль

        <input type="text">

          Повтор пароля

          <input type="text">


text:
Q: which algorithm should be chosen to complete this task Hi
 I am new to Cluster,I don't know which algorithm is appropriate to my task. let me describe my task:

*

*first, given a set of points and their distances between them

*clustering them into several clusters based on distance.

*a few new points will be added, the distance among all of points will also be given.

*repeating 2

for example,first we have the following matrix
   | p1 | p2 | p3 |
---|----|----|----|
p1 |    |    |    |
p2 | d1 |    |    |
p3 | d2 | d3 |    |

after clustering, we add a new point and the distance is also given:
   | p1 | p2 | p3 | p4 |
---|----|----|----|----|
p1 |    |    |    |    |
p2 | d1 |    |    |    |
p3 | d2 | d3 |    |    |
p4 | d4 | d5 | d6 |    |

The problem here is the speed, I expect that the clustering is the incremental cluster, i.e. the later clustering can utilize previous result. Because we will add the points frequently(if we find one), and if we re-cluster the points each time. Even if the cluster itself has O(n), the total time of cluster will be O(n^2).
Any suggestion?
Thanks

A: One option is to fix the number of clusters (say, you have K clusters). Whenever you add a new point, you add it to the cluster whose center of gravity (average of the coordinates of the points in the cluster) is nearest to the point you added. If you recluster completely whenever the number of points in your space becomes a power of two (1, 2, 4, 8, 16, 32 ...), the amortized cost of reclustering is still O(n).


text:
Q: JQuery Get Selected Item from List Box and split by comma Can anyone offer more help on this I have the code setup on jsfiddle at...
http://jsfiddle.net/justinerswell/feDTU/
I need to get the last item in the substr and work backwards to populate the fields I need.
Thanks
Original Question
Hi I have a list box returned on a page with multiple result which are being parsed in as a string into the value...
<option value="1 Corn Exchange, The Strand, RYE, East Sussex, TN31 7DB, UNITED KINGDOM">

Using JQuery I need to do a couple of things..

*

*Get Selected Value

*Split Value of Selected Item by Comma's

*Loop through in revers and set a variable for each item i.e country: United Kingdom Postcode:TN31 7DB etc

Can anyone help me?
Thanks

A: Do you want to fetch the data on click or submit?
    $('select').click( function() {

        var selected = $(this).find(':selected').text();

        var substr = selected.split(',');
        var product = substr[0];
        var city = substr[1];
        var postcode = substr[2];
        var country = substr[3];

        //DO SOMETHING WITH IT??
    });

But its not a very good idea, considering your "data" structure can't change (ie. missing fields and so on) - since it will break on the indexes....

A: jquery has a selector for selected value.
so use
var selectedValue = $('#myselect option:selected').val();

then split on space
var table = selectedValue.split(',');

and loop on your table
for(i = 0 ; i < table.length; i++) {
    // dosomething with table[i]
}

A: suppose if you are use Html Listbox than try this
 <select id="Select1" size="4" multiple="multiple" onchange="Check(this);">
 <option value="1">item 1</option>
 <option value="2">item 2</option>
 <option value="3">item 3</option>
 <option value="4">item 4</option>
 <option value="0">All</option>
</select>

javascript
 function Check(selectObject)
  {
   var items = new Array();
   for (var i = 0, j = selectObject.options.length; i < j; i++)
   {
       if (selectObject.options[i].selected)
       {
           items.push(selectObject.options[i].value);
       }
   }
   // selectObject.id holds the "id"
   var itemsToString = items.toString();
   alert(itemsToString);
   //split and get values.
   var s = itemsToString.split(',');
   for(var k=0; k<s.length; k++)
      {
           alert(s[k]);
      }

  }

Hops its helps

A: Try $.map() to get all selected items in list
var selectedValues = $.map($('#ddlList option:selected'), function (element) {
        return element.value;
    });

A: Try this simple, call this function onchange() event of  dropdown listbox .
function FuncFilter() {
     var selectedText = $("#DrpDatefilter").find(':selected').text();
     alert(selectedText );

    **Or**
     var selectedValue = $("#DrpDatefilter").find(':selected').val();
     alert(selectedValue );

 }


text:
Q: Intersection between a line and a plane. A line can either lie on a plane, lie parallel to it or intersect it.
Determine, if there is one, the point of intersection between the line given by the equation
$$\displaystyle\frac{x−5}{2} =\displaystyle\frac{y−1}{-1} = \displaystyle\frac{z−15}{4}$$
      and the plane given by the equation
$$(x, y, z) = (-2, -7, 5) + s(2, 6, 3) + t(1, 4, -1)$$
So, what I have to do, is determine if the line and the plane either intersect or are parallel? What equation applies in this problem?

A: A very basic way could be to find $x$, $y$ and $z$ from plane's equation and then put them into line's equation. This would lead us to see if the achieved system of equations is consistent or not: $$x=-2+2s+t, y=-7+6s+4t, z=5+3s-t$$

A: By inspection we can find that the line is parallel to the vector $(2,-1,4)$ and that the point $(5,1,15)$ lies on the line. In homogeneous coordinates, the line is thus the join of $\mathbf p=[2:-1:4:0]$ and $\mathbf q=[5:1:15:1]$. This line can be represented by its Plücker matrix $\mathbf p\mathbf q^T-\mathbf q\mathbf p^T$.
A normal to the plane is $(2,6,3)\times(1,4,-1)=(-18,5,2)$ and $(-18,5,2)\cdot(-2,-7,5)=11$, so the plane can be represented in homogeneous coordinates as $\mathbf\pi=[-18:5:2:-11]$. The intersection of the line and plane is $$L\mathbf\pi=\mathbf p\mathbf q^T\mathbf\pi-\mathbf q\mathbf p^T\mathbf\pi=-66\mathbf p+33\mathbf q=[33:99:231:33]$$ or in (inhomogeneous) Cartesian coordinates, $(1,3,7)$.


text:
Q: How to create new Partitions without creating a new collection? I'm trying to create a new Partitions inside of a collection without creating a new Collection?
I already created a new collection with a new partionkey, but now I'm trying to create some inside of a collection.
DocumentCollection collectionDefinition = new DocumentCollection();
collectionDefinition.Id = collectionId;
collectionDefinition.PartitionKey.Paths.Add("/IoTDevices"); //--> add this

DocumentCollection partitionedCollection = await client.CreateDocumentCollectionAsync(
    UriFactory.CreateDatabaseUri(databaseId),
    collectionDefinition,
    new RequestOptions { OfferThroughput = 10100 });

A: you dont need to create partitions inside collections. when you create a document inside the collection it will get assigned to an appropriate partition automatically based on partition key value of the document you are creating. if the partition doesn't exist - it will get created.


text:
Q: Sparse column vs. Indirection As I understand, MySQL doesn't have any special SPARSE COLUMN directive, and any question like this is purely situational, so I'm wondering if there is a good rule of thumb for when to use a sparse column vs. when to create another table.
As a specific example, I have a table called Lessons.  We want to add a lesProgramNumber, but this will only apply to about 10% of all lessons at any given time (it will be NULL for the other 90%).  We could avoid a lot of NULL data by having a LessonsProgramNumber table very easily, but then this requires an additional JOIN at times.  Is there an easy way to make a choice about what I need?  What if Lessons only has 500 rows?  What if it has 500 million?

A: InnoDB's COMPACT row format (which is the default) does not store anything when a column is NULL; it only stores non-null columns.  It just skips that column in the on-disk row storage.  So the cost of sparse columns is not so bad.
See http://dev.mysql.com/doc/refman/5.1/en/innodb-physical-record.html


text:
Q: Using and updating textfiles as data storage I am not too sure why, but the current stock for all the items now appears as zero when it shows up in a listbox/on the 'receipt'. Also, I am struggling to get it to update back up from zero when it becomes zero.
Public Class Form1
    Dim GTIN As String
    Dim LineContaining As String
    Dim quantity As String
    Dim description As String
    Dim singleamount As String
    Dim singleprice As Double
    Dim totalprices As Double
    Dim correctcode As Boolean
    Dim stocklevel As String
    Dim requiredstock As Integer
    Dim remainingstock As Integer
    Dim stock As Integer
    'declare variables
    Private Sub btnEnterGTIN_Click(sender As Object, e As EventArgs) Handles btnEnterGTIN.Click
        GTIN = getValidGTIN()
        Call itemfinder(GTIN)
    End Sub
    Function getValidGTIN()
        Dim GTIN, ValidGTINAmountCharacters As String
        Dim GTINOK As Boolean
        'Declaring variables.
        GTINOK = False
        Do
            GTIN = InputBox("Enter the full GTIN Number (it should be 8 digits long)")
            'Prompts the user to enter the GTIN.
            ValidGTINAmountCharacters = Len(GTIN)
            'Makes it so that the amount of characters of the GTIN is stored in the variable ValidGTINAmountCharacters.
            If ValidGTINAmountCharacters = 8 Then GTINOK = True
            'Makes it so the program will only accept an input if it was 8 characters long.
            If Not IsNumeric(GTIN) Then GTINOK = False
            'Makes it so that if any other character typed in apart from a number is not valid.
            If Not GTINOK Then MsgBox("The GTIN Number isn't valid. It should be a 8 digit number. (Should not contain letters or symbols).")
            'Makes it so that if the GTIN is not valid according to the above, a message appears saying it is invalid.
        Loop Until GTINOK
        Return GTIN
    End Function
    Private Sub itemfinder(ByVal GTIN As String)
        Using reader As New IO.StreamReader("receipt_orders.txt")
            While Not reader.EndOfStream
                Dim line As String = reader.ReadLine()
                If line.Contains(GTIN) Then
                    LineContaining = line
                    Exit While
                End If
            End While
        End Using
        'reads the textfile to find the entered GTIN
        description = Mid$(LineContaining, 10, 17)
        singleamount = Mid$(LineContaining, 38, 4)
        stocklevel = Mid$(LineContaining, 43, 2)
        quantity = InputBox("Enter the quantity you require?")
        'prompts user to input the quantity

        Dim QuantityOK As Boolean
        QuantityOK = False
        If quantity <= stocklevel Then
            QuantityOK = True
        End If

        Dim GTINOK As Boolean
        GTINOK = False
        Using reader As New IO.StreamReader("receipt_orders.txt")
            While Not reader.EndOfStream
                Dim line As String = reader.ReadLine()
                If line.Contains(GTIN) Then
                    GTINOK = True
                    Exit While
                End If
            End While
        End Using
        stocklevel = stock
        If QuantityOK = False And stock > 0 Then
            MsgBox("There is not enough of this item in stock, restocking item to extra stock needed. You will not get " _
                   & quantity & " items, but we can give you " & stocklevel & " and restock the remaining amount.")
            requiredstock = quantity - stocklevel
            totalprices = stocklevel * singleamount
            lstGTIN.Items.Add(GTIN)
            lstName.Items.Add(description)
            lstQuantity.Items.Add(quantity)
            lstInStock.Items.Add(stocklevel)
            lstAdditionalStock.Items.Add(requiredstock)
            lstSinglePrice.Items.Add(FormatCurrency(singleamount))
            lstTotal.Items.Add(FormatCurrency(totalprices))
            lstTotals.Items.Add(totalprices)
            lstReceipt.Items.Add("GTIN Code: " & GTIN)
            lstReceipt.Items.Add("Item: " & description)
            lstReceipt.Items.Add("Quantity wanted: " & quantity)
            lstReceipt.Items.Add("Quantity available: " & stocklevel)
            lstReceipt.Items.Add("Required restock amount: " & requiredstock)
            lstReceipt.Items.Add("Price per unit: " & FormatCurrency(singleamount))
            lstReceipt.Items.Add("Subtotal cost: " & FormatCurrency(totalprices))
        End If

        If QuantityOK = False And stock = 0 Then
            MsgBox("This item is out of stock. We will register this item for restock in time for your next purchase.")
            requiredstock = quantity
            totalprices = 0
            lstGTIN.Items.Add(GTIN)
            description = Mid$(LineContaining, 10, 17)
            lstName.Items.Add(description)
            lstQuantity.Items.Add(quantity)
            lstInStock.Items.Add(stocklevel)
            lstAdditionalStock.Items.Add(requiredstock)
            lstSinglePrice.Items.Add(FormatCurrency(0))
            lstTotal.Items.Add(FormatCurrency(totalprices))
            lstTotals.Items.Add(totalprices)
            lstReceipt.Items.Add("GTIN Code: " & GTIN)
            lstReceipt.Items.Add("Item: " & description)
            lstReceipt.Items.Add("Quantity wanted: " & quantity)
            lstReceipt.Items.Add("Quantity available: " & stocklevel)
            lstReceipt.Items.Add("Required restock amount: " & requiredstock)
            lstReceipt.Items.Add("Price per unit: " & FormatCurrency(0))
            lstReceipt.Items.Add("Subtotal cost: " & FormatCurrency(totalprices))
        End If
        'if the GTIN is found in the textfile it is valid.

        'if the GTIN code was incorrect then put the listboxes as product not found or zero.
        If QuantityOK = True Then
            MsgBox("No restock of item needed.")
            totalprices = quantity * singleamount
            remainingstock = stocklevel - quantity
            lstGTIN.Items.Add(GTIN)
            lstName.Items.Add(description)
            lstQuantity.Items.Add(quantity)
            lstInStock.Items.Add(stocklevel)
            lstAdditionalStock.Items.Add(requiredstock)
            lstSinglePrice.Items.Add(FormatCurrency(singleamount))
            lstTotal.Items.Add(FormatCurrency(totalprices))
            lstTotals.Items.Add(totalprices)
            'if the GTIN code was correct, calculate the subtotal amount and put information in listboxes.
            lstReceipt.Items.Add("GTIN Code: " & GTIN)
            lstReceipt.Items.Add("Item: " & description)
            lstReceipt.Items.Add("Quantity: " & quantity)
            lstReceipt.Items.Add("Quantity in stock: " & stocklevel)
            lstReceipt.Items.Add("Required restock amount: " & requiredstock)
            lstReceipt.Items.Add("Price per unit: " & FormatCurrency(singleamount))
            lstReceipt.Items.Add("Subtotal cost: " & FormatCurrency(totalprices))
            'adds all the information onto a receipt - updates after every purchase.
            Dim contents As String = IO.File.ReadAllText("receipt_orders.txt")

            If GTINOK = False Then
                lstReceipt.Items.Add("GTIN Code: " & GTIN)
                lstReceipt.Items.Add("Item: Product not found")
                lstGTIN.Items.Add(GTIN)
                lstName.Items.Add("Product not found!")
                lstQuantity.Items.Add(0)
                lstSinglePrice.Items.Add(FormatCurrency(0))
                lstInStock.Items.Add(0)
                lstAdditionalStock.Items.Add(0)
                lstTotal.Items.Add(FormatCurrency(0))
                lstTotals.Items.Add(0)
            End If

            contents = contents.Replace(stocklevel, remainingstock)
            IO.File.WriteAllText("items_to_restock", contents)

        End If

        Dim totalprice As Double
        For x As Integer = 0 To lstTotals.Items.Count - 1
            totalprice += Val(lstTotals.Items.Item(x).ToString)
        Next
        'adds up the numbers in the total list box and puts in the text box TotalPrice.
        txtTotalPrice.Text = FormatCurrency(totalprice.ToString)
        'formats the total as a currency.
    End Sub

    Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
        'clears all listboxes
        lstGTIN.Items.Clear()
        lstName.Items.Clear()
        lstQuantity.Items.Clear()
        lstSinglePrice.Items.Clear()
        lstTotal.Items.Clear()
        lstTotals.Items.Clear()
        lstReceipt.Items.Clear()
        lstInStock.Items.Clear()
        lstAdditionalStock.Items.Clear()
        'clears the total text box
        txtTotalPrice.Text = ""
    End Sub

    Private Sub btnShowCodes_Click(sender As Object, e As EventArgs) Handles btnShowCodes.Click
        Process.Start("receipt_orders.txt")
    End Sub
End Class


text:
Q: What should i put in the username and password field in paypal check android sdk? I am using Paypal checkout android SDK(latest), but I am encountering some issues.
please refer to this:
https://developer.paypal.com/docs/business/native-checkout/android/
Go to step no 2.
In there, under maven, there are credentials(// Be sure to add these non-sensitive credentials in order to retrieve dependencies from the private repository.)
///////////
I don't know what should I put in the "non-sensitive credentials". Should I have to put the Paypal username(email id) and password or something else?
Any help will really be appreciated.
Please help friends.

A: As the comment says, "be sure to add these non-sensitive credentials in order to retrieve dependencies from the private repository"
Use those credentials.


text:
Q: Showing that $m(\{x \in [0, \pi/2] | \cos(x) \in \mathbb{Q} \}) = m(\{ [0, \pi/2] \cap \mathbb{Q}\}) = 0.$ (if the statement is correct) Showing that $m(\{x \in [0, \pi/2] | \cos(x) \in \mathbb{Q} \}) = m(\{ [0, \pi/2] \cap \mathbb{Q}\}) = 0.$
My Questions are:
for proving $\subseteq$:
Assume that $0 \leq x \leq \pi/2$, then taking the cosine of this, we get $\cos 0 \geq \cos x \geq \cos (\pi/2),$ so, $1 \geq \cos (x) \geq 0$ (because $\cos (x)$ is a decreasing function in this interval.) ..... is my proof correct?
for proving $\supseteq$:
I think that this direction is not true, I think the correct statement should be $m(\{x \in [0, \pi/2] | \cos(x) \in \mathbb{Q} \}) \subseteq m(\{ [0, \pi/2] \cap \mathbb{Q}\}) = 0.$ am I correct?
Could anyone help me in answering those questions, please?

A: The two sets are emphatically NOT equal (hint: $x=\pi/3$); the statement only asserts that both sets are measure zero.
The reason the second set is measure zero should be clear using very basic measure theory (presumably you have seen that $\mathbb{Q}$ is measure zero). The reason the first one is measure zero follows by the same reason the second one is. Namely, note that $\cos(x)$ is monotonically decreasing on $[0,\pi/2]$, and so if $f(x)=\cos(x)$, then $f^{-1}(a)$ is either empty or a singleton for each $a\in \mathbb{Q}$. Can you conclude (using the countability of $\mathbb{Q}$ and basic properties of Lebesgue measure)?

A: The other answer covers it, but it may be instructive to note that $\textit{any}$ Lipschitz continuous function maps sets of measure zero to sets of measure zero:
Suppose for all $x,y\in A,\ |f(x)-f(y)|\le C|x-y|$ for some positive constant $C$. If $A$ has measure zero, we can cover it by a countable union of open balls $\{B_j\}_j$ each of radius $r_j$ such that $\sum |B_j|<\delta$ for any prescribed $\delta>0.$ Then, $f(A)\subseteq \bigcup_j f(B_j)$ and each $f(B_j)$ is contained in a ball of radius less than $Cr_j$ so $|f(A)|\le C\sum |B_j|<C\delta.$


text:
Q: How to schedule automated tasks with power automate desktop I know power automate desktop does not yet have the scheduled tasks feature  but we can achieve the same via a perpetual loop as shown below and then running the flow to until the boundary conditions are met to trigger the action.
Please check the below shown image of a desktop flow which Ive created to emulate a daemon
proposed soultion

A: In this case PAD is the wrong tool for the job, rather look at a windows scheduled task and run something in powershell or command prompt (.bat file)
There is a saying that goes something like:
"Just because you've got a hammer doesn't mean everyting is a nail"


text:
Q: "Family Tree" of Theorems Is anyone aware of any attempt to describe the dependencies of theorems (perhaps in mathematics generally, perhaps in some limited areas) in the form of a "family tree"?  That is, each node on the tree might correspond to a theorem, and branches would indicate dependencies between theorems?  I realize that this would not constitute an actual tree -- as there can exist loops -- but this sort of meta-description of theorems might provide some insight not available in other manners.
[Added:] Except in some very formalized proof systems, making the  notion of dependency precise is probably difficult, if not impossible.  But colloquially, people will often make statements such as "Theorem A is used / can be used to prove Theorem B".  I'm sure everyone here can think of many such statements to which few will object.  For those cases, it might be very nice to have some accessible database with this information.  Not only might the data in this "graph" be practically useful (e.g., I want to write an expository paper about five interesting consequences of the Borsuk-Ulam theorem), but perhaps even some "meta-data" might provide valuable insight.  Just a thought.

A: Concerning (parts of) algebraic geometry, the Stacks Project offers so-called dependency graphs.

A: Formal vs self-organised knowledge systems: a network approach
A.P. Masucci, Physica A 390 (2011) 4652-4659 (arXiv:1105.1058)

In this work we consider the topological analysis of symbolic formal systems in the framework of network theory. In particular we analyse the network extracted by Principia Mathematica of B. Russell and A.N. Whitehead, where the vertices are the statements and two statements are connected with a directed link if one statement is used to demonstrate the other one. We compare the obtained network with other directed acyclic graphs, such as a scientific citation network and a stochastic model. We also introduce a novel topological ordering for directed acyclic graphs and we discuss its properties in respect to the classical one. The main result is the observation that formal systems of knowledge topologically behave similarly to self-organised systems.

This paper looks at how logical statements such as theorems are organized in specific expository works (like the Principia). As others have noted in the comments, outside such organized works, the dependencies can be ambiguous as theorems can have alternate proofs. Moreover, the order of deriving theorems is not canonical so that if all proof paths were included, cycles will have formed. The Principia is as good as any work to start with, but I would really love to see a similar analysis on Bourbaki and on Euclid's Elements.

Figure from the paper: distribution of in and out degrees in the Principia DAG, in the DAG of citations, and in a stochastic generative model.

A: There are fairly recent dependency graphs relating to Euclid's Book 1, Elements, in the literature.
See A Boxer's paper in Bridges Art/Math 2015
Also see M. Schiefsky (Harvard Classics) and Boman (Penn State Math) and Nyugen (Berkeley) for overviews and graphs.
The most interesting is that of Jesse Atkinson, Bridges Art/Math 2016, that shows a 3-D in-tree dependency graph of Euclid's proof of the Pythagorean Theorem (1.47) embedded in a discussion about the overall role of 1.45 and 1.47 in that book.  It is an elegant "little" paper, by an undergraduate math student, to say the least.

A: The idea of "dependencies" is somewhat ill-defined. The Reverse Mathematics Program has one way of defining dependencies by comparing the theorems over a very weak base theory called RCA0. To see nice diagrams stemming from this program, check out the Reverse Mathematics Zoo!


text:
Q: creating new array with combining same keys I have following array. (A var_dump output) I want to combine those same key elements to single array. How do I do that?
 array (size=3)
      'totals' =>
        array (size=3)
          0 =>
            array (size=1)
              'total' => string '4' (length=1)
          1 =>
            array (size=1)
              'total' => string '50' (length=2)
          2 =>
            array (size=1)
              'total' => string '44' (length=2)
      'styles' =>
        array (size=3)
          0 =>
            array (size=1)
              'style' => string '11' (length=2)
          1 =>
            array (size=1)
              'style' => string 'aaa' (length=3)
          2 =>
            array (size=1)
              'style' => string 'bb' (length=3)
      'colors' =>
        array (size=3)
          0 =>
            array (size=1)
              'color' => string '11' (length=2)
          1 =>
            array (size=1)
              'color' => string 'ccc' (length=3)
          2 =>
            array (size=1)
              'color' => string 'ddd' (length=3)

The final output should be like,
      'totals' =>
        array (size=3)
          0 =>
            array (size=1)
              'total' => string '4' (length=1)
              'style' => string '11' (length=2)
               'color' => string '11' (length=2)

     'styles' =>
        array (size=3)
          1 =>
            array (size=1)
               'total' => string '50' (length=2)
                'style' => string 'aaa' (length=3)
                 'color' => string 'bb' (length=3)

      'colors' =>
        array (size=3)
          2 =>
            array (size=1)
               'total' => string '44' (length=2)
                'style' => string 'ccc' (length=3)
                 'color' => string 'ddd' (length=3)

A: Try this :
NOTE : It is not maintaining the key => becomes numeric array, but does the functionality.
        $array = array("total"=>array(array("total"=>1),array("total"=>2),array("total"=>3)),
                "styles"=>array(array("style"=>4),array("style"=>52),array("style"=>6)),
                "colors"=>array(array("color"=>7),array("color"=>8),array("color"=>9))

);
array_unshift($array, null);
$res = call_user_func_array('array_map', $array);

echo "<pre>";
print_r($res);

output :
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [total] => 1
                )

            [1] => Array
                (
                    [style] => 4
                )

            [2] => Array
                (
                    [color] => 7
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [total] => 2
                )

            [1] => Array
                (
                    [style] => 52
                )

            [2] => Array
                (
                    [color] => 8
                )

        )

    [2] => Array
        (
            [0] => Array
                (
                    [total] => 3
                )

            [1] => Array
                (
                    [style] => 6
                )

            [2] => Array
                (
                    [color] => 9
                )

        )

)

A: Maybe this work
   for ($j=0; $j < count($your_array) ; $j++) {

        for ($k=0; $k < count($your_array[0]) ; $k++) {
            if(!isset($sum[$k]))
            {
               $sum[$k]=0;
            }else{
                $sum[$k]=$sum[$k]+$your_array[$j][$k];
            }
        }
    }

so the same key wilbe combine, where ever size on it :)


text:
Q: Is it possible to get JsonRootName of nested child with Jackson? I have nested objects that I want to get the root name from when I serialize it to json using jackson. this is the result I want(I apologize to all the flower enthusiasts but just needed a example, this is not to be interpreted as accurate data):
{
   "plants": "flowers",
   "types": {
       "rose" : {
           "color": "red",
           "height": 25,
       }
   }
}

I got 2 classes, one wrapper class:
public class JsonWrapper {
    public String plants = "flowers";
    public Object types;
}

and the "flower" class:
@JsonRootName("rose")
public class rose{
   public String color = "red";
   public int height   = 25;
}

now what I do is this:
JsonWrapper wrapper = new JsonWrapper();
wrapper.types = new rose();
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
String jsonInString = mapper.writeValueAsString(wrapper);

The result i get is:
{
 "JsonWrapper":{
 "plants": "flowers",
     "types": {
         "color": "red",
         "height": 25,
     }
 }
}

So i get the root name for the wrapper object that is not annotated but not for the child object that is annotated. is there a way to tell jackson not to get a root name where there is none and also analyze child objects?

A: An alternate solution without JsonRootName.

JsonWrapper.java

import java.util.HashMap;
import java.util.Map;

public class JsonWrapper {
    public String plants = "flowers";
    Map<String, Flower> types = new HashMap<>();

    public Map<String, Flower> getTypes() {
        return types;
    }

    public void setTypes(Map<String, Flower> types) {
        this.types = types;
    }
}

Flower.java

public class Flower {
    public String color = "red";
    public int height   = 25;
}

Main.java

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {

    public static void main(String[] args) throws JsonProcessingException {
        JsonWrapper wrapper = new JsonWrapper();
        wrapper.getTypes().put("rose", new Flower());
        ObjectMapper mapper = new ObjectMapper();
        String jsonInString = mapper.writeValueAsString(wrapper);
        System.out.println(jsonInString);

    }
}


text:
Q: Gradle: Test Java library on Android (I asked a similar question earlier, so I'll try a more general form and see if anybody knows how to do that.)  There's a Java library to which I have added patches for Android support.  I would like to automate testing of the code, but in order to check if it runs properly on Android, I need to test it on Android.  The library artifact is a jar, though, not an AAR or an APK, so I don't want to remove the old build modes, and so far my attempts to add the Gradle Android Plugin yields errors like The 'java' plugin has been applied, but it is not compatible with the Android plugins.
How can I continue to produce a plain Java jar, but also automatically test it on Android?  Do I need to, like, make a new submodule or something specifically for the tests?

A: Yes, usually it's a good practice to create a new module, say integration-tests, which in itself is an android library/app, and then you'd include your JAR/java lib in there and run android tests over it.


text:
Q: about making offline dictionary Before asking things, i am really sorry for all developers who are studying well, making well. Because person such like me would not be qualified in here to even ask a question. but i really, sincerly need help from people like you.
Currently i am studying in HUFS(Hankuk University of Foreign Studies) South korea.
My major is Polish(language in poland) and eventhough we already have a paper dictionary which were made by our professors but it is not that much useful because it is big and heavy to take everyday.
Do for my big plan, I want to make a dictionary app for my senior and also for my other friends who learn polish and more people who want to study polish alone.
But sadly I have never studied a JAVA in my whole life, maybe only the chance I could see JAVA in my life would be when I played minecraft.
So I decided to study as much as I can do alone with the book in library, but still so much hard. But i dont want to ask whole help for the project because it would be a very rude thing to ask. Also I know helping one person is also matter of money... ( in korea everyone, asked me about if i help you how much could you pay??)
Here is the 2 Big question about my project.
1. What do i need? 2. How Can I?
For the first model of my app, i think i might gonna add only simple searching system:
main menu -> button click -> (main activity changes) -> search screen comes out.
when the search screen comes out , there is search bar in the top , and
other part will be result list.
for this part i will use autocompletetext mechanism.
the problem is next.
if i searched
 on the search bar,
at the search result list, there might appear
1. Red
2. Reply
3. Read
like this.
but if i click word  can i connect to a new acitivity that shows word 's meaning?
all youtube videos only shows when you search it, the word comes out and it's all.
i want something like this

*

*I put a word "Re" on the search bar

*automatically finding words that contain "Re" from my db.

*click on of word that is on result list.

*IF, CLASSIFICATION that i put in DB, is "VERB", than open a mainactivity 13
that has form which can show you pastence, futuretence, have+p.p and meaning
4-1. if CLASSIFICATION that iput in DB, is "ETC", than open a mainactivity 12
that has form which only show(loads) meaning and explanation.

my db is like this.
enter image description here
first column is word that is private key.
second column is classification. which will classify if word is
"Verb", "Noun", "ETC", "Adjective", "Adverb"
3rd column is meaning.
4rth column is explanation or some example sentences.
form 5th is just all changeable format of words (dont mind it. it is for loading
some textures when you load certain mainacitivy)
So for the conclusion,
what i want to ask is "IS THERE ANY WAY for me to search, and then click, and then open new activities by giving option with db's "Classification"??"
i need your help.
i dont need money after making this app. i will be putting out for free for every koreans who would like to learn polish my him/herself.

A: You probably going to have to use a Recycle Views, its the best thing to use for handling click events, there is tons of examples online on using and implementing Recycle Views  but what you are trying to do shouldn't be difficult, check this out -> https://codereview.stackexchange.com/questions/141701/android-activity-with-a-recyclerview-inflated-by-a-big-arraylist
and -> Handle click item in Recycleview


text:
Q: Declaring an extension method in Angular 6 I come from a C# background and am trying to find an equivalent in implementing extension methods for types. I am using Angular 6, but I feel like this may be a typescript question as well.
I have declared a new file in my application:
// myExtensions.ts

import { TypeToExtend } from 'path_to_type';

declare module 'path_to_type' {
  interface TypeToExtend {
    newMethod(): string;
  }
}

TypeToExtend.prototype.newMethod = function(): string {
  return this.Whatever + ' Hello World';
};

And in one of my services I consume it as following:
typeToExtendObject.newMethod();

newMethod() shows up just fine in the VS Code intellisense, however when I actually run the application I see the error:

"typeToExtendObject.newMethod() is not a function"

Do I have to add this to my modules somehow? Am I not exporting this extensions module correctly?

A: It gets messy, mainly because most of your type information goes away after compilation.  You could write a function that takes an object (instance), and imbues that object with the method:
interface NewMethodable {
    newMethod(): string;
}
addExtension<T>(obj: T): T & NewMethodable {
    obj.newMethod = function ...;  // edited from original answer
    return <T & NewMethodable>obj;
}

This is very much off the cuff, so there are probably bugs.

A: Just use the export class then your class will be visible, and import it  where you want to use it. even the class could be static to not use a instance.
export class User {
  id: number;
  name: string;
  car: Car;

  newFunction(){
    //TODO
  }

}


text:
Q: How do I 'grep' for the longest chain of lines matching a regexp I'm running a program that outputs lines like these (simplified):
A
E
E
R
E

etc... And I'm trying to find the longest occurrence of the letter code E without something else in between. I suspect the easiest way would be to try looking for N consecutive where I try a couple descending values for N but I'm not sure how to do a specific case, say 3 consecutive E lines. Is this easy with a sed command? I thought of awk pattern range but it allows for anything in between..

A: using existing Unix tool set...
uniq -c file | sort -k2 -k1,1nr | awk '/E/{print $1;exit}'

uniq will give you the counts of sequences, sort by names and counts (in reverse order) so that highest run count will appear on top.  Let awk pick the highest sequence length which is the first by design.

A: With awk:
BEGIN { currCount = maxCount = 0;}
$0 == "E" { currCount++;
            if(maxCount < currCount) {maxCount=currCount; line=NR;}
            next
          }

       { currCount=0; }

END { print "max sequence is " maxCount " ending at line " line }

if the line must match the pattern instead of equal exactly the string, use of /E/ instead of $0 == "E"

A: Perl solution:
program | perl -lne '
               if (/E/) { $c++ }
                  else  { $c = 0 }
               $m = $c if $m < $c;
               }{
               print $m'

$m remembers the maximal count $c which is incremented for each E and set to 0 for each non-E.

A: $ uniq -c file | awk '/E/&&($1>m){m=$1} END{print m+0}'
2


text:
Q: How to escape special character ' \ '? I use php to retrive the data from table and ajax to display the result.
When I search using location for the 1st time, I get the result and the pagination is not working, especially for "istanbul".
The reason is the special character '\' added with the address that's taken from Google map.
The URL passed when i go to next page, is
http://www.mysite.com/dropinn/search/\"http://www.mysite.com/dropinn/search?checkin=mm%2Fdd%2Fyy&checkout=mm%2Fdd%2Fyy&guests=1&location=Istanbul%2C+Turkey&min_bathrooms=0&min_bedrooms=0&min_beds=0&per_page=10&search_view=1&sort=1&page=3"

How to over come this problem?
This is the code that I have written:
$config['base_url']   = site_url('search').'?checkin='.urlencode($checkin).'&checkout='.urlencode($checkout).'&guests='.$nof_guest.'&location='.urlencode($location).'&min_bathrooms='.$min_bathrooms.'&min_bedrooms='.$min_bedrooms.'&min_beds='.$min_beds.'&per_page='.$per_page.'&search_view=1&sort='.$sort;

A: Using double quotes, you escape \ with another \. If you need to display a \, then you must type \\, or you could use single quotes.
Example: echo "\hello\world"; would need to be echo "\\hello\\world";, or echo '\hello\world';

A: To escape in php, you must use \\
Try this:
http://www.mysite.com/dropinn/search/\"http://www.mysite.com/dropinn/search?checkin=mm%2Fdd%2Fyy&checkout=mm%2Fdd%2Fyy&guests=1&location=Istanbul%2C+Turkey&min_bathrooms=0&min_bedrooms=0&min_beds=0&per_page=10&search_view=1&sort=1&page=3\"

Or this:
http://www.mysite.com/dropinn/search/\\"http://www.mysite.com/dropinn/search?checkin=mm%2Fdd%2Fyy&checkout=mm%2Fdd%2Fyy&guests=1&location=Istanbul%2C+Turkey&min_bathrooms=0&min_bedrooms=0&min_beds=0&per_page=10&search_view=1&sort=1&page=3\"

Or lastly:
http://www.mysite.com/dropinn/search/\\"http://www.mysite.com/dropinn/search?checkin=mm%2Fdd%2Fyy&checkout=mm%2Fdd%2Fyy&guests=1&location=Istanbul%2C+Turkey&min_bathrooms=0&min_bedrooms=0&min_beds=0&per_page=10&search_view=1&sort=1&page=3\\"

Your question is a little confusing without seeing more code, but those should work.


text:
Q: generate access token using Postman I have written API using Django REST Frameword and Django oAuth Toolkit for oauth2 authentication and using Postman to test my API authorization process.
I have to send following curl request
curl -X POST -d "grant_type=password&username=<user>&password=<password>" -u "<client_id>:<client_secret" http://127.0.0.1:3333/auth/token/

I can generate access_token simply using Postman Get Access Token window

But I want to do it by sending a request and passing data using request form, so that I could test the API and also generate the documentation for auth.
Now, I can pass user data (username, password) in form-data but how to pass client_id and client_secret?

A: For a full Postman answer, the way to accomplish this is with a pre-request script. The client id and the client secret are simply encoded with the base64 encoding scheme. Just do this:

Notice that client_id_client_secret is an environment variable. If you don't want to do that, then drop the first line and hard-code your client id and secret into CryptoJS.enc.Utf8.parse('my-trusted-client:mysecret'), where 'my-trusted-client' is the client id and 'mysecret' is the client secret.
Here's the code for copy/paste joy.
let keys = pm.environment.get('client_id_client_secret');
let encoded = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(keys));
pm.environment.set("base64_client_id_client_secret", encoded);

Now, create a header and include the variable you created:

The value part of that image:
Basic {{base64_client_id_client_secret}}

Now... just Postman bliss.

A: curl encrypts the value of -u parameter, which we can see using -v (verbose)option.
Therefore, to collect the header's authorization value, use -v once with the curl command. It will print the raw request as following:-
$ curl -X POST -d "grant_type=password&username=<user>&password=<password>" -u "client_id:client_secret" http://127.0.0.1:3000 -v
Note: Unnecessary use of -X or --request, POST is already inferred.
* Rebuilt URL to: http://127.0.0.1:3000/
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to 127.0.0.1 (127.0.0.1) port 3000 (#0)
* Server auth using Basic with user 'client_id'
> POST / HTTP/1.1
> Host: 127.0.0.1:3000
> Authorization: Basic Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=
> User-Agent: curl/7.54.0
> Accept: */*
> Content-Length: 55
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 55 out of 55 bytes
< HTTP/1.1 200 OK
< Content-Type: text/plain
< Date: Sat, 19 May 2018 07:09:35 GMT
< Connection: keep-alive
< Transfer-Encoding: chunked
<

In the above verbose log, we can see the Key Value pairs as
> Authorization: Basic Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=

After collecting these key as "Authorization" and value as "Basic Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=", you can use them in headers of the request through postman. "Basic Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=" is the encrypted value generated using the -u "client_id:client_secret" option with curl.
Hope this will solve the auth problem using postman request.


text:
Q: How create CSV containing both file metadata and file content? Using Scripting Guy's code, I can create a csv that shows the metadata associated to the files on my computer:

I would like to add an additional column to this csv that contains the entire content of the file.  I found the Get-Content cmd and was able to get it to work, but I cannot figure out how to insert it into the code.
I've tried a variety of approaches:
if($objFolder.getDetailsOf($File, $a))
           {
             $hash += @{$($objFolder.getDetailsOf($objFolder.items, $a))  =
                   $($objFolder.getDetailsOf($File, $a))
                   & $($objFolder.get-content($File, $a)) }
            $FileMetaData | Add-Member $hash
            $hash.clear()
           } #end if

Error code: The hash literal was incomplete.
if($objFolder.getDetailsOf($File, $a))
           {
             $hash += @{$($objFolder.getDetailsOf($objFolder.items, $a))  =
                   $($objFolder.getDetailsOf($File, $a)) }
            $FileMetaData | Add-Member $hash
            $FileMetData | Get-Content($objFolder)
            $hash.clear()
           } #end if

Error code: a positional parameter cannot be found that accepts the argument 'recurse'
edit: here is the full code:
  Function Get-FileMetaData
{
Param([string[]]$folder)
 foreach($sFolder in $folder)
  {
   $a = 0
   $objShell = New-Object -ComObject Shell.Application
   $objFolder = $objShell.namespace($sFolder)

   foreach ($File in $objFolder.items())
    {
     $FileMetaData = New-Object PSOBJECT
      for ($a ; $a  -le 266; $a++)
       {
  if($objFolder.getDetailsOf($File, $a))
               {
                 $hash += @{$($objFolder.getDetailsOf($objFolder.items, $a))  =
                       $($objFolder.getDetailsOf($File, $a))}
                $FileMetaData | Add-Member $hash
                $hash.clear()
               } #end if
       } #end for
     $a=0
     $FileMetaData
    } #end foreach $file
  } #end foreach $sfolder
} #end Get-FileMetaData
$picMetadata  = Get-FileMetaData -folder (Get-childitem C:\Olivia\ -Recurse -Directory).FullName

$picMetadata |

Select Name,'Date created','Folder name'|

Export-CSV -Path C:\Olivia\metadata.csv -NoTypeInformation

A: OK so the issue was where to put the Get-content
You have 3 loops happening inside each other.

*

*The most outward is For each folder inside the array of folders from the parameters. This one creates a shell com object and get the information about the folder.

*The next one loops through every item inside the folder. And creates a PSObject $FileMetaData

*The last one and most inner gets the item details looping through 266 options. Then adds them to the PSObject.
Loop 2 is where we need to add a new property to the PS object and add the content so it only get looped once per Item. We also need to make sure its not a folder as a folder has no file contents.
This was the change added to the function in the 2nd loop
$FileMetaData | Add-Member -MemberType NoteProperty -Name Content -Value $(
    If($File.IsFolder -eq $false){
        Get-Content $File.Path
    }else{
        $null
    }
)

here is the remake of the function
Function Get-FileMetaData{
Param([string[]]$folder)
foreach($sFolder in $folder){
    $a = 0
    $objShell = New-Object -ComObject Shell.Application
    $objFolder = $objShell.namespace($sFolder)
    foreach ($File in $objFolder.items()){
        $FileMetaData = New-Object PSOBJECT
        for ($a ; $a  -le 266; $a++)
        {
            if($objFolder.getDetailsOf($File, $a))
            {
            $hash += @{$($objFolder.getDetailsOf($objFolder.items, $a))  =
                    $($objFolder.getDetailsOf($File, $a)) }
            $FileMetaData | Add-Member $hash
            $hash.clear()
            }
        }
        $a=0
        $FileMetaData | Add-Member -MemberType NoteProperty -Name Content -Value $(
            If($File.IsFolder -eq $false){
                Get-Content $File.Path
            }else{
                $null
            }
        )
         $FileMetaData
        }
    }
}


text:
Q: How to embed arguments into Robot Framework keyword name I've tried to make some keywords in Robot Framework which has arguments embedded in the keyword name, according to (Robot Docs), but unfortunately I'm always getting None when I'm checking what is under the variable. Did you meet such behaviour? What have I done wrong??
My keyword example:
Set ${object} state to ${state}
    Log To Console  ${object}
    Log To Console  ${state}

Let's assume that ${object} and ${state} are strings, so the call of this keyword looks like this:
${status}=  Run Keyword And Return Status  Set camera state to locked

A: Your code is fine. Here is a complete working example:
*** Keywords ***
Set ${object} state to ${state}
    Log To Console    ${object}
    Log To Console    ${state}

*** Test Cases ***
Example test case
    ${status}=        Run Keyword And Return Status    Set camera state to locked
    Should be True    ${status}


text:
Q: Is it possible to make a method inside an interface that takes list of method from that interface as parameter? Edit:
I finally decided to:

*

*Add SaveChanges() method to my repository, and make saving changes optional.

*Use TransactionScope and SaveChanges in my controller methods

The above should work and is simple to implement - this may not be the best approach, and is not direct answer to the question but it will have to do.
Original question:
I use the following repository pattern interface in my project:
public interface IRepository<T>
{
    KeyValuePair<bool, Exception> Create(T entityToAdd);

    KeyValuePair<bool, Exception> Create(List<T> entityListToAdd);

    KeyValuePair<bool, Exception> CreateOrUpdate(T entity);

    KeyValuePair<T, Exception> Get(int entityID);

    KeyValuePair<bool, Exception> Update(T entityToUpdate);

    KeyValuePair<bool, Exception> Update(List<T> entityListToUpdate);

    KeyValuePair<bool, Exception> Delete(int entityID);

    KeyValuePair<bool, Exception> Delete(List<int> entityIDs);

    KeyValuePair<List<T>, Exception> GetFiltered(Expression<Func<T, bool>> filter);

    KeyValuePair<List<T>, Exception> GetFiltered<TOrderBy>(Expression<Func<T, bool>> filter, Expression<Func<T,TOrderBy>> order);

    KeyValuePair<T, Exception> GetFilteredSingle(Expression<Func<T, bool>> filter);

    KeyValuePair<bool, Exception> UpdateCustomProperty<ValueType>(Expression<Func<T, bool>> filter, Expression<Func<T,ValueType>> property, ValueType value);
}

Problem is that I designed my method to call context.SaveChanges() at the end of successful operation, and now I need to do something more complex (create objects in two different tables in the same method), and this can cause trash data if - for example - first entity is created but second is not.
I would like to add a method to my repository, that takes list of methods (from the repository) as parameter - thus, I cold execute them one by one and call SaveChanges() only if all calls succeed.
How can I do something like this? I tried messing with Funct<> but since it needs fixed amount of function variables to work, it doesn't seem very suitable for the job.
Thanks in advance.
Best regards.

A: I would think about distributing responsibility between different types.
Concept may look like this:
public interface IDBSAve {} //generic interface

public class Table1Saver : IDBSave {} //class that saves ONLY in Table1
public class Table2Saver : IDBSave {} //class that saves ONLY in Table2

//business process that requires save in these 2 tables
var twoTablesBusinessProcess = new List<IDBSave> {new Table1Saver(), new Table2saver()};

//execute save in all calling chanin of this business process and if ALL
//succeed, confirm commit.
if(twoTablesBusinessProcess.All(save=>save.SaveTable()))
    context.SaveChanges();

I assume here that every type that derives from  IDBSAve interface implements bool SaveTable(..) method, that returns true if save suceed and false otherwise.


text:
Q: MySQL UPDATE only WHERE max() I'm looking to UPDATE the value of my Table_B from my Table_A where the id matches and where the Table_A.col1 value is maximal.
Consider that Table_A as two columns B_id and col1. Table_B has two columns id and col1
UPDATE Table_A, Table_B
SET Table_B.col1 = Table_A.col1
WHERE  Table_B.id = Table_A.B_id
--WHERE Table_A.col1 is maximal

I know that the last line of my query isn't correct but I can't figure out how to use MAX() here. Any thoughts?

A: UPDATE Table_B AS b
  JOIN ( SELECT B_id, MAX(col1) AS max_col1
         FROM Table_A
         GROUP BY B_id
       ) AS a
    ON b.id = a.B_id
SET b.col1 = a.max_col1 ;

A: AND TableB.col1 = (select MAX(col1) from TableB)

(mind the AND instead of WHERE)


text:
Q: Problems with variables sass i need some help try to compile variables to the main sass.  I have created a document sass with variables and i compiled this documente to the main sass: @import "../sass/helpers/_variables.scss" In this document is declared some variables like colors, fonts, etc. Well, whene i try to call some variables in other document sass (compiled to the main), SASS terminal tell me this problem :
  "status": 1,
  "file": "C:/Users/Rafager/Desktop/Inmobiliaria web/sass/desing/_header.scss",
  "line": 50,
  "column": 22,
  "message": "Undefined variable: \"$microsoft-regular\".",
  "formatted": "Error: Undefined variable: \"$microsoft-regular\".\n        on line 50 of sass/desing/_header.scss\n        from line 9 of sass/main.scss\n>>
     font-family: $microsoft-regular;\r\n   ---------------------^\n"
}

Note: The fonts is declared in other document called and called in the main: @import "../sass/bases/_fonts.scss" and this is the code:

@font-face {
    font-family: "Microsoft YaHei UI Regular";
    src: url("../../fonts/msyh.ttc");
}
@font-face {
    font-family: "Microsoft YaHei UI Bold";
    src: url("../../fonts/msyhbd.ttc");
}
@font-face {
    font-family: "Microsoft YaHei UI Light";
    src: url("../../fonts/msyhl.ttc");
}```

¿Could you help me please?-

A: You need to state what $microsoft-regular is.
In your variables set fonts with names such as:
$microsoft-regular: 'Microsoft YaHei UI Regular';
$microsoft-bold: 'Microsoft YaHei UI Bold';
$microsoft-light: 'Microsoft YaHei UI Light';


text:
Q: MYSQL PHP help with return a dataset Hey guys...I am trying to get some data based on a condition which I don't know how to write the code for.
My table looks like this:

id | meta_id | key      | value
--   -------   ---        -----

1  | 1       | image    | 0

2  | 1       | path     | 1

3  | 1       | location | parent

4  | 2       | image    | 1

5  | 2       | path     | 2

6  | 2       | location | self

From this how can i return the meta_id that has key = image and value = 1 and value = 2..so you see i have value 2 times...can this be done?

A: I hope I've understood
select * from table where key = 'image' and value in (1,2)


text:
Q: Suppress output from queries being executed using ADODB I am working on some old code using ADODB in PHP.  Queries look like this:
$query = "SELECT `foo`
          FROM `bar`;
$result = $conn->Execute( $query );

I am adding some AJAX functionality to the software but I realised that the Execute function is echoing/printing out the query - I don't want this:
(mysqlt): SELECT `foo`
           FROM `bar`

I believe mysqlt is the MySQL driver.
Is there a way to stop this output ?
Many thanks.

A: Try disabling debugging.
$query = "SELECT `foo` FROM `bar`";
$conn->Debug = false;
$conn->Execute($query);

Otherwise, try using output buffering:
ob_start();
$query = "SELECT `foo` FROM `bar`";
$conn->Execute($query);
ob_end_clean();


text:
Q: Убрать отступы между background Есть галерея

Вот код

Каким образом можно сделать обтекание без пропусков , что бы получилось как на картинке , желательно без привлечения javascript , только средствами css

A: С помощью колонок:
Поддержка браузерами 97.6%

.galery{
   -webkit-column-count:2;
    -moz-column-count:2;
    column-count:3;

    /*Отступ между колонками*/
    -webkit-column-gap: 0px;
    -moz-column-gap: 0px;
    column-gap: 0px;

    /*Отступ между картинками*/
    line-height:0;
}

.galery img{
     width:100%;
}

A: Например с помощью masonry grid:

$('.galleryLoad').masonry({
  itemSelector: '.aGalleryImg',
  percentPosition: true
});
img {
  max-width: 100%;
  width: 100%;
}

.aGalleryImg {
  width: 33%;
}

Такой еще вариант с flex:

img {
  max-width: 100%;
  width: 100%;
}

.aGalleryImg {
  width: 33%;
}

.galleryLoad {
  display: flex;
  flex-flow: column wrap;
  max-height: 650px;
  height: 100%;
}


text:
Q: Spring Integration poller hangs or stop after a while I have an application which reads JMS message coming from a HornetQ.
<int-jms:message-driven-channel-adapter
            id="myJmsChannelAdapter"
            channel="myJmsChannel"
            connection-factory="myCredentialsConnectionFactory"
            destination-name="${my.jms.topic}"
            pub-sub-domain="true"
            subscription-durable="${my.jms.subscription.durable}"
            client-id="${my.jms.client.id}"
            durable-subscription-name="${my.jms.subscription.name}"
            />

When a message arrive, I treat them via a poller
<!-- Send Jms message one by one to creation -->
<int:bridge input-channel="myJmsChannel" output-channel="jmsMessageCreateInputChannel">
    <int:poller max-messages-per-poll="1" fixed-delay="100">
        <int:transactional transaction-manager="transactionManager" propagation="REQUIRES_NEW"/>
    </int:poller>
</int:bridge>

The poller call a chain which store the content of the message in my DB
<chain id="jmsMessageCreate" input-channel="jmsMessageCreateInputChannel">
    <!-- extract the operation from the message itself -->
    <int-xml:xpath-header-enricher>
        <int-xml:header name="operation" xpath-expression="name(./node())" overwrite="true"/>
    </int-xml:xpath-header-enricher>

    <service-activator expression="@jmsMessageService.createNewJmsMessage(payload, headers['operation'])"/>
    <!-- have a JPA entity in the payload -->
    <gateway request-channel="persistEntityChannel"/>
    <logging-channel-adapter logger-name="JmsLogger" expression="'JMS message with operation ['+headers['operation']+'] created in DB'"/>
</chain>

My problem is the following, sometimes, for no apparent reason and without any error message in the logs, my messages are no treated anymore. The chain id jmsMessageCreate is not called anymore like if the poller stopped working.
If the server is restarted, it works well again but I have lost the JMS messages that were sent between the moment the poller stopped and the moment the server is restarted.
I really don't know where to look or what to do to prevent that. Maybe a change in the config?
Thanks in advance for your help.

A: Most likely the poller thread is "stuck" somewhere in your code. Use jstack <pid> to take a thread dump to see what the thread is doing. You can use jps to find the pid.
To avoid losing messages you should set acknowledge="transacted" on the message-driven adapter - this was changed to default to true in version 4.2.
You should not be using QueueChannels and pollers in this environment - the threading is managed by the message-driven adapter. With a queue channel, even with transacted sessions, the container will commit as soon as the message is put in the queue.


text:
Q: passing response ajax to handlebars I have some problem with handlebars,
I already import handlebars library and jquery, everything seems work fine.
The problem is when i have an response ajax and passing it to handlebars, then  i try to open the web it shows nothing.
javascript

handlebars template

view.blade.php

            Username

            Password

@include('/handlebars/user')

Thanks for your help


text:
Q: yii query with 4 table on CActiveDataProvider hi master i've 4 tables
-pegawai
   -penilaian
   -universitas
   -jurusan
I usually  use
    SELECT  u.nama_univ, j.singkatan, peg.* FROM pegawai AS peg LEFT JOIN penilaian AS pen ON pen.no_test=peg.no_test LEFT JOIN universitas AS u ON u.id=peg.univ_s1 LEFT JOIN jurusan AS j ON j.id=peg.bidang_s1

how to convert this query to yii ?
i've tried this code but it's not working well
$dataProvider = new CActiveDataProvider('Pegawai', array(
    'criteria' => array(
        'select' => array(
            '`pen`.*',
            '`u`.`nama_univ` AS `nama_univ`',
            '`j`.`singkatan` AS `singkatan`'
        ),
        'join' => 'JOIN `Penilaian` AS `pen` ON `pen`.`no_test` = `t`.`no_test`',
        'join' => 'JOIN `Universitas` AS `u` ON `u`.`id` = `t`.`no_test`',
        'join' => 'JOIN `Jurusan` AS `j` ON `j`.`id` = `t`.`no_test`',
    )
));

but only one join there's execute

A: Do one thing you just print the criteria object like
$dataProvider = new CActiveDataProvider('Pegawai', array(
    'criteria' => array(
        'select' => array(
            '`pen`.*',
            '`u`.`nama_univ` AS `nama_univ`',
            '`j`.`singkatan` AS `singkatan`'
        ),
        'join' => 'JOIN `Penilaian` AS `pen` ON `pen`.`no_test` = `t`.`no_test`',
        'join' => 'JOIN `Universitas` AS `u` ON `u`.`id` = `t`.`no_test`',
        'join' => 'JOIN `Jurusan` AS `j` ON `j`.`id` = `t`.`no_test`',
    )
));
echo "<pre>";
print_r($dataProvider);   //Check the object or try to post it below
exit();

A: You have assigned 3 values to the same index of array ('join') so only the last one is stored.
Try:
$dataProvider = new CActiveDataProvider('Pegawai', array(
'criteria' => array(
    'select' => array(
        '`pen`.*',
        '`u`.`nama_univ` AS `nama_univ`',
        '`j`.`singkatan` AS `singkatan`'
    ),
    'join' => 'JOIN `Penilaian` AS `pen` ON `pen`.`no_test` = `t`.`no_test` JOIN `Universitas` AS `u` ON `u`.`id` = `t`.`no_test` JOIN `Jurusan` AS `j` ON `j`.`id` = `t`.`no_test`',
)
));


text:
Q: jQuery animate height to auto I have a ul with an height of 125px. When a user hovers the ul i want that the height will animated to height auto. And when the user is out of the ul that the UL collpase to 125px again.
    $('.box .box-overflow ul').hover(function() {
        $(this).animate({
            height: '100%'
        }, 400);
    }, function() {
        $(this).animate({
            height: '125px'
        }, 400);
    });

This working but when a user comes in the ul it expand but not with a nice animated effect?
Can somewone help me with this? :)

A: You can do it with scrollHeight.
$('ul').hover(function(){
  $(this).animate({
    height: $(this)[0].scrollHeight+'px'
  }, 400);
}, function(){
  $(this).animate({
    height: '125px'
  }, 400);
});

A: try something like this on hover:
var height = $(this).css('height','auto').height();  // get real height
$(this).css('height','125px'); // return current state;
$(this).animate({height: height+'px'}, 400);

The activivty in first two lines should not bee seen by user, but you can get real height of your UL. You can make fancy sliding effect only if you know final height.
The working example is here: http://jsfiddle.net/axpFk/

A: Posted this elsewhere, but I feel like its useful here too: I made a little plugin that deals with this problem - should be fairly straightforward, based on Darcy Clarke's method which has been published here, with some (imo) very necessary improvements.  Just plug and play for jQuery:
https://github.com/azaslavsky/jQuery-Animate-Auto-Plugin


text:
Q: SQL Join using floating Where Date I have a 2 tables, one with activity generated information, the other with new contract information. Ultimately what I'm trying to do is see if within 30 days after the activity date, a new contract was generated. So for example:

The first table is the activities table, the 2nd the contract table. As you'll see for example, account ABC123 does have a new contract within 30 days of the activity date - CT-7135. However, CT-7695, although it exists in the table and is associated with account ABC123, would not satisfaction the "New Contract" requirement b/c it started outside of the 30 window since the activity date.
Account GJ1234 however would be a "no" b/c there is no contract in the table that is within 30 days of the activity date. Likewise CGE435 (because of CT-4389) and GHE568 (because of contracts CT-4389, CT-8080 AND / OR CT-6690 ---- BUT NOT because of CT-6829) both qualify.
I guess my issue is trying to do this dynamic join off of activity date b/c it's different for each line items.
Thoughts?
Thanks.

A: Try this:
Select Distinct AccountId
From Accounts a
Where Exists
    (Select * From contracts
     Where AccountId = a.AccountId
       And ContractDate >= a.ActivityDate
       And DateDiff(day, a.ActivityDate, ContractDate) <= 30)

A: The following will find all the accounts that have had a new contract within 30 days of the activity:
SELECT * FROM activities AS A WHERE AccountID IN (SELECT DISTINCT(AccountID) from contracts WHERE ContractStartDate >= A.ActivityDate AND ContractStartDate <= DATE_ADD(A.ActivityDate, INTERVAL DAY 30))


text:
Q: Integer division in Mixed Integer Linear Programming What is a solver friendly way of encoding integer division in MILP programs? Currently I'm using the following encoding (in Gurobi python), which may not be totally correct and I hope not that optimal.
# res is an integer variable in the solver
# val is an integer variable in the solver
# divVal is just a python variable, a constant for solver
offset = 0.999
divRes = val / divVal
model.addConstr(divRes - offset <= res)
model.addConstr(res <= divRes)

Above encoding essentially says that res should be assigned a value between divRes - offset and divRes, since offset is 0.999, there should be only 1 integer in the range and solver is forced to assign that to res. Is there a better (faster) way of encoding this?
EDIT: By integer division I mean that the result of division is an integer. If there is any fractional part after the division, I want to discard that and round down the result which will be stored in res. What I essentially want to do is shift a number by some x bits. In MILP solver, that boils down to dividing a number by (1 << x), but there is some fractional part after the division which I want to get rid of.

A: model.addRange(val - divVal*res, 0, 0.99999, name="Range")
I would prefer to use this above mentioned Range Constraint only. Incorporating tighter bounds (there is only integer in the given range, which we require) directly into the model can not only improve the numerical behavior, but it also speed up the optimization process (because gurobi use branch and bound algorithm to get solutions)
https://www.gurobi.com/documentation/9.1/refman/improving_ranges_for_varia.html
Optimality - A small change in model can easily calculate an optimal result, adding res in a Minimisation type objective function or negative of it in the maximisation function would shrink its value at lower side if divVal*res will become integer. Gurobi does not provide Less than constraint. Moreover, An integrality restriction on a variable is considered satisfied in Gurobi when the variable's value is less than IntFeasTol from the nearest integer value. Default value of IntFeasTol tolerance is 1e-5, and it could be further reduced up to 1e-9 for a better result. However, making multi-objective model, add extra complexity to the model. I would not like to recommend it.
model.addRange(val - divVal*res, 0, 1, name="Range")
model.setObjective(res, GRB.MINIMIZE)


text:
Q: bxslider isn't displaying images until page resize with responsive design I am trying to implement bxslider on a responsive page (using Bootstrap) and for the first 2 or 3 times it is showing images correctly. However after that it just shows a narrow white band:

If I resize the browser then the bxSlider resizes correctly and displays the images.
My partial code contains the following code (Note, this populates a div as a result of an AJAX call)

  <% @product.images.each do |image| %>

<%= image_tag image.image.url %>

  <% end %>

The bxslider setup is working correctly as I do always get the expected output to console.
I have replicated this behaviour in Safari, Chrome and Firefox.
From my searches most people who have had resize issues with bxslider were having issues when resizing the browser, not on initial load.
Edit
Setting an initial fixed height for the layout of the bxslider displays all images at once (including 2 extra - which I assume are for buffering the navigation). Again only a browser resize forces the bxslider to resize and display correctly.
.bx-viewport.bx-viewport {
  min-height: 90px;
}

This is suggesting that perhaps the issue isn't, as I originally believed, a result of misbehaving with responsive layouts.
Perhaps the following information is pertinent to this question. I am using Rails and the page I posted earlier is a result of an AJAX invocation of ProductsController#show action. There doesn't appear to be anything esoteric going on here:
ProductsController#show
  def show
  end

show.js.erb
  $('#product-details').html("<%= escape_javascript(render 'products/show') %>")

_show.html.erb
as posted at start of question
invocation
<%= link_to 'Show', product, remote: true %>

A: That happens to my projects when the first slide has a video. bxSlider sometimes will go to a strange default height if it takes too long on initial calculation of .bx-viewport. Typically, it will reload the correct height on a refresh or even a transition of a slide. Try this:

.bx-viewport.bx-viewport {
   min-height: 90vh;
}

Adjust the value to your specific needs, but I recommend that you use an intrinsic or absolute unit of measurement such as vh or px, and avoid relative measurements like percentages or em.
Another fix is like the previous one, but counter-intuitive:

`$('.bx-viewport`).height(0).css('min-height', '80vh')`;

@David has found the solution by using the opposite of what I use, suggesting that his site burdens bxSlider less than mine does. bxSlider does not hang on every loading error or timeout, it has a tendency to continue and start making shortcuts. Unfortunately, the calculation for .bx-viewport's height is a common shortcut victim, resulting in a narrow bxSlider (.bx-viewport {height:0}).

`$('.bx-viewport').css('height', '');

This and previous techniques will "wake up" bxSlider into recalculating .viewport height. Either one does the same thing, but mileage varies per user.

A: Out of curiosity, this might work.
$(function () {
  // Your code.
  $(element).bxSlider({
    // options.
  });
  // Add this.
  $(window).trigger("resize");
});

So, all that you need to do is, add this little code after bxSlider loading:
$('.product-view-bxslider').bxSlider({
  onSliderLoad: function(){
    console.log('finished loading');
  }
});
// Add this.
$(window).trigger("resize");


text:
Q: Jacobian or No Jacobian - Surface Integrals I've read http://www.physicsforums.com/showthread.php?t=310220 and http://www.physicsforums.com/showthread.php?t=458840, but I'm still confused whether we need the Jacobian or not in computing surface integrals. The following examples are from P1091 and 1092 in Section 16.7 from Calculus, 6th Edition, by James Stewart. Why is there a Jacobian for #23 $\color{red}{\text{in red}}$ but NOT for #15 and #47?

$\Large{\text{15.}}$ Evaluate the surface integral:
  $\iint_Sz(x^2 + y^2) dS $ where $S$ is the hemisphere $x^2 + y^2 + z^2 = 4, z \geq 0$.
$\Large{\text{23.}}$ Evaluate the surface integral $\iint_S \mathbf{F} \cdot d\mathbf{S},$ where $\mathbf{F} = (x,-z,y)$ and $S$ is the part of $x^2 + y^2 + z^2 = 4$ in the first octant and oriented towards the origin. Remember to use the positive (outward) orientation.
$\Large{\text{47.}}$ Let $\mathbf{F(r)}$ = $\cfrac{c\mathbf{r}}{{\vert \mathbf{r} \vert}^3} $ for some constant $c$ and $\mathbf{r} = (x,y,z) $ and $S$ be a sphere with center the origin.  Show that the flux of $F$ across $S$ is independent of the radius of $S$.

Given solutions:

$\Large{\text{15.}}$ Parameterise with spherical coordinates : $x = \color{green}{2}\cos\theta\sin\phi,  y = \color{green}{2}\sin\theta\sin\phi, z = \color{green}{2}\cos\phi.$ Then
  $\iint_Sz(x^2 + y^2) dS = \int_0^{2\pi}\int_0^{\pi/2}[4\sin^2\phi2cos\phi]
\underbrace{(4\sin\phi)}_{\vert \partial_{\phi} \mathbf{r} \times \partial_{\theta} \mathbf{r} \vert} \require{enclose} \enclose{horizontalstrike}{(p \color{green}{= 2})^2\sin\phi}  dA $.
$\Large{\text{23.}} $ $\iint_S \mathbf{F} \cdot d\mathbf{S} = \iint \mathbf{F} \cdot \mathbf{\hat{n}} dS = \iint_{x^2 + y^2 \leq 4} \dfrac{-x}{\sqrt{4 - x^2 - y^2}} dA = \int_0^{\pi/2}\int_0^{2}
\dfrac{-(r\cos\theta)^2}{\sqrt{4 - r^2}} \color{red}{(r dr d\theta)}. $
$\Large{\text{47.}}$ Let the sphere's radius $:= \vert \mathbf{r} \vert := k$. Parameterise with spherical coordinates : $x = \color{brown}{k}\cos\theta\sin\phi\,  y = \color{brown}{k}\sin\theta\sin\phi, z = \color{brown}{k}\cos\phi.$
Then $\iint_S \mathbf{F} \cdot d\mathbf{S} = \iint_D \mathbf{F[r}(\phi, \theta)] \cdot (\partial_{\phi} \mathbf{r} \times \partial_{\theta} \mathbf{r})  dA  $ $
= \int_0^{\pi}\int_0^{2\pi} \frac{c}{k^3}(k\cos\theta\sin\phi\,  k\sin\theta\sin\phi, k\cos\phi) \cdot (k^2\cos\theta\sin^2\phi, k^2\sin\theta\sin\phi, k\sin\phi\cos\phi) \require{enclose} \enclose{horizontalstrike}{(p\color{brown}{= k})^2\sin\phi}d\theta d\phi$

$\Large{\text{Supplementaries in response to Muphrid's answer:}}$
$\Large{\text{Q1.}}$ In your first paragraph, you wrote that if $\mathbf{r}(x,y)$ then $\partial_x \mathbf{r} = \mathbf{\hat{x}} $ and $\partial_y \mathbf{r} = \mathbf{\hat{y}} $. How is this true?
For example, if $\mathbf{r}(x,y) = (x, y, z(x,y))$ then $\partial_x \mathbf{r} = (1, 0, \partial_xz) $ and $\partial_y \mathbf{r} = (1, 0, \partial_yz) $?
$\Large{\text{Q2.}}$ In your sixth paragraph, you wrote: "Here, we don't have the area element vector expressed in a coordinate system yet, so it doesn't make sense to use (say) Cartesian and then push it forward with the Jacobian."
In your last paragraph, you wrote: "The solutions here skip the Jacobian..."
However, are you only referring to #15 and #47 here? With many thanks to you, I now understand that #15 and #47 start and remain working with spherical coordinates.
But in #23, my understanding is that the solution starts with $(x, y, z(x,y))$. Then it uses the Jacobian ($r dr d\theta$) while converting to polar coordinates. #23 is the only question for which the Jacobian is used (and not in #15 or #47).
$\Large{\text{Q3.}}$ In your third paragraph, you commented on "why this integral is phrased in terms of $r$ at all." I'm inferring that you disagree with the solution's choice of starting with $(x, y, z(x,y))$? You (and I) believe that only spherical coordinates should be used the whole time because of convenience?

$\Large{\text{Supplementary in response to Muphrid's 2nd answer:}}$
$\Large{\text{Q2.1}}$ Many thanks for your second answer. You wrote in your second answer, for problem #23:  "...But I must emphasize that that, in itself, is not using the Jacobian matrix, because the Jacobian matrix must act on some vector, converting it from one coordinate system to another.  Since they don't write down the cartesian components of $\hat{\mathbf n}$, it doesn't seem to me that they're actually using it."
How does solution for #23 NOT use the $\color{magenta}{\text{Jacobian}}$? The solution starts with $(x, y, z(x,y))$ and then convert to polar coordinates.
$\Longrightarrow \iint_R f(x,y, z(x,y)) dA = \iint_D f(r\cos\theta, r\sin\theta, z(r\cos\theta, r\sin\theta) \color{magenta}{\underbrace{\dfrac{\partial(x,y)}{\partial(r,\theta)}}_{\huge{= ... = r > 0}}} dr \, d\theta  $
(More info on Stewart P1017)

A: When you do an integral over a surface in coordinates, we use basis vectors to talk about directions and their cross products to talk about areas.  For instance, we can parameterize a surface in (edit) $s, t$ and talk about the differential area $d\mathbf A= ( \partial_s \mathbf r \times \partial_t \mathbf r) \, ds \, dt$.  Of course, if the surface if one of constant $z$, then we can parameterize in terms of $x,y$ and $\partial_x \mathbf r = \hat{\mathbf x}$, and $\partial_y \mathbf r = \hat{\mathbf y}$, so we get $d\mathbf A = \hat{\mathbf x} \times \hat{\mathbf y} \, dx \, dy$.
In (15), the same approach is used, but using $\theta, \phi$ instead of $x, y$.  You could use the Jacobian and get the same answer by expressing $dx$ in terms of $dr, d\theta, d\phi$ and similarly for $dy$, but it's not really necessary.
In (23), it's not clear to me why this integral is phrased in terms of $r$ at all, since the surface is a sphere and thus lies at constant $r = 2$.  Nevertheless, you can use the same approach.
$$d\mathbf A = (\partial_r \mathbf r \times \partial_\theta \mathbf r) \, dr \, d\theta$$
We get $\partial_r \mathbf r = \hat{\mathbf r}$ and $\partial_\theta \mathbf r = r \hat{\boldsymbol \theta}$. That explains where the extra $r$ comes from.
(47) is worked the same way, again using $\theta, \phi$.
Now, you may be wondering, if you can find all these area elements without using the Jacobian, then why do people say "use the Jacobian"?  Well, that's because, if you already have the vector of the area element expressed in one coordinate system, you can move it to another using the Jacobian.  Here, we don't have the area element vector expressed in a coordinate system yet, so it doesn't make sense to use (say) Cartesian and then push it forward with the Jacobian.
It's easiest to demonstrate this with a line integral.  Consider a line integral with differential $d\boldsymbol \ell = \partial_x \mathbf r \, dx$.  Let $u = u(x)$ be some function, so that the integral can be equivalently phrased as $d\boldsymbol \ell = (\partial_u x)(\partial_x \mathbf r) \, du = \partial_u \mathbf r \, du$.  This all comes from the chain rule, and $\partial_u x$ is the 1d version of the Jacobian.
So what are we doing with the Jacobian?  We're taking derivatives of $\mathbf r$ with respect to one set of coordinate and converting them to derivatives with respect to another set of coordinates.  The solutions here skip the Jacobian because they take derivatives in spherical coordinates directly.
Edit:
1) You're correct; I was talking about a surface of constant $z$ (and was lazy in doing so).
2) My point is merely that you can derive $d\mathbf A = r \hat{\boldsymbol \phi} \, dr \, d\theta$ quite easily in a direct fashion, rather than expressing the vector in cartesian, writing out the Jacobian matrix, and then pushing it forward into a spherical coordinate system.
Since they know the answer, I think honestly they just knew $dA = r \, dr \, d\theta$ and thought nothing of it. After working with spherical and polar coordinate systems long enough, you kind of just know these things.  But I must emphasize that that, in itself, is not using the Jacobian matrix, because the Jacobian matrix must act on some vector, converting it from one coordinate system to another.  Since they don't write down the cartesian components of $\hat{\mathbf n}$, it doesn't seem to me that they're actually using it.
3) I'm referring to something more fundamental.  They say quite clearly that this should be "the surface of a sphere", which by definition doesn't vary with $r$, and so $r$ should not be integrated over, and yet they end up with an expression that does depend on $r$, which makes no sense.  It's like they're integrating over some completely different surface from what they describe.
As for using spherical coordinates, yeah, if you're just going to transform into those coordinates anyway, they should be used from the outset.  Parameterizing these surfaces in another coordinate system is largely a pointless exercise; one of the main advantages of working in other coordinate systems is to simplify integrals and to match the natural symmetries of a given problem.


text:
Q: Simple moderation in PROCESS: What does it mean if the interaction is not significant but some of the conditional effect of X on Y are significant? I have conducted a simple moderation analysis in SPSS using the PROCESS macro and I've found that the interaction XM is not significative (p=0.87), but almost all three conditional effects of X on Y at values of the moderator are significative:

*

*Moderator=1.64 Effect=1,17 p=.00 95% CI [0.38 - 1,97]

*Moderator=2.58 Effect=1,22 p=.00 95% CI [0.66 - 1,79]

*Moderator=3.52 Effect=1,27 p=.00 95% CI [0.45 - 2,09]

The same happens with the Johnson-Neyman technique, as I see that Moderator value(s) defining Johnson-Neyman significance region(s):
Value= 4.50 % below=98.44 % above=1.56
I'm truly lost. Can anybody help me with the interpretation of these results? How can it be that all the conditional effects of X on Y at values of the moderator are significant, but the interaction XM is not?

A: The interaction is the degree to which the effect of the focal predictor changes based on different levels of the moderator. The focal predictor might have a significant effect at all levels of the moderator; in fact, this is what you see. But the effect of the focal predictor may not vary much at different levels of the moderator. In your example, for large changes in the moderator, the effect of the focal predictor changes very little.