text:
Q: Validating a LaTeX file, java So I have this text file
\begin{document}
    {\Large \begin{center} Homework Problems \end{center}}\begin{itemize}\item\end{itemize}
    \begin{enumerate}
                    \begin{proof}
                            \begin{align}

                            \end{align}
                    \end{proof}

                    \begin{proof}

                            \begin{align}

                            \end{align}

                    \end{proof}
    \end{enumerate}
\end{document}

And I want to go through each line, find all of the "\begin" pieces and then take the string with in the "{_}" and store it in a stack. When the corresponding "\end" is found, I call the pop() command on the Stack and remove it. I'm have a few issues though...

*

*I'm running into dealing with all sorts of crazy cases and making sure everything is accommodated and its becoming too specific to this case when I want to make it work for all sorts of files that are written as such.

*I don't know how to check for "\begin" and "\end" as opposed to "begin" and "end", the reason this is important is because if the file contains text that says "begins" or "end" it might not be a command and thus, not what I'm looking for.

All "if" statements DO NOT work on account of the "\" being present, I tried adding square brackets but it didn't fix anything.
Here is my code so far, and its getting really confusing, can anyone help organize and help rectify the issues I've stated above?
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;

public class LaTeXParser{

public static void main(String args[]) throws FileNotFoundException{

    Scanner scan = new Scanner(System.in);

    Stack s = new Stack();

    int lineCount = 0;

    String line;
    String nextData = null;
    String title = null;

            String fname;

            System.out.print("Enter the name of the file (no extension): ");
            fname = scan.next();

            fname = fname + ".txt";

            FileInputStream fstream = new FileInputStream(fname);

            Scanner fscan = new Scanner(fstream);

            System.out.println();

            while(fscan.hasNextLine()){

                lineCount++;
                line = fscan.nextLine();
                StringTokenizer tok = new StringTokenizer(line);

                while(tok.hasMoreElements()){

                    nextData = tok.nextToken();
                    System.out.println("The line: "+nextData);

                    if(nextData.contains("\\begin") && !nextData.contains("\\end")){

                        if(nextData.charAt(1) == 'b'){

                            title = nextData.substring(nextData.indexOf("{") + 1, nextData.indexOf("}"));

                            s.push(title);

                        }

                        else{

                            //title = nextData.substring();

                        }
                    }//end of BEGIN if

                    if(nextData.contains("\\end") && !nextData.contains("\\begin")){

                        if(s.peek().equals(nextData.substring(nextData.indexOf("{") + 1, nextData.indexOf("}")))){

                            s.pop();

                        }
                    }//end of END if

                    if(nextData.contains("\\begin") && nextData.contains("\\end")){

                        String[] theLine = nextData.split("[{}]");

                        for(int i = 0 ; i < theLine.length ; i++){

                            if(theLine[i].equals("\\end") && theLine[i+1].equals(s.peek())){

                                s.pop();

                            }

                            if(theLine[i].equals("\\begin")){

                                title = theLine[i+1];

                                s.push(title);

                            }

                        }

                    }//end of BEGIN AND END if

                }
            }//end of whiles

            fscan.close();

    while(!s.isEmpty()){

        System.out.println("the top "+s.pop());

    }
}
}

EDIT: In the if statement that is used to check a line to see if it contains both a "\begin" and "\end" after finding the "\begin", how do I go back through to check if that line also contains it's "\end"? So I am talking about the case...
\begin{itemize}\item\end{itemize}

See I can get to the "\begin" and add the proper string, but it just moves and passes the "\end{itemize}". Anyway to fix this?
Actually it should check and perform normally even after the "itemize" string is pushed, but it doesn't work! I believe it has to do with "\end", can anyone confirm? It skips over that step, and obviously because it doesn't fit the conditions, but it works for the other lines. Just not this specific case!

A: You probably need to escape the backslashes, so write \\ instead of \. And if they are in regular expressions (regexprs) you need to escape them twice: \\\\ ; I don't think the brackets are needed.


text:
Q: time function and comparison I create nodes that have different dptr_time, for example 8:00, 12:00, 14:00.
I want to find all the nodes that have dptr_time that are with 30mins of lets say 11:45. I can't find a time function, is there an easy way to do that in cypher

A: Easist way is to store dptr_time in millis since epoch as numeric value instead of a string representation like "8:00". Numeric values can be easily filtered using:
START n=node(....)
WHERE n.dptr_time>[lower_boundary_in_millis] and n.dptr_time<[upper_boundary_in_milles]
RETURN n

redpajama_set_name: RedPajamaStackExchange


text:
Q: Inconsistent display of TraditionalForm in version 9 After installing version 9, the default style sheet uses Arial font in text and formula cells. So far, so bad. At least one would hope this is done consistently.
But now I see this:

You can see that the default font for TraditionalForm in output cells is Times, which will make such output look disjoint from the equations in inline or displayed maths. The $1$ on the output line has serifs, while the 1 on the third line (in the text cell) are sans-serif. This is what I would call visually disjoint, or incongruous.
What would be the best way to change the default font for the TraditionalForm output so that it always remains consistent with Arial (i.e., is displayed as sans-serif) when the default stylesheet is chosen?
I am aware that I could also try to change the default stylesheet back to version-8 style as discussed in "How to use version 8 default.nb style sheet in place of version 9 default.nb" - but here I'm asking what to do if I don't want to go back to Times font, only trying to get a more uniform sans-serif appearance.
Edit
Sorry to say that the inconsistencies extend far beyond the above.
I only realized this morning that many important math symbols remain in the old form that was based on Times glyphs, even when the rest of the expression is converted to Arial. Here is a screenshot where I typed the math symbol paired with a corresponding normal Arial character - first some double-struck glyphs, then $\hbar$, then some Greek. The square root also looks unchanged from Times font, which may be OK but isn't how I recall sans-serif square roots looking. One important problem in the juxtaposition between pairs of special and normal characters is not just the presence versus absence of serifs, but also the general mismatch in the heights.

The last comparison between $l$ and $I$ is of course just a reminder of how bad the Arial font is on general grounds, I'm not asking how to fix that...
As a result, I think the inconsistencies I'm worried about can't be removed completely until a whole new set of glyphs is added to the Arial font. I'll have to give it some more time before perhaps accepting one of the answers, although I'm not at all happy and currently waiting for a miracle.
Edit 2
Two alternative titles for this question:

*

*How to un-xkcd TraditionalForm equations in version 9?

*Will Frankenformulas take over the world?

Update: the second part of this question appears to have been fixed in version 10.1 (except that I still think Arial is a bad font for math typesetting). However, the first part is still unchanged.

A: To specify the style of inline formula, there is a style called "InlineCell". Add the following to the stylesheet would do it:
Cell[StyleData["InlineCell"],
 LanguageCategory->"Formula",
 FontFamily->"Arial"]

Or specify the "TraditionalForm" style as Rojo said to make sure the font used in inline formula is consistent with it used in stand alone TraditionalForm cell.
Note that "InlineCell" style has a higher priority level than "TraditionalForm" style.

A: I have no clue yet why this behaves like it does, but if I understood you correctly this workaround would perhaps suit you.
You want all traditional form to display in Arial? Then open your Default.nb stylesheet, add the style TraditionalForm (by typing it in the InputField above), select it, open the Options Inspector and set FontFamily explicitly to Arial
The TraditionalForm style does not specify a font family by default, and I still haven't found where it inherits Times from for Input and Output cells, and I can't test a lot right now...

A: Not an answer. Please do not upvote nor downvote me. I just need to show Jens what I get on V9 since I switched to Default_8.nb now. (can't paste images in comments) It looks ok now.


text:
Q: How can we create Mega Menu in SharePoint Classic Publishing site? I tried to look into many blogs but did not find and correct direction to create Mega Menu in SharePoint Classic Publishing site

A: I'm not associated with this company, but I've used them in the past, for $150 you can't code a solution that cheap.
https://www.sharepointmegamenus.com


text:
Q: Бан аккаунта разработчика Google Play Начнем с того, что все было хорошо: выполнял задание на фрилансе. Делал конвертацию сайта в приложение. Сделал, далее создал аккаунт разработчика Google и затем выложил приложение. Казалось бы, что приложение прошло публикацию и даже какое-то время спустя был доступ к Google Play Console, однако спустя ровно 1 день мне прилетело вот такое сообщение на почту:

This is a notification that your Google Play Publisher account has been terminated.
REASON FOR TERMINATION: Prior violations of the Developer Program Policies and Developer Distribution Agreement by this or associated accounts as outlined in previous emails sent to the registered email address(es) of the Publisher account(s).
Google Play Publisher suspensions are associated with developers, and may span multiple account registrations and related Google services.
You can visit the Developer Policy Center to better understand how we enforce Developer Program Policies. If you've reviewed the policy and feel this termination may have been in error, please reach out to our policy support team.
Do not attempt to register a new developer account. We will not be restoring your account at this time.
The Google Play Team

Где и в каком месте были нарушены соглашения тот еще вопрос. Кто знает, как вернуть аккаунт?


text:
Q: Finding missing number in unordered arithmetic progression takes too long I am working on the Code Wars challenge Missing number in Unordered Arithmetic Progression:

If you have not ever heard the term Arithmetic Progression, refer to a previous code challenge:

An Arithmetic Progression is defined as one in which there is a constant difference between the consecutive terms of a given series of numbers. [...] There is however one hitch: exactly one term from the original series is missing from the set of numbers which have been given to you. The rest of the given series is the same as the original AP. Find the missing term.

And here is an unordered version. Try if you can survive lists of MASSIVE numbers (which means time limit should be considered). :D
Note: Don't be afraid that the minimum or the maximum element in the list is missing, e.g. [4, 6, 3, 5, 2] is missing 1 or 7, but this case is excluded from the kata (i.e. the code challenge).
Example:
find([3, 9, 1, 11, 13, 5]) # => 7

My solution code works just fine in 99% of test cases. Nevertheless, a random test with big enough input always exceeds the permissible execution time.
function find(seq) {
    function compareNumbers(a, b) {
        return a - b;
    }
    let arr = [...seq].sort(compareNumbers);
    let difference = arr[1]-arr[0];
    let arrLen = arr.length;
    let i=0;
    while(i<arrLen){
        if(arr[i+1]-arr[i]!==difference) return arr[i] + difference;
        i++;
    }
}

I suppose there are some improvements to be made in the sort algorithm or the while loop. I've tried to replace the sort algorithm with a QuickSort one, but that didn't help.

A: As the code challenge guarantees that the minimum and maximum are present in the input, you can derive the step from the following info:

*

*minimum

*maximum

*length

Given the minimum and the step, you can easily go through the sequence of expected values and verify they are in the set of input values.
Here is an implementation:
function find(seq) {
    let low = seq[0];
    let high = low;
    for (let i of seq) {
         if (i < low) low = i;
         else if (i > high) high = i;
    }
    let step = (high - low) / seq.length;
    let set = new Set(seq);
    for (let i = low + step; i < high; i += step) {
        if (!set.has(i)) return i;
    }
}

NB: I didn't use Math.min(...seq) here, as for very large arrays that will run into stack size limitations.
Alternative solution
As discussed in comments, we could calculate what the expected sum would be if there were no missing number in the sequence (based on the minimum and maximum in the input, and its length) and subtract the actual sum from that: the difference would be the missing number.
As this sum could be large and even overrun the maximum safe integer for the number data type in JavaScript, we should then shift the input numbers to a "safe" area (around 0) so that the sum will be close to zero. This way we avoid the inaccuracies that would be introduced if the sum would move out of the safe-integer range.
Here is how that looks:
function find(seq) {
    let low = seq[0];
    let high = low;
    for (let i of seq) {
         if (i < low) low = i;
         else if (i > high) high = i;
    }
    let step = (high - low) / seq.length;
    let mid = low + Math.floor((high - low) / 2);
    let expectedSum = (low - mid + high - mid) * (seq.length + 1) / 2;
    let sum = 0;
    for (let i of seq) {
        sum += i - mid;
    }
    return expectedSum - sum + mid;
}


text:
Q: FullCalendar do not show event blocks and instead display a customized text? is there a way to hide or not to display event blocks and at the same time use a customized text?

A: Like EatPeanutButter says I can customize the appareance of events with eventRender:
eventRender: function(event, element) {
            console.log(event);
            console.log(element);
            element.text("a bigger text for this object, you can modify element as you want now with another label");
        },


text:
Q: Weird glitch in UITableView section header when reloading section above Have a look at this video.
I get this glitch when running this code:
[NSFetchedResultsController deleteCacheWithName:@"Root"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"following == YES"];
[self.fetchedResultsController.fetchRequest setPredicate:predicate];
[self.fetchedResultsController performFetch:nil];
[self.tableView beginUpdates];
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:THE_SECTION_WITH_THE_BLOGS] withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tableView endUpdates];

Why does the section header below the section I reload change it frame like this? Any solutions?
EDIT:
This is my viewForHeaderInSection:
(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
if (tableView != self.tableView)
return nil;
BLMenuTableSectionHeaderView *view = nil;

if (section != BLMenuSectionUser) {
    view = [[BLMenuTableSectionHeaderView alloc] initWithFrame:CGRectZero];
    if (section == BLMenuSectionFollowing){
        if ([self blogCount] > 0){
            [view setTitle:NSLocalizedString(@"Following", nil)];
            [view addSubview:self.editButton];
        }else{
            self.tableView.editing = NO;
        }
    }
    if (section == BLMenuSectionPosts){
        [view setTitle:NSLocalizedString(@"Browse", nil)];
    }
    else if (section == BLMenuSectionSettings)
        [view setTitle:NSLocalizedString(@"Settings", nil)];
}

return view;
}

A: Afaik, you shouldn't use -beginUpdates and -endUpdates in conjuction with a reload, but rather when inserting or deleting.
Not sure if this is causing your problems, but it might be worth checking out.
Is it the same regardless of animation type?
From Apple's docs:

Call this method if you want subsequent insertions, deletion, and
  selection operations (for example, cellForRowAtIndexPath: and
  indexPathsForVisibleRows) to be animated simultaneously. This group of
  methods must conclude with an invocation of endUpdates. These method
  pairs can be nested. If you do not make the insertion, deletion, and
  selection calls inside this block, table attributes such as row count
  might become invalid. You should not call reloadData within the group;
  if you call this method within the group, you will need to perform any
  animations yourself.


text:
Q: passing array of structs to glVertexAttribPointer I'm starting from the Apple-spupplied iOS OpenGL game template in Xcode and I have an array of structs (more of an array of structs of structs, if you will) that I'm trying to use with an OpenGL VBO. However, while I get no errors, nothing is drawn to the screen.
First I create and populate this array which is of type VecAttributeType, a struct which in turn has 3 other structs: vPosition, vTCoordinates and vNormal.
Then I try copying the array to a VBO and binding the positions and normals (meaning VecAttributeType.vPosition and VecAttributeType.vNormal in terms of offsets) via glVertexAttribPointer to the appropriate in / attributes in the vertex shader.
Then I try rendering.
And nothing is drawn :/
Mind you, the arrayOfStructs contains ALL vertices needed to draw the model. That is, I'm not using indices to vertices. Rather, for this test, I'm going through the face definitions in the obj and for each index, retrieving the appropriate vertex,texture,normal and copying it in the arraOfStructures.
So for instance, for a classic cube in obj format, the file lists 8 vertices but my final arrayOfStructs has length 12 and there's 12 VecAttributeType structs in it, each with the right position, texture coord and normal for that vertex, derived from the indices in the obj file's face definition. And yes, I'm offsetting the indices in the f definitions by -1 to account for the fact that obj files index starting at 1.
My guess is that I'm simply calculating the offset into the VBO for the positions and normals wrong. I think so because I've tried printing the first position x coordinate in the first VecAttributeType in the arrayOfStructures like so:
NSLog(@"\nTEST:\nfirst vertex X = %f", arrayOfStructs[0].vPosition.x);

and I get the expected value, while trying to print like so:
char* address = (char*)arrayOfStructs+offsetof(VecAttributeType, vPosition.x);
    float b = *address;
    NSLog(@"\nTEST:\nfirst vertex X = %f",  b);

prints 0 instead (the right value should be 1);
Here are the relevant sections of code:
//Inside a c++ class I'm parsing an Obj and creating the vertex attribute array:
typedef struct
{
    float x;
    float y;
    float z;

} Vec3fType;

typedef struct
{
    float s;
    float t;

} Vec2fType;

typedef struct
{
    int p;
    int n;
    int t;

} Vec3iType;

typedef struct
{
    Vec3fType vPosition;
    Vec3fType vNormal;
    Vec2fType vTCoordinates;

} VecAttributeType;

int arrayLength = // Some number;
VecAttributeType* arrayOfStructs = new VecAttributeType[arrayLength];

//  Populate the array.

// . . .

// Then, in the ViewController (Objective-C) class, I try binding to the VBO and getting the offsets right:

[EAGLContext setCurrentContext:self.context];

[self loadShaders];

glEnable(GL_DEPTH_TEST);

GLuint _vertexBuffer;
glGenBuffers(1, &_vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(VecAttributeType)*arrayLength, arrayOfStructs, GL_STATIC_DRAW);
glEnableVertexAttribArray(GLKVertexAttribPosition);
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(VecAttributeType), BUFFER_OFFSET(0) + offsetof(VecAttributeType, vPosition) + offsetof(Vec3fType, x));
glEnableVertexAttribArray(GLKVertexAttribNormal);
glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, sizeof(VecAttributeType), BUFFER_OFFSET(0) + offsetof(VecAttributeType, vNormal) + offsetof(Vec3fType, x));

And finally, the drawing code is:
- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
    glClearColor(1.f, 0.f, 0.f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glBindVertexArrayOES(_vertexArray);

    // Render the object again with ES2
    glUseProgram(_program);

    glUniformMatrix4fv(uniforms[UNIFORM_MODELVIEWPROJECTION_MATRIX], 1, 0, _modelViewProjectionMatrix.m);
    glUniformMatrix3fv(uniforms[UNIFORM_NORMAL_MATRIX], 1, 0, _normalMatrix.m);
    glDrawArrays(GL_TRIANGLES, 0, arrayLength);
}

Any ideas?

A: Ok I got it...
Turns out at some point I forgot I was using the VAO extension (glBindVertexArrayOES) and after disabling it at the end of the VBO setup, I was forgetting to enable it in glkView:draInRect:
My code above shows it enabled, but only cause I created a new project to copy the relevant sections of code to before posting on SO.
Also, the glVertexAttribPointer lines can be rewritten a bit more compactly like this:
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(VecAttributeType),(void*)offsetof(VecAttributeType, vPosition.x));
glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, sizeof(VecAttributeType), (void*)offsetof(VecAttributeType, vNormal.x));


text:
Q: How to use custom label color logically to a row chart in dc.js using ReactJS How to use custom label color to a row chart in dc.js
my requirement is to show green and red color on the basis of some logical condition. I have tried 'pretransition' but not understand how to use it.
Can someone help me regarding this below is my code for rowchart.
Thanks in advance.
chart
    .width(768)
    .height(480)
    .elasticX(true)
    .label(function(d) return d.label)
    .dimension(runDimension)
    .group(speedSumGroup)
    .render();


text:
Q: How to override array var in child class? I have class Slider. Which slides array of advertisements [Advertisement]. Now I created sliderForFood which must slide foods array [Food]. How can I override my advertisement [Advertisement] var with foods[FOOD] var.
class SliderADV {
    var arrayAdvertisements: [Advertisement] = [Advertisement]()
}

class SliderForFood: SliderADV {
    var arrayFood:[Food] = [Food]()

     override var arrayAdvertisements: [Advertisement]{
        get {
           return arrayFood
           }
       set{
           if newValue is [ArrayFood]{
               self.arrayAdvertisement = newValue
          }
     }
}
}

A: You should better do it following way - create an Item protocol and create two implementations of this i.e Advertisement and Food (and you may need many more in future). Your slider functionality can change based on the  implementation of the item object and you do that by adding methods and properties in the protocol.
protocol Item {
 var name : String {get set}
 func showDetail()
}

class Advertisement : Item {
   var name : String!
   init(with name: String) {
      self.name = name
   }

    func showDetail() {

    }
}

class Food : Item {
   var name : String!
   init(with name: String) {
      self.name = name
   }

     func showDetail() {

     }
}

class Slider {
   var items: [Item]!  // any object which implements Item protocol
}

Let me know if that doesn't solve your problem.

A: Inheritance basically means "is a kind of". You're saying that "Slider for food is a kind of slider for ads" which does not make sense to me.
IMO, you should create a protocol like this:
protocol Slider {
    associatedtype ThingToSlide
    var things: [ThingToSlide] { get set }
}

Then you have your two slider classes conform to it:
class SliderForAds : Slider {
    typealias ThingToSlide = Advertisment
    var things: [Advertisment] = [Advertisment]()
}

class SliderForFood : Slider {
    typealias ThingToSlide = Food
    var things: [Food] = [Food]()
}


text:
Q: What are the main issues in designing an interpreter for a functional language? Suppose I want to implement an interpreter for a functional language. I would like to understand the issues involved in doing so and suitable literature that is available. This is a new language that is in early design stages, that is why the question is broad in scope.
For the purpose of this discussion we can assume that the purpose of the language is not important and that its functional features can be changed (even drastically) if it makes a significant difference in the ease of writing an interpreter.
The MIT website has an online copy of Structure and Interpretation of Computer Programs as well as videos of the MIT 6.001 lectures using Scheme, recorded at HP in 1986. These form a great introduction to language design.

A: I would highly recommend Structure and Interpretation of Computer Programs (SICP) as a starting point. This book will introduce the idea of what it means to write an interpreter (and a compiler), and is generally a must-read for anybody designing languages.
Implementing an interpreter for a functional language isn't likely to be too much different from implementing an interpreter for any other general purpose language. There's lexical analysis, parsing, AST construction, semantic analysis, plus execution (for a pure interpreter) or code generation and optimisation (for a compiler, even compiling to bytecode like Java/Perl/Python). SICP will introduce the difference between "applicative order" and "normal order" evaluation, which may be important for you in a pure functional context.

A: For just about any language interpreter or compiler, the main issues are the same, I think.
You need to decide certain basic characteristics of the language (semantics, not syntax), and the bulk of the design of the thing follows from that.

*

*For example, does your language have
a type system? If so, what sorts of
types does it have? Is it going to be
statically typed, dynamically typed,
duck-typed?

*What sort of expressions are you
planning to support? Do you need to
define an order of operations? Will
you even have operators?

*What will you use as the run-time
representation of the program? Will
you convert the text to a byte-code
representation, or an AST, or a
tokenized form of the source text?
There are toolkits available to help take some of the tedium out of the actual parsing of text (ANTLR and Bison, to name two), but I don't know of anything that helps with the actual interpretation part of the task. I'm sure somebody will suggest something.

A: The main issue is having a semantics for the language you're implementing -- with that, the implementation becomes straightforward. Otherwise, this question is incredibly broad and hard to answer.

A: I'd recommend Essentials of Programming Languages as a good complement to SICP, particularly if you're interested in interpreters: Official EOPL site. You may want to check out the third edition-- the site hasn't been updated for it yet.
Edit: spam prevention is making me choose between links, so the official page is now unheated. It's easily Google-able, though.


text:
Q: Woocommerce insert images attachments Im creating a product post (in wordpress) with all the necesary elements, everithing is fine: title, brand, reviews, for featured image i made this code:
$media_id = media_sideload_image($imgppal, $new_post_id, null, 'id');

set_post_thumbnail($new_post_id, $media_id);

Everything is fine until here, but I can´t insert more images to a product, can someone help me please?

A: A post can only have 1 thumbnail by default. If you want to add multiple images you can use the wp_insert_attachment() functionality to add multiple images.
<?php
$media_id = media_sideload_image($imgppal, $new_post_id, null, 'id');
$attachment = array(
    'ID' => $media_id,
    'post_parent' => $custom_post_id //post id you want to add the image to
);
wp_insert_attachment( $attachment );

?>


text:
Q: Passing an id to an update mysql query I am trying to run a very simple update query which works in itself when the values are hardcoded in but which doesn't work when I try to pass the ID of the app dynamically. I have a .json object that passes data along, together with the ID of the app. Other similar code in the project works. The javascript function works as the success part returns an appropriate message but the db does not update. Advice on why this may not be passing through? Also, is there a way to "console log" in php what ID it's trying to pass to the query?
Here's the code:
<?

date_default_timezone_set("America/Boise");

$time = array('current_datetime'=>date('Y-m-d H:i:s'));

$inputs = json_decode(file_get_contents("php://input"));

include '../databases.php';

$db_object = new database();

// start a secure session
$db_object->secureSessionStart('__dpc_session');

try {
    // check if admin
    $db_object->permissionCheck(1);

    $con = $db_object->connect();

    // sanitize inputs
    $cleanInputs = $db_object->sanitize($inputs);

    // create sql
    $sql = "UPDATE applications SET enr1 = ?, enrName1 = ?, enr2 = ?, enrName2 = ? WHERE id = ? LIMIT 1";

    // store in database
    $db_object->genericSql($sql, ['i', 's', 's', 's', 's'], [$cleanInputs->id, $cleanInputs->enr1, $cleanInputs->enrName1, $cleanInputs->enr2, $cleanInputs->enrName2]);

} catch (Exception $e) {
    http_response_code(401);
    print_r(json_encode(array('error'=>$e->getMessage()), JSON_UNESCAPED_UNICODE));
    exit;
}

A: The hiccup came from passing the ID dynamically after all, but the solution was super easy.
Instead of passing id = ?, id needed to be set to something that came from $cleanInputs, like this:
$sql = "UPDATE applications SET enr1 = ?, enrName1 = ?, enr2 = ?, enrName2 = ? WHERE id = '$cleanInputs->id'";


text:
Q: What happen if I forgot to add Core Data when creates the project in xcode 7+ ,ios 9,with Objective C I have an ios project written in objective C. When I create the project I forgot to add core data (absolutely at that moment I create the project, I didn't have a need of core data and now I want). so is it a matter with Xcodee 7+ and if I add now core data to my project, can I continue with the normal way. Or else do I have to copy & paste files from a project which created with core data. Searching for a better and easy way to do this.
how can I do this.hope your helpful answer with this.

A: If you select the use CoreData option in the new project wizard, it just puts in some boilerplate code and includes the CoreData framework in your build settings.  You can do this after the fact with no problems.
There are plenty of tutorials that will show you how to do this as well.  They are easy to find with a cursory google search.
If you don't want to go through the trouble of finding a tutorial, the easiest thing to do is create a new project with CoreData and add the pieces in that project that are missing in yours (last time I looked at the template project, most of the CoreData code was in the app delegate, and of course you'll need to add a data model file).
UPDATE: Removed link to first tutorial I found doing a cursory google search, since it is no longer available.


text:
Q: How to optimize query that has the same subquery twice? I'm trying to improve some queries performance, the queries' structure is something as follows:
select 'Total_amount',
(select SUM(Total) from dbo.Invoices i where i.BU = bun.BU),
case when (select SUM(Total) from dbo.Invoices i where i.BU = bun.BU) > 100000 then 'Good' else 'Not good' end
from dbo.BusinessUnits bun

I know this example can be solved using joins, but on my real queries I need the subqueries.
As you may notice, I have the same subquery twice, one to give the actual value and another one to calculate a status.
Is there a way to improve performance by just calculating the subquery once?

A: You may try using OUTER APPLY like this:-
select 'Total_amount', SumTotal, case when SumTotal > 100000
then 'Good' else 'Not good' end
from dbo.BusinessUnits bun
OUTER APPLY (select SUM(Total)
from dbo.Invoices i where i.BU = bun.BU) CA(SumTotal)

SPECIAL THANKS TO MARTIN SMITH for pointing that!!

A: Another option using WITH
WITH total_table( 'Total_amount' )
AS
( SELECT SUM(Total)
  FROM Invoices INNER JOIN  BusinessUnits ON (Invoices.BU = BusinessUnits.BU )
)

SELECT
   CASE WHEN Total_amount > 100000 then 'Good'
   ELSE 'Not good'
   END
FROM
   total_table


text:
Q: Comparing values within an array to the arithmetic mean of the first and last numbers #include<iostream>
using namespace std;
int count(float v[100],int n)
{
    int i,nr=0;
    float m;
    m=(v[0]+v[n-1])/2;
    for(i=0;i<n;i++)
        if(v[i]>=m)
            nr++;
    return nr;
}
int main()
{
    int i,n,ok=0;
    float v[100];
    cin>>n;
    for(i=0;i<n;i++)
        cin>>v[i];
    if(v[0]==v[n-1])
        ok=1;
    if(count(v,n)==2 && ok==1)
        cout<<"YES";
    else
        if(ok==0 && count(v,n)==1)
            cout<<"YES";
        else
            cout<<"NO";
}

This program supposedly checks if the first and last numbers from within an array are the lowest values that are in that respective array. This is done , as the title states, by comparing the numbers to the arithmetic mean of the first and last numbers
The problem is, it doesn't. Whatever values I input, it only displays "NO" (meaning that these numbers are not the lowest). Gone through it a hundred times, but can't really figure out what's wrong...any help would be appreciated.

A: The line if(ok==0 && count(v,n)==1) should be if(ok==0 && count(v,n)== n-1).
If the first and last are not equal, but one of them is the lowest number, then count(v,n) will return n-1.
With your example data with 6 input: 12 245 654 23 652 11.
(first + last) / 2 = 11.5
12, 245, 654, 23, and 652 are all greater than 11.5, so count(v,n) returns 5 (e.g. n-1), which indicates that "either the first of the last number is the lowest".

edit: The simplest solution would be fixing count() to check if(v[i]<=m) instead of >=.  That way it returns the quantity of datum that are less than (first+last)/2.  If first==last, it will return 2, if first!==last, it should return 1.

A: Your algorithm is fundamentally flawed and won't do what you want (check if the first and last numbers are the two lowest). Consider this array:
2, 19, 19, 19, 19, 20
Every element except the first is greater than the mean (11) but the last item is the largest not one of the smallest two.
I think the actual simplest way to solve this is to partial_sort the first two elements (in a temporary container if needed) and check if they match the first and last elements of the original data.


text:
Q: How Can I Create a button that links to multiple websites using this HTML outline? I just wanted to know how I can create a button that can take a person to multiple websites in a random order when it is clicked each time. I plan on using this button for a toolbar that I'm planning to create, and the outline that is provided for the HTML component looks like this:
<html>
<head>
<!--
Uncomment out the below script reference as needed.  For more information on using the API, please consult http://www.conduit.com/Developers/overview.aspx
<script language="JavaScript" src="http://api.conduit.com/BrowserCompApi.js"></script>
-->
<style type= "text/css">
<!--
BODY {margin-left:0; margin-right:0; margin-top:0; margin-bottom:0;
width:100%;height:100%;overflow:hidden;background-color:threedface;}
-->
</style>
</head>
<body>

<!-- ENTER YOUR HTML HERE -->

</body>
</html>

Is there any way that I can do this by using this outline? Thanks in advance.

A: As suggested by others, simply make a button click call a function that picks a random site from an array. Here is an explanation on how to pick a random element from a Javascript array.
Example implementation:
<script type="text/javascript">
    var websites = ["http://google.com", "http://reddit.com", "http://stackoverflow.com"];

function randomWebsite() {
    var website = websites[Math.floor(Math.random()*websites.length)];
    window.location = website;
}
</script>

<button type="button" onclick="randomWebsite();">Random website</button>

A: I'm not going to write the script for you but you'd want to use javascript to do this.  Use the random function and assign your website urls to an appropriate number.
Example:
if you had three total websites then you'd do the random function and assign 0-.33 website 1, .34 - .66 website2, and .67 - 1 website 3.

A: I think you need javascript to do this,
Take a look on this page maybe this can help you
http://ozirock.hubpages.com/hub/How-to-make-a-Random-Page-button-for-your-website

A: You need Javascript for that.
You can have a list of websites.
You can get the website you will go to, when the button is clicked, by using the random function in javascript.
Here is the example when using an array, Getting a random value from a JavaScript array
Hope it helps.
We shouldn't give you any code, as you didn't provide anything. But your algorithm should follow what I mentioned.


text:
Q: PDO Zero-indexed when using Integer keys with FETCH_KEY_PAIR I'm trying to use the PDO::FETCH_KEY_PAIR parameter in a PDO fetchAll() to be able to output an array where each key is the primary key and the value is another field of each row returned by the SELECT statement.
So for example:
$stmt = $this->db->prepare('SELECT country_id, name FROM _country');
$stmt->execute();
$data = $stmt->fetchAll(\PDO::FETCH_KEY_PAIR);

where country_id is an INT(10) and name is a VARCHAR. The $data is then processed in another script:
foreach( $data as $key => $value ){
        echo $key . "|" . $value;
    }

SELECT statement result:
 ------------------------
 |country_id | name     |
 ------------------------
 | 18        | India    |
 | 26        | Germany  |
 | 129       | Sweden   |
 ------------------------

However, when the array is returned the keys are zero-indexed, only using the name column as the value.
Expected output (using echo print_r($data))
Array ( [18] => India [26] => Germany [129] => Sweden)

Actual output
Array ( [0] => India [1] => Germany [2] => Sweden)

Curiously, when I switch the columns:
SELECT name, country_id FROM _country;

it works perfectly returning each country name as a key with the primary key integer as the value.
Array ( [India] => 18 [Germany] => 26 [Sweden] => 129)

I thought i'd try playing around with the PDO::ATTR_STRINGIFY_FETCHES and PDO::ATTR_EMULATE_PREPARES attributes, but to no avail.
I'm running:
- php 5.5.9
- mysql server 5.6.16
- pdo_mysql mysqlnd 5.0.11-dev

A: Try this way of fetching your result:
$stmt = $this->db->prepare('SELECT country_id, name FROM _country');
$stmt->execute();
$data = array_map('key_value', $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC));

function key_value($value){
    return $value[0]['name'];
}

PDO::FETCH_GROUP|PDO::FETCH_ASSOC returns an array of arrays. Then I mapped the resulting array to a function and generated only the desired output, which should be at your end:
Array ( [18] => India [26] => Germany [129] => Sweden)
I actually tried to generate your result using the \PDO::FETCH_KEY_PAIR parameter but it worked just fine. I don't know what the problem is!


text:
Q: SQL Server 2012 - Synchronizing tables on different servers Hi I need your assistance.
I have a table that I must synchronize in near real time.
There is however a couple of challenges that I'm sitting with:

*

*The table (Table A) to by synchronized do not reside on the same server, but on two different servers. Server A (Production) and Server C (Development).

*The table (Table A) on server A and server C do not have a primary key, so merge and transactional replication cannot work.

*Setting triggers up on server A - the production server - is out of the question, this is a operation critical server.

*Adding a primary key is also out of the question.

*There is +/- 90 records being added to the table per minute.

Please can anyone assist?
Many thanks

A: You have ruled out so many options for any HA technologies to work..Only solution i could think of  is
1.Write a custom solution in C#,which compares tables and does the necessary merge based on some column like date
2.Write the last written records into some table for the exe to start from there again
3.Trigger this through SQLServer Agent
You can also use AlwaysOn which provides readable secondaries as well,but i am not sure you be failing over production and development ..


text:
Q: Centos: getting this error on Atom editor Trying to run a simple java code in atom editor but giving the error: bash javac command not found.
Tried to set the path as follows but does not resolve the problem:
[root@localhost ~]# export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.151-1.b12.el7_4.x86_64
[root@localhost ~]# export PATH=$JAVA_HOME/bin:$PATH

A: Run this command su -c 'yum provides javac'
This will tell you what packages will provide javac
Just because you installed a java RE doesn't mean you have a Java DK
Install java-devel or java-1.8.0-openjdk-devel or whatever version you want.


text:
Q: Reference the correct static file in phoenix In a phoenix project, I can reference digested img in a css file with:
background-image: url("/images/phoenix.png");

and that references:
http://localhost:4000/images/phoenix-5bd99a0d17dd41bc9d9bf6840abcc089.png?vsn=d

I would like to reference the same file, but the image src added with javascript, like so:
document.querySelector('#my-img').src = '/images/phoenix.png';

But this only references:
http://localhost:4000/images/phoenix.png

How can I configure the phoenix endpoint to instead serve the digested img file?
(I would like this functionality for updating cached file purposes)

A: Since you know the image file beforehand, you can have a javascript variable and set the value to the URL to that image file and use it later in your script
Something like this in your .eex template:
<script>
 // using static_path(@conn, "/path/to/asset") will give the digested file url
 var disgestedImageUrl ="<%= static_path(@conn, "/images/phoenix.png") %>";
</script>

Then have your script that uses the URL in your .js file
<script>
  document.querySelector('#my-img').src = digesterImageUrl;
</script>


text:
Q: audio-taper potentiometer in 50-100 ohm range Anyone know where to source an audio or logarithmic taper potentiometer in the 50 or 100'ish ohm range ?   Mouser and Digikey don't show anything, even non-stocked.  I'd like to build an adjustable current source with an LM317, and the current is proportional to the reciprocal of the adjustment resistor - so a linear taper is far from ideal.  Thanks !

A: This might be an option: -

It can be a very accurate constant current source and relies on the fact that the op-amp takes an input voltage referenced to the positive supply voltage rail (Vin) and, by op-amp action, supplies enough base current to the transistor to ensure that that voltage also appears across R1.
This means that the current through R1 is Vin/R1 and that the current through your load is also the same current (plus a little bit of base current). I normally expect the current output to be accurate to within 0.5% of the demand voltage (Vin) and the resistor value R1. So, if you need accuracy make R1 a 0.1% resistor.
There is also a version of this that can use a P channel MOSFET. Here's one that is dual stages to give you the control voltage referenced to the 0V rail: -

An LM317 is OK as a current source but it isn't very accurate and will tend to drift with temperature. It also needs a couple of volts headroom between input and output voltage to do the job properly. There is also a minimum current that you cannot get below due to the device needing a couple of mA to actually work (this flows into the load). Also, as a dynamic current source it's impedance is not very good at high frequencies.

A: Grab something called an "audio L-pad".
This is a device intended to allow adjustable level control for a 8-ohm loudspeaker.
This device contains two separate adjustable resistance elements arranged so that the input impedance of the pad remains constant as the level to the speaker is changed.
I don't remember the details of exactly how I wired those resistance elements but I do recall that I was able to do what you are trying to do.
It's worth checking out.


text:
Q: Adjoint of Sum = Sum of Adjoints? Didnt find this anywhere, just verifying.
We know that: $$ (A+B)^T= A^T+B^T $$.
Does it follow that:$$ (A+B)^† = A^† +B
^† $$ for all A and B matrices (the dagger here representing the adjoint)?
If so what is the proof?

A: $\langle (A + B)^\dagger x, y \rangle = \langle x,  (A + B)y \rangle = \langle x, Ay + By \rangle$
$= \langle x, Ay \rangle + \langle x, By \rangle = \langle A^\dagger x, y \rangle + \langle B^\dagger x, y \rangle; \tag 1$
from this we have
$\langle (A + B)^\dagger x - A^\dagger x - B^\dagger x, y \rangle = 0; \tag 2$
since this binds for all $y$, we have
$(A + B)^\dagger x - A^\dagger x - B^\dagger x = 0,
 \tag 3$
or
$(A + B)^\dagger x = A^\dagger x + B^\dagger x,
 \tag 4$
holding for all $x$; we thus conclude that
$(A + B)^\dagger = A^\dagger + B^\dagger .
 \tag 5$

A: This statement is not true in general.
Wikipedia tells us that for 3 by 3 matrices the first element of the adjoint obtains as,
$$
a_{1,1}^\dagger = a_{2,2}a_{3,3} - a_{2,3}a_{3,2} \quad \text{ and } \quad b_{1,1}^\dagger = b_{2,2}b_{3,3} - b_{2,3}b_{3,2},
$$
but
$$
\begin{align}
(a_{1,1} + b_{1,1})^\dagger &= (a_{2,2} + b_{2,2})(a_{3,3} + b_{3,3}) - (a_{2,3} + b_{2,3})(a_{3,2} + b_{3,2}) \\ &= a_{2,2}a_{3,3} + b_{2,2}b_{3,3} - a_{2,3}a_{3,2} - b_{2,3}b_{3,2} + a_{2,2}b_{3,3} + b_{2,2}a_{3,3} - a_{2,3}b_{3,2} - b_{2,3}a_{3,2} \\ &=
a_{1,1}^\dagger + b_{1,1}^\dagger + a_{2,2}b_{3,3} + b_{2,2}a_{3,3} - a_{2,3}b_{3,2} - b_{2,3}a_{3,2} \\ &\neq a_{1,1}^\dagger + b_{1,1}^\dagger
\end{align}
$$
You may also check numerically with Matlab:
A = randn(3);
B = randn(3);
adjoint(A+B)
adjoint(A)+adjoint(B)


text:
Q: Getting Data Before Rendering Component/HTML File in Angular Please, I am having issues working with some async data on angular which comes from my API. I've spent some time trying to figure out how to scale through, but I still get stuck.
Scenario
When on edit mode of a patient form, I need to call my centre service to get all available centres from db. When the data is returned, I need to process the data to check which centres a patient belong to, then use this on the html. But I see that the component renders before data is received. This is because, when I click save button to check the data, I see the data there. But in the method where I need to write some logic, when I try to inspect the data returned from the API, it remains undefined.
NB: I can't use a resolver in this case because, I'm not using a router link to navigate to the page.
I've tried to use an async pipe to conditionally check and render the html only if I receive the data which was one solution that worked for someone else. But this seem not to work in my case as i still get undefined on the variable which is inside a method, and where I need to process the data returned before showing my component/html.
Goal
The goal is to first get all centres first before initializing the reactive form, so that i can handle the data on the getPatientCentres() method. I intend to use the data gotten from the API to pre-populate an array when creating the form.
Done other steps and research but the solution doesn't seem to solve my case.
Any help or logic on how to proceed would be highly appreciated.
Here is my TS code
  export class Patient2Component implements OnInit {
  formTitle: string;
  patientForm: FormGroup;
  centreList: ICentre[] = [];
  loadedData: boolean = false;
  patient: IPatient;

  constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private fb: FormBuilder,
    private centreService: CentreService,
  ) { }

  ngOnInit() {
    this.getCentres();
    this.initCentreForm();
    this.checkParamsForEditAction();
  }

  initCentreForm() {
    this.patientForm = this.fb.group({
      id: [null],
      firstName: ['', Validators.required],
      lastName: ['', Validators.required],
      centres: [this.centreList]
    });
  }

  getCentres() {
    this.centreService.getCentres().subscribe(res => {
      this.centreList = res;
      // this.loadedData = true;
    });
  }

  checkParamsForEditAction() {
    this.activatedRoute.data.subscribe(data => {
    this.patient = data['patient'];
    if (this.patient) {
      this.formTitle = 'Edit Patient';
      this.getPatientCentres(this.patient);
      this.assignValuesToControl(this.patient);
    }
   });
  }

  assignValuesToControl(patient: IPatient) {
      this.patientForm.patchValue({
        id: patient.id,
        firstName: patient.firstName || '',
        lastName: patient.lastName || '',
      });
  }

  getPatientCentres(patient: IPatient) {
    const patientCentres = patient.patientCentres;

    /**Here, the centreList is undefined since data has not returned yet
     * And i need this data for processing.
     */
    console.log(this.centreList);
  }

  save() {
     /**Here, i can see the data  */
     console.log(this.centreList);
   }

A: Try this
in ngOnInit
 ngOnInit() {
    this.initCentreForm();
    this.getCentres(this.checkParamsForEditAction);
  }

getCenters Method
     getCentres(callBack?) {
        this.centreService.getCentres().subscribe(res => {
          this.centreList = res;
          // this.loadedData = true;
          if(callBack) {
            callBack();
          }
        });
     }

you can also use  forkJoin, or async await

A: getCentres(callBack?) {
        this.centreService.getCentres().subscribe(res => {
          this.centreList = res;
          // this.loadedData = true;
          //Now call your function directly
         this.checkParamsForEditAction();
        });
     }

Call your function after the get centers is loaded
Order of calling
this.initCentreForm();
this.getCentres();


text:
Q: How do you load an image in a canvas using CamanJS? The example on the CamanJS website (http://camanjs.com/guides/#BasicUsage) looks like this:
Caman("#canvas-id", "path/to/image.jpg", function () {
  // manipulate image here
  this.brightness(5).render();
});

I've tried to run this very first, very basic example on JSBin (http://jsbin.com/uGUPOFo/3/edit?html,js,output) using one of my own images
Caman("#cv", "http://preemiestoday.noahpeters.com/images/feature.png", function () {
  this.brightness(5).render();
});

But it does nothing. Does anyone know what I'm missing? The docs say that it can run "next to jQuery, YUI, Scriptaculous, MooTools, etc." I would like to not use any of those, though I tried loading the latest 1.x jQuery to no effect.

A: it seems to me that the image is not on your server but remote.
if i were you i'd check out this link:
https://github.com/meltingice/CamanJS/wiki/How-to-use#editing-remote-images
"CamanJS can even edit images that are stored remotely. Since the browser enforces a same-origin policy for editing canvas data, we have to load the image data via a local proxy."
"If no proxy is defined when a remote image is attempted to be edited, an error will be thrown."


text:
Q: How Do i maintain my app in running state in background My app is not starting from current state, without closing my app i am going to push into background. I am just minimizing my app but not closing my app. If again start my app its going to start from starting like from splash screen.
I want start my app from current state where i have minimize my app.
My question is:
What i need to do in app delegate class, here i my work around:
-(void) applicationDidEnterBackground:(UIApplication*)application {
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"SplashLoadCheck"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    if( [navController_ visibleViewController] == director_ )
         [director_ stopAnimation];
}

-(void) applicationWillEnterForeground:(UIApplication*)application
{
     if( [navController_ visibleViewController] == director_ )
        [director_ startAnimation];
}

- (void)applicationWillTerminate:(UIApplication *)application {

    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"SplashLoadCheck"];
    [[NSUserDefaults standardUserDefaults]synchronize];     CC_DIRECTOR_END();
}

A: You can set your following plist flag.
"Application Does Not Run in Background" = NO.

This will allow the application to run in background as well.

A: In order to run your app in the background, you should enable the required background modes of your app. This is depends on the kind of app you have. Otherwise apple will reject the app. One more thing even though you are not turning on the background modes, app will not terminate immediately. OS will put your app in an idle state and terminate automatically when it requires. Until this termination happens, if you are launching the app again app will come to the same state where you left it before going to background.
Here is the list available background modes


text:
Q: Detecting if client's browser has Cookies Turned Off I want to check if the user of my website is allowing cookies or not.
Basically I want to do the following:
<?php
     if(cookies are enabled)
     {
          /* Cookies related code goes here */
          /* Create PHP cookie, read cookies etc */
     }
     else
     {
          /* Do something else */
     }
?>

My idea is to check if setcookie function returns true then cookies are enabled otherwise not.

A: As above: it won't always work.
So, basically, you can do something like this:
<?php
setcookie('enabled', '1');
if($_COOKIE['enabled']=='1'){
    echo('Cookies are enabled. ');
}else{
    if($_GET['nocookies']==1){
        echo('Cookies are disabled. ');
    }else{
        $adr = explode('/', $_SERVER['SCRIPT_NAME']);
        header('Location: '.$adr[count($adr)-1].'?nocookies=1');
    }
}
?>

A: The 'setcookie' return isn't enough. In case of Firefox, this function does return true even if cookies are disabled.
I think the best way to check it is setting a value in a cookie and checking for that value in the next request.

A: To answer your question exactly, if you create a function
<?php
function cookies_are_enabled() {
    setcookie('enabled', 'enabled');
    return $_COOKIE['enabled'] === 'enabled';
}
?>

Then in your code you have:
<?php
if (cookies_are_enabled()) {
  /* Cookies related code goes here */
  /* Create PHP cookie, read cookies etc */
} else {
  /* Do something else */
}
?>

Update: As pointed out in the comments. This won't work directly. From the setcookie PHP page (my emphasis):

'Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, superglobals such as $_COOKIE became available in PHP 4.1.0. Cookie values also exist in $_REQUEST.'

Given that you can't trust setcookie, best I can think of doing is forcing a redirect.
<?php
function cookies_are_enabled() {
    // if first page load
    // set cookie and redirect
    // if redirected check the cookie
    if (isset($_GET['cookie_check'])) {
        return $_COOKIE['enabled'] === 'enabled';
    } else {
        setcookie('enabled', 'enabled');
        if (empty($_SERVER['QUERY_STRING'])) {
            $url = $_SERVER['PHP_SELF'].'?cookie_check=1';
        } else {
            $url = $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'].'&cookie_check=1';
        }
        exit(header("Location: $url"));
    }
}

if (cookies_are_enabled()) {
    /* Cookies related code goes here */
    /* Create PHP cookie, read cookies etc */
    $message = 'cookies are enabled';
} else {
    /* Do something else */
    $message = 'cookies are not enabled';
}
?>
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Cookies!</title>

<?php echo $message; ?>


text:
Q: Jetpack glance widget only the whitespace is clickable, text and image are not I have a glance widget that contains a column. The column has tiles containing text and image. The row has clickable modifier, however, I can click only the whitespace. Any way to solve this?
There is a similar question however the answer to it suggests reverting to alpha-03 but I have alpha-05 which I believe the bug should be solved.
Sample code:
Column(
        modifier = GlanceModifier
            .fillMaxSize()
            .cornerRadiusCompat(
                cornerRadius = 16,
                color = if(uiState.isDark)
                    LocalContext.current.getColor(R.color.dark_list_widget_background_color)
                else
                    LocalContext.current.getColor(R.color.light_list_widget_background_color)
            )
    ) {
        ListWidgetHeader(
            isDark = uiState.isDark,
            type = uiState.type
        )
        Box(
            modifier = GlanceModifier
                .fillMaxSize()
                .background(
                    if (uiState.isDark)
                        R.color.dark_list_widget_background_color
                    else
                        R.color.light_list_widget_background_color
                ),
            contentAlignment = Alignment.Center
        ) {
            ListWidgetContent(
                data = uiState.data,
                isDark = uiState.isDark,
                type = uiState.type
            )
        }
    }

@Composable
private fun ListWidgetContent(
    data: List<ListWidgetData>,
    isDark: Boolean,
    type: WidgetCategoryEnum
) {
    Column{
        data.forEachIndexed { index, model ->
            ListWidgetTile(
                model = model,
                isDark = isDark,
                bottomPadding = 16.dp,
                topPadding = if (index == 0) 16.dp else 0.dp,
                type = type
            )
        }
    }
}

@Composable
private fun ListWidgetTile(
    model: ListWidgetData,
    isDark: Boolean,
    bottomPadding: Dp,
    topPadding: Dp,
    type: WidgetCategoryEnum,
) {
    val action = // Some Action related to app-logic
    val intent = Intent(
        Intent.ACTION_VIEW,
        "${URL}/${Screens.Splash.navigateWithDeepLink(DeepLinkModel(model.id, action))}".toUri()
    )
    val bitmap = if(model.image != "") {
        model.image.decodeToBase64()
    } else {
        null
    }
    Row(
        modifier = GlanceModifier
            .fillMaxWidth()
            .padding(
                start = 24.dp,
                end = 15.dp,
                bottom = bottomPadding,
                top = topPadding
            )
            .clickable(
                actionStartActivity(intent)
            ) // WORKS ONLY IN WHITESPACE
    ) {
        Column(
            modifier = GlanceModifier
                .fillMaxWidth()
                .defaultWeight()
                .padding(
                    end = 8.dp
                )
                .clickable(
                    actionStartActivity(intent)
                ) // NOT WORKS
        ) {
            Text(
                text = model.source,
                style = TextStyle(
                    fontSize = 8.sp,
                    fontWeight = FontWeight.Medium,
                    color = ColorProvider(
                        resId = if (isDark)
                            R.color.dark_list_widget_source_time_color
                        else
                            R.color.light_list_widget_source_time_color
                    )
                ),
                modifier = GlanceModifier
                    .padding(
                        bottom = 8.dp
                    )
            )
            Text(
                text = model.title,
                style = TextStyle(
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold,
                    color = ColorProvider(
                        resId = if (isDark)
                            R.color.dark_list_widget_title_color
                        else
                            R.color.light_list_widget_title_color
                    )
                ),
                maxLines = 3,
            )
        }
        if (bitmap != null) {
            Image(
                provider = ImageProvider(
                    bitmap
                ),
                contentDescription = "Image",
                modifier = GlanceModifier
                    .size(70.dp)
                    .imageCornerRadius(),
                contentScale = ContentScale.Crop
            )
        }
    }
}


text:
Q: Listen for next 5 key presses after hotkey is pressed I'm quite new to c# and I'm trying to create a small system tray app that pastes something in the active window (sends a CTRL+V command) based on a short text and hotkey that are written in the window.
Ex. If you type |hl in Notepad, the app will paste Hello in the active window.
So far I got the app to stat in system try using NotifyIcon, based on the example found here, and was able to setup a keyboard hook to listen for key down events.
What I need now is this:
if(e.KeyCode.ToString() == "OemPipe") //if hotkey is pressed
{
    //listen for the next 5 KeyCode
    if(//next 5 KeyCode are A, B, C, D and E)
    {
         //do stuff
    }
    else
    {
        //ignore and listen for hotkey again
    }
}

I've been banging my head against the wall trying to find how this is done for a few days now, but I can't even find something to get me started.
Any ideeas would be greatly appreciated and if you have a code sample as well that would be even better.

A: I'll try to lend a hand.
I'm assuming you're receiving the Keycode by a KeyEventArgs object, if you scroll through its properties you will notice two interesting ones:
KeyEventArgs.Modifiers
KeyEventArgs.Shift

With those you will know if a key was pressed while holding CTRL, ALT or SHIFT, then in your code you can add into an array which keys were consecultively pressed while holding those hotkeys and do some action if you find the right combination or just clear the array if the next key doesn't come along with any modifier.
Somehing like:
private void button1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{

   if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift)
   {
       AddtoShiftArray(e.keyCode);
       clearAllOtherBuffers(); //ignore and listen for hotkey again

       if(seeIFWithWhatIHaveHereICanDoStuff()){
           doMyStuff();
           clearShiftBuffer();
       }
   }
   //Same for ctrl
   //Same for alt

}

hope this helps! :D


text:
Q: Visual Studio Code Git won't discard files I have about 5000 files that I am unable to discard and VSCode keeps warning me that there are too many files. I'm not sure when I started tracking these files, but if I click on discard and then confirm the discard, nothing happens. Any ideas on how I can solve this?

A: VSCode recently renamed the "Clean" option onto "Discard".
But it is about unstaging current changes, not deleting files.
If you have too many files (that should not be part of the repo, for example because they are generated), simply delete them, then record your deletion (add and commit).
Then you will be able to push.
Additionally, consider adding them (or their parent folder) to a .gitignore file.

A: this is from a while ago but for anyone else having this problem. The way I solved it was because I had clicked my home directory when using source control.
Try closing and reopening vs code and once the "open a folder" option comes up pick the specific project folder and the 5000 files should be reduced to the files you want


text:
Q: Firebase: Can I combine a push with a multi-location update? I need to create a new object with a generated key and update some other locations, and it should be atomic. Is there some way to do a push with a multi-location update, or do I have to use the old transaction method? This applies for any client platform, but here's an example in JavaScript.
var newData = {};
newData['/users/' + uid + '/last_update'] = Firebase.ServerValue.TIMESTAMP;
newData['/notes/' + /* NEW KEY ??? */] = {
  user: uid,
  ...
};
ref.update(newData);

A: There are two ways to invoke push in Firebase's JavaScript SDK.

*

*using push(newObject). This will generate a new push id and write the data at the location with that id.

*using push(). This will generate a new push id and return a reference to the location with that id. This is a pure client-side operation.
Knowing #2, you can easily get a new push id client-side with:
var newKey = ref.push().key(); // on newer versions ref.push().key;

You can then use this key in your multi-location update.

A: I'm posting this to save some of future readers' time.
Frank van Puffelen 's answer (many many thanks to this guy!) uses key(), but it should be key.
key() throws TypeError: ref.push(...).key is not a function.
Also note that key gives the last part of a path, so the actual ref that you get it from is irrelevant.
Here is a generic example:
var ref = firebase.database().ref('this/is/irrelevant')

var key1 = ref.push().key // L33TP4THabcabcabcabc
var key2 = ref.push().key // L33TP4THxyzxyzxyzxyz

var updates = {};
updates['path1/'+key1] = 'value1'
updates['path2/'+key2] = 'value2'

ref.update(updates);

that would create this:
{
  'path1':
  {
    'L33TP4THabcabcabcabc': 'value1'
  },
  'path2':
  {
    'L33TP4THxyzxyzxyzxyz': 'value2'
  }
}

I'm new to firebase, please correct me if I'm wrong.


text:
Q: Equivalents of c# solutions and projects in xcode Newly I am switched from xamarin.iOS to Xcode.
In C# a good feature is that you have a solution that contains several projects and you can define debug/build configurations and based on them build separate projects with each other.
Now, I want to know that is there any mechanism like this in the Xcode too?
Actually I want to develop 3 apps that they have many shared codes. So I want to create a base project that contains shared codes (and contents) and then 3 sub projects. Now with some thing like build configuration, I can build each of them that I want for publishing.
Does Xcode support mechanisms for this porpose?
UPDATE
By reading below answers I created a workspace with below structure:

I also added ../testproject/testproject to the build settings of link1Project but when I want to use files in testproject the autosuggest is not working and also when I build the link1Project I face with:
    Undefined symbols for architecture i386:
  "_OBJC_CLASS_$_ShowAlertView", referenced from:
      objc-class-ref in mftTbnFlipsideViewController.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Am I wrong in creating the workspace? Does the structure is right or I missed something?

A: You can have multiple targets for the same project, and each target can have different settings or files.

A: You can include this base project as a sub-project to each of those 3 projects (just drag it). And create a workspace to include all three child project in it, although it is not necessary - including project as a sub-project is enougth to share code between projects.


text:
Q: Шаблоны WORD Подскажите как добавить поля в WORD для ввода информации через PHP.
Я использую PHPWord. Пытаюсь записать значение поля через
$PHPWord = new PHPWord();
$document = $PHPWord->loadTemplate('/1.docx');
$document->setValue('Value1', '123');
$writer = PHPWord_IOFactory::createWriter($PHPWord, "Word2007");
$writer->save('2.docx');

Проблема в том, что я не уверен в правильности добавления полей в WORD. Как правильно их добавлять?
A: Нашел ответ на свой вопрос самостоятельно :)
В документе WORD нужно просто написать ${Value1}.
Код нужно поправить следующим образом:
$PHPWord = new PHPWord();
$document = $PHPWord->loadTemplate('/1.docx');
$document->setValue('Value1', '123');
$document->save('2.docx');


text:
Q: Unable to run custom decorator after post_save signal I have a post_save signal which is run after any updates happens to a Profile, like so:
# removing the `dispatch_uid` parameter doesn't change anything
@receiver(post_save, sender=Profile, dispatch_uid="c_profile_invite")
def send_invitation_email(sender, instance, **kwargs):
    # ... do things

I would like to run a custom decorator on the signal, after the post_save has been run, like so:
def my_test_decorator(func):
    print("outside the wrapper")

    def wrapper(request, board_id, board_name):
        print("INSIDE THE DECORATOR AFTER POST_SAVE")
        try:
            return func(request, board_id, board_name)
        except Exception:
            return Http404("Board not found")
    return wrapper

@my_test_decorator
@receiver(post_save, sender=Profile, dispatch_uid="c_profile_invite")
def send_invitation_email(sender, instance, **kwargs):
    # ... do things

However, my method my_test_decorator doesn't run at all. However, if I switch places on the decorators then it will run but it will run before the @receiver decorator, not after.
What am I missing? Found this 5 year old question, but it was left unanswered so I'm trying again.
TYIA


text:
Q: How to create executable file for Odoo project? I have a Odoo project. I want to create executable file of that project. Can anybody give me idea to get start on this?
Thank you.
Project File Explorer:

A: Odoo is a web based application and not a desktop application.

A: I created this guide for my personal reference. So I try to keep it short and clear.
This will focus only on Odoo 8 in Windows 7 environment and can be easily adapted to later versions.
OS: Windows 7, Odoo Version: 8
1) Install Python27 (https://www.python.org/downloads/windows/).
2) Install PIP.
Odoo windows packaging files are available at https://github.com/odoo/odoo/tree/8.0/setup/win32
You have to be on Windows host to build .exe for Odoo due to the fact that the Makefile (https://github.com/odoo/odoo/blob/8.0/setup/win32/Makefile#L7) was using the Cygwin's cygdrive emulated path.
3) Assuming that Windows was the host machine and we can proceed to install Cygwin (https://cygwin.com/install.html)
While installing Cygwin, you will get an option to select the supporting packages. Make sure you select the category python and devel with it.
Once Cygwin installation is done, open the Cygwin's terminal and enter "make". If you got "make: *** No targets specified and no makefile found. Stop.", then you're good to go.
4) Use your favorite git client (mine is http://www.mingw.org/ or you can use the Cygwin if you want to) and clone the Odoo repo.
git clone https://www.github.com/odoo/odoo --depth 1 --branch 8.0 --single-branch
Since we are building for 8.0, a single branch is enough for this tutorial.
5) Install the dependency packages from the req.txt file from Odoo repo.
https://github.com/odoo/odoo/blob/8.0/requirements.txt
https://github.com/odoo/odoo/blob/8.0/doc/requirements.txt
6) Static folder for the third party software's like WkHtmltoPdf, PostgreSQL etc are placed at this static folder. https://github.com/odoo/odoo/tree/8.0/setup/win32/static
7) Download the PostgreSQL from https://www.postgresql.org/download/windows/ and place it under static folder.
8) For the WkHtmltoPdf, the recommended version is 0.12.1 and is available on the WkHtmltoPdf download page, in the archive section.
Download from http://download.gna.org/wkhtmltopdf/0.12/0.12.1/ and put the necessary files based on arch under static folder.
9) The images for the setup file needs to be placed on https://github.com/odoo/odoo/tree/8.0/setup/win32/static/pixmaps
10) Edit the https://github.com/odoo/odoo/blob/8.0/setup/win32/Makefile.version and enter VERSION=8.0
Files you might be interested in:
Service: https://github.com/odoo/odoo/blob/8.0/setup/win32/win32_service.py
Setup: https://github.com/odoo/odoo/blob/8.0/setup/win32/win32_setup.py
Makensis: https://github.com/odoo/odoo/blob/8.0/setup/win32/setup.nsi
Package: https://github.com/odoo/odoo/blob/8.0/setup/package.py
11) Change the NSI file based on your need which is available at https://github.com/odoo/odoo/blob/8.0/setup/win32/setup.nsi
If you are using the NSIS from the http://nsis.sourceforge.net/ and installed at a different location from the default, you may have to change the path to makefile on the following file:
https://github.com/odoo/odoo/blob/8.0/setup/win32/Makefile#L12
12) Finally, the build command is Open the Cygwin's terminal and navigate to https://github.com/odoo/odoo/tree/8.0/setup/win32.
Enter "make -f Makefile"
On the successful run, final "openerp-allinone-setup-8.0.exe" will be available in the same folder.
Source https://www.odoo.com/forum/help-1/question/how-to-build-odoo-10-for-windows-as-an-executable-software-117670


text:
Q: Create code to clean up and add sample data to tables with relationship I tried to create the code to clean all tables respecting their relations (the child tables must be cleaned before their parent) and after this I need to add some basic data to run my tests.
I'm having some issues related to Promises chaining, because if I use Promise.all it doesn't respect the correct order, and if the create the chained blocks using then(() => {}) (as in the sample code below) it respects the order but the code becomes a mess.
How can I achieve the same result but without the mess?
before((done) => {
        modelDef.TaskListItemModel.TaskListItem.query().del()
            .then(() => {
                modelDef.TaskListModel.TaskList.query().del()
                    .then(() => {
                        modelDef.ProductAnomalyModel.ProductAnomaly.query().del()
                            .then(() => {
                                modelDef.ProductModel.Product.query().del()
                                    .then(() => {
                                        modelDef.UserModel.User.query().del()
                                            .then(() => {
                                                modelDef.UserModel.User.forge(test_User)
                                                    .save()
                                                    .then((result) => {
                                                        test_User.id = result.get('id');
                                                        test_ProductAnomaly.createdBy = test_User.id;
                                                        test_TaskList.createdBy = test_User.id;

                                                        return modelDef.ProductModel.Product.forge(test_Product)
                                                            .save();
                                                    })
                                                    .then((result) => {
                                                        test_Product.id = result.get('id');
                                                        test_ProductAnomaly.ProductId = test_Product.id;

                                                        return modelDef.ProductAnomalyModel.ProductAnomaly.forge(test_ProductAnomaly)
                                                            .save();
                                                    })
                                                    .then((result) => {
                                                        test_ProductAnomaly.id = result.get('id');
                                                        test_TaskListItem.ProductAnomalyId = test_ProductAnomaly.id;

                                                        return modelDef.TaskListModel.TaskList.forge(test_TaskList)
                                                            .save();
                                                    })
                                                    .then((result) => {
                                                        test_TaskListItem.tasklistId = result.get('id');

                                                        return modelDef.TaskListItemModel.TaskListItem.forge(test_TaskListItem)
                                                            .save();
                                                    })
                                                    .then(done);
                                            })
                                    })
                            })
                    })
            });

    });


text:
Q: How to isolate server disaster script in PHP? Oh my goodness. I never thought that I will need to ask you this. But unfortunately yes, I need to!
I have a PHP written script of my own that uses ffmpeg-php. And ffmpeg-php is a bastard. For some input it works ok, but for some it crashes my whole PHP and server throws Internal Server Error 500. I've tried several times to update ffmpeg-php, ffmpeg itself and so on, but when for some input it works in version 0.5 in 0.6 it wont work. And what i need is be sure that rest of the script will be processed correctly. And now it does not, because when it comes to run toGDImage() on movie frame I have Internal Server Error 500 and no feedback why from any source.
So for peace of mind of my users I decided that I need to isolate this part of script that messes with ffmpeg-php. I need a way to assure that if something will go terribly wrong in this part, it rest will go on.
Try catch does not work because this is not a warning, nor a fatal error, it is a horrible server-disaster. So what are your suggestions?
I think about putting this script into another file called ffmpeg-php-process.php and call it via HTTP and read result, if it is Internal Server Error 500 - I will know that it was not ok.
Or are there any other, more neat ways to isolate disaster scripts in PHP?
Ps. Don't write that I need to diagnose or debug or find the source of the error. I'm not a damn beginner and I'm not a ffmpeg dev to mess in it's code, I need to make my users safe now, and it's everything that i care now.

A: If you're getting a 500 error, it's because an exception of some sort is being thrown at a level lower than that of PHP itself. Unless your code is spinning into some kind of infinite loop or hitting a recursion limit (and especially since it worked with version 0.5), there's a good chance that ffmpeg or ffmpeg-php is crashing and taking the instance of PHP that launched it down with it.
Frankly, there's nothing you can do from PHP.
Your best bet would be, since you've already got access to the server, to write the script in question using a language like Python. There's a ton of ffmpeg python plugins, so you shouldn't have a difficult time setting that up at all. Call your Python script from PHP and pull in the output from a file. What this will do is isolate PHP from your script failing. It'll also get you away from ffmpeg-php (which, at least to me, seems like an unholy combination).
If you're dead-set on using PHP (which I don't recommend), you can launch another PHP script using php-cli from your outward-facing PHP script and do the work from there (as you would with Python). Again, I highly recommend that you avoid this.
Hope this helps!

A: You could spawn a new process containing your php-ffmpeg script. There are some functions to do that: proc_open() as instance.
The documentation has a not bad example about it:
http://php.net/proc_open

A: I have something similar going with a convoluted, large, bulky legacy php-email system I support.  When it got apparent that the email system was becoming it's own beast, we split it off as its own virtual server entirely.  There's no separation like PHYSICAL separation.  And hey, virtual servers are cheap....
On the plus side, you can start, restart, and generally destroy the separate server with little affect on the rest of your code.  It may also have improved backup implications (isolate media and logic)  Since going this route, we've not ever taken the main application server down.
However, it does create a connection challenge as now rather than working local you're going to have your server talking to another separated by at the very least a bit of wire in the same cabinet (hopefully)


text:
Q: Node js require()[env] undefined Brand new to node trying to understand a project. The project loads on dev on a windows machine just fine, but throws this error on Azure App Services..
TypeError: Cannot read property 'database' of undefined

when trying:
config.database for example in index.js

models/index.js
const env = process.env.NODE_ENV || "development";
const config = require(path.join(__dirname, '..', 'config', 'config.json'))[env];
>>> var whatever = config.database; <<<

config/config.json
{
  "development": {
    "logging": false,
    "dialect": "mssql",
    "username": "whatever",
    "password": "whatever",
    "database": "whatever",
    "host": "whatever",
    "dialectOptions": {
      "encrypt": true
    }
  }
}

No idea where to start with this since it works fine on local. The file location seems correct, path is valid, path.join() works fine...
Thank you!

A: There is really only one main possibility here and you need to do a little bit of your own debugging to verify it.
Because this statement does not generate an error:
const config = require(path.join(__dirname, '..', 'config', 'config.json'))[env];

That means that require(path.join(__dirname, '..', 'config', 'config.json')) is returning a Javascript object.  So, there must indeed be a file at the path you construct and it must be giving you an object when you require() it.
But, the error itself: TypeError: Cannot read property 'database' of undefined when you try to reference config.database means that config is undefined.  The only way that happens is that you're using a value for env that is not in your config object.
That's like trying to do this:
const obj = {development: {someKey: "someValue"}};  // what require() gives you
const env = "test";                                 // your value for env
const config = obj[env];                            // reading non-existent [env] property
console.log(config);                                // undefined

So, add console.log(env) to your code to see what env actually is and then verify that you have an object in your config data structure for that specific value (or set the desired value in the environment).
If you had verified the value of env yourself with basic debugging steps before posting here, you probably would have solved your own problem (hoping you can learn simple techniques to solve more of your own problems).
If you didn't follow all of my original logic, you could also just debug it like this:
const env = process.env.NODE_ENV || "development";
console.log("env: ", env);

const configPath = path.join(__dirname, '..', 'config', 'config.json');
console.log("configPath: ", configPath);

const configObj = require(configPath);
console.log("configObj: ", configObj);

const config = configObj[env];
console.log("config: ", config);


text:
Q: If there were a function mapping a set onto its powerset, would the unrestricted comprehension schema be true? I have the following exercise in a set:

Cantor proved that there can be no function $\phi$ mapping a set onto the set of all of its subsets. Show directly that if there were such a mapping, then we would have an interpretation of "$\in$" which makes the unrestricted comprehension schema true, including the version with parameters.

I am not sure how one would go about proving this at all. For the schema to be true, it would need to have a model in which it (all of its instances) is (are) true, but there can be no such model, as far as I know.

A: That's the point. You are trying to show that under a certain assumption, you can derive something false.
For a hint on how to get started, if you have a bijection $\psi:X\to\mathcal{P}(X)$, you can define a new membership relation $\varepsilon$ on $X$ by $$x\;\varepsilon\;y:\iff x\in\psi(y)$$ You just need to show that there's such a bijection given the assumptions, and that the comprehension scheme would hold.


text:
Q: How to clear all subscripted variables? I have the following variable:
Subscript[n, 0 ] = 12 (\[Sigma] L^2)/(e h^2)

If I now do:
ClearAll["Global`*"]

And then call:
Subscript[n, 0 ]

I get:
12 (\[Sigma] L^2)/(e h^2)

... So apparently a variable with a subscript cannot be deleted by "clear all".
How can you do it ?
Here for testing:
Subscript[n, 0 ] =12 (\[Sigma] L^2)/(e h^2)
ClearAll["Global`*"]
Subscript[n, 0 ]


text:
Q: Facebook Messenger Bot curl_exec returns false hopefully you can help me.
I created a simple Messenger Chatbot yesterday and it works fine. Then I tried to program it more complex and the result was that I don't get any responses anymore.
I deleted and created a new Facebook App and I used a simple script again. But this script won't work either.
$hubVerifyToken = 'YES-THIS-IS-MY-BOT';
$accessToken = "MY-HOPEFULLY-RIGHT-ACCESS-TOKEN-I-RENEWED-IT-SEVERAL-TIMES";

if ($_REQUEST['hub_verify_token'] === $hubVerifyToken) {
    echo $_REQUEST['hub_challenge'];
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);

$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = $input['entry'][0]['messaging'][0]['message']['text'];

$answer = "Error";
if($message == "hi") {
    $answer = "Hello";
}

$jsonData = '{
"recipient":{
    "id":"' . $sender .'"
},
"message":{
    "text":"' . $answer . '"
}
}';
$ch = curl_init('https://graph.facebook.com/v2.6/me/messages?access_token='.$accessToken);
curl_setopt($ch, CURLOPT_POST, 1);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$resp = curl_exec($ch);

I checked the $resp and I found out that it return 'false'?
But I have absolutely no idea why ...
Can you please help me?
Comment if you need more infos.
Thank you.


text:
Q: Solve $\lim \limits_{x \to 0} (\frac{\sin x}{x})^\frac{1}{1-\cos x}$ without L'Hospital's Rule or Taylor expansion. I solved it with L'Hospital's Rule, but I had to use it 4 times! Is there any way to avoid it?

A: Can we use some basics: $\lim \limits_{x \to 0} (1+x)^\frac{1}{x} = e$ and $\lim \limits_{x \to 0} \frac{\sin x}{x} = 1$?
So, we separate $1$: $$\large\lim \limits_{x \to 0} \left(\frac{\sin x}{x}\right)^\frac{1}{1-\cos x} = \lim \limits_{x \to 0} \left(1+\frac{\sin x}{x}-1\right)^\frac{1}{1-\cos x}
= \lim \limits_{x \to 0} \left(\left(1+\frac{\sin x}{x}-1\right)^\frac{1}{\frac{\sin x}{x}-1}\right)^\frac{\frac{\sin x}{x}-1}{1-\cos x}=e^{\lim \limits_{x \to 0}\frac{\frac{\sin x}{x}-1}{1-\cos x}},  $$
$$\lim \limits_{x \to 0}\frac{\frac{\sin x}{x}-1}{1-\cos x} =
\lim \limits_{x \to 0}\frac{\frac{\sin x}{x}-1}{2\left(\frac{x}{2}\right)^2}\cdot \frac{2\left(\frac{x}{2}\right)^2}{2\sin^2\left(\frac{x}{2}\right)} = 2\lim \limits_{x \to 0}\frac{\sin x-x}{x^3},$$
$\lim \limits_{x \to 0}\frac{\sin x-x}{x^3}$ is here.


text:
Q: Gradle JavaExec StandardOutput to include Java command Is it possible to add in the java command to the standardOutput stream on a JavaExec command in Gradle?
Ie
task importSitesDef(dependsOn: init, type: JavaExec) {
    main = 'com.x'
    classpath = configurations.runE
    standardOutput = new FileOutputStream(standardLog, true)
}

Will log the output but I want to see
java com.x -cp ... in the file too before the input.
This is due to using the same output stream/file for multiple tasks and its very hard to tell where the output from one task finished before another one starts.

A: I know this is an old question but all I did to get the Java command used was to get the output of the JavaExec commandLine method and join it's elements, like so:-
commandLine.collect().join(' ')
Then output it.


text:
Q: Design for a mass e-mailer in an ASP.NET page --- is just a foreach loop and SmtpClient sufficient? We are interested in implementing something into our ASP.NET web application that will send out an e-mail to addresses pulled from SQL Server 2008.
This doesn't seem like it would be that difficult.  Pseudo-code:
EmailAddressList addresses = EmailAddressManager.GetList();

foreach (EmailAddress x in addresses)
{
    MailMessage msg = new MailMessage("fromaddress@test.com", x.ToAddress);
    //prepare msg, body, subject, etc.

    SmtpClient smtp = new SmtpClient();
    smtp.Send(msg);

    //add artificial delay for throttling?  this seems to be a common tactic
}

This question has an upvoted comment that links to something that was supposedly helpful, but now just leads to a Page Not Found error.
And in this question, the OP says specifically that the above pseudo-code method isn't "the good way."  But what is wrong with it?  Is there a common or better practice for this?  Are there hidden pitfalls I'm not taking into account?
And just a little bit more detail about our situation: this will only be used maybe twice per month, and the number of emails to be sent at once will not be above roughly 30 or 40.  The end goal is, we go to this page that has this tool, we can preview what's going to get sent out and to who, and then we just press a button and it executes the above pseudo-code.

A: I don't think there's anything wrong with a loop like you're doing, but there are a few things you probably need to handle. The most important would probably be error handling. If one of the emails fails, you'll just break out having sent emails to a subset of people, and it'll be tough to deal with should you need to send to the rest. Even if you have some simple try-catch, you'll still have a problem retrying those emails. You'll want to have some way of storing all the emails you planned on sending to and the results of each send.
Next will be performance-related. Sending emails one at a time using .Send() is going to be slow if it's a lot of emails. An easy way around it is to use the Task library or the Async version to multithread the sends. Of course this makes the state management a little more complicated, but it will improve email sending speed significantly. If you have a limit to the number of emails you can send per minute/hour, then that may or may not be at odds with this optimization.
If you have different content for each recipient you'll probably want to use some templating library like NVelocity or the MS Razor Engine.
Or you could just outsource this boring stuff to somewhere like SendGrid.


text:
Q: Date back vs date back to I don't know why they use this expression.
It's a text about "We Are the World" from an English textbook.

They recorded a song called "We Are the World 25 for Haiti" to aid people who were suffering from the disaster. As the title of the song shows, its roots date back 25 years.

Date back to is often found but date back isn't, it seems to me. I did look up the expression in a dictionary. I found a lot more examples of "date back to." The language textbook should prefer more-often-used expressions. But here date back is used. So I think that means the writer must have felt that "date back" is more appropriate here in the context. But I don't know why. I want to know native speakers' opinions. Is there any difference between date back and date back to? Is there any preference?
I'm waiting for you to "lend a helping hand."

A: Date back to is used when referring to the point or period in time when some event occurred. For example, "These pieces of artwork date back to the 18th century."
Date back (without to) is used when referring to the duration of time that has passed since some event occurred. For example, "These pieces of artwork date back 3 centuries."


text:
Q: Set default tab to Angular.js tabs I have an Angular.js component which has a list of tabs. When a tab is clicked I assign an ng-classto it (active), so it gets highlighted. This is working fine, but I also want the first tab to be the default active one when a user first load the page, but at the moment nothing is highlighted when I load the page.
Here's my component:
'use strict';

angular.module('menuBar').component('menuBar', {
    templateUrl: 'menu-bar/menu-bar.template.html',
    controller: function menuBarController() {
        this.menus = [
            {
                name: 'Tab1'
            }, {
                name: 'Tab2'
            }, {
                name: 'Tab3'
            }, {
                name: 'Tab4'
            }, {
                name: 'Tab5'
            }
        ];

        this.tab = this.menus[0].name;

        this.setTab = function (tabId) {
            this.tab = tabId;
        }

        this.isSet = function (tabId) {
            return this.tab === tabId;
        }
    }
});

Here my html template:

                {{menu.name}}

Maybe something wrong at this line here where I'm trying to set my default tab?
this.tab = this.menus[0].name;

Update: Plunker added
Live preview here

A:

            {{menu.name}}

A: You can use orderBy:

Function: A getter function. This function will be called with each item as argument and the return value will be used for sorting.

I'm not sure about the syntax since I haven't used components yet but something among the lines:

                {{menu.name}}


text:
Q: Copy a Range to another spreadsheet with data validations, formats etc I managed to copy values and formulas from one range to another spreadsheet range (of the same size).
Copy range to another spreadsheet
I need to copy formats, fonts, colors, borders, data validations etc to the new range in another spreadsheet.
Is it possible?

A: There are actually multiple ways to do this with built-in methods rather than manually. The easiest one is to use copyTo(). This copies everything you mentioned from a source range to a destination. A simple sample of how it works:
    //Replicate rangeA on rangeB

    let ss = SpreadsheetApp.getActiveSpreadsheet();
    let source = ss.getSheetByName("Sheet1")
    let destination = ss.getSheetByName("Sheet2");

    let rangeA = source.getRange("A1:A5");
    let rangeB = destination.getRange("A1");

    rangeA.copyTo(rangeB);

As mentioned in the documentation, only the top-left cell position in the destination range is relevant, so you only need to specify a single cell and the method will just expand the copied data accordingly.
In case that you need to narrow down what you need to copy there are other methods to just copy certain parts, for formatting you can use copyFormatToRange(), for just values you can use copyValuesToRange(), for data validations you first need to get them with getDataValidations() and then set them separately with setDataValidations(). Formulas work similarly with getFormulas() to setFormulas(), and so on.
I suggest you check the documentation for more code samples. The Range object actually has a lot of useful methods to manipulate ranges:

*

*Class Range


text:
Q: span minipage content over multiple pages I'm writing my own layout for the CV (that I'd like to convert into a public class), and I'm trying to have a two-column layout like the following:

where for each section the summary on the left side is a minipage, and the content another one, but wider.
As soon as I added more work experiences, I realized that LaTeX tried to put on a new minipage. I have made some search and the community suggests I should use flowfram, but I tried to take inspiration from other classes, where I saw some workaround using tabular.
The pros of flowfram is its easiness, but I would like to put each section's title with the content (well, as you can see not exactly. I place a little space above). Tabular seems to be the answer, but it sounds like the web in the old 90's.
So here is the question: which of the two I should use? Are there any other ways to accomplish that neatly?

A: A breakable sort of minipage can be done with the tcolorbox package.
The following could do the job. Observe that the WORK EXPERIENCE box is broken from page 1 to page 2.
\documentclass{article}
\usepackage{geometry}
\usepackage{lipsum}
\usepackage[skins,breakable]{tcolorbox}

\newtcolorbox{cvbox}[2][]{%
  blanker,
  leftupper=4cm,
  after skip=8mm,%   enlarge distance to the next box
  title=#2,
  breakable,
  fonttitle=\sffamily\bfseries,
  coltitle=cyan,
  fontupper=\sffamily,%
  #1
}

\begin{document}

\begin{cvbox}{SUMMARY}
  \lipsum[1]
\end{cvbox}

\begin{cvbox}{HIGHTLIGHTS}
  \begin{itemize}
    \item Methodical
    \item Blabla
  \end{itemize}
\end{cvbox}

\begin{cvbox}{WORK EXPERIENCE}
  \lipsum[2-5]
\end{cvbox}

\begin{cvbox}{CONCLUSION}
  \lipsum[6]
\end{cvbox}

\end{document}


text:
Q: Time difference in pandas (from string format to datetime) I have the following column
Time
2:00
00:13
1:00
00:24

in object format (strings). This time refers to hours and minutes ago from a time that I need to use as a start: 8:00 (it might change; in this example is 8:00).
Since the times in the column Time are referring to hours/minutes ago, what I would like to expect should be
Time
6:00
07:47
7:00
07:36

calculated as time difference (e.g. 8:00 - 2:00).
However, I am having difficulties in doing this calculation and transform the result in a datetime (keeping only hours and minutes).
I hope you can help me.

A: Since the Time columns contains only Hour:Minute I suggest using timedelta instead of datetime:
df['Time'] = pd.to_timedelta(df.Time+':00')
df['Start_Time'] = pd.to_timedelta('8:00:00') - df['Time']

Output:
      Time Start_Time
0 02:00:00   06:00:00
1 00:13:00   07:47:00
2 01:00:00   07:00:00
3 00:24:00   07:36:00

A: you can do it using pd.to_datetime.
ref = pd.to_datetime('08:00') #here define the hour of reference
s = ref-pd.to_datetime(df['Time'])
print (s)
0   06:00:00
1   07:47:00
2   07:00:00
3   07:36:00
Name: Time, dtype: timedelta64[ns]

This return a series, that can be change to a dataframe with s.to_frame() for example