text:
Q: Using a class method from another class in a class's class methods Hope that title was confusing enough for everyone! The program I am recreating uses a ton of classes. The two I am working with are called "receiver" and "storage". I have a class method in the storage class named store. In my receiver class I have a class method add. I need the add method to call Storage.store(object). The way it is setup now doesn't work but I can't seem to think of a work around. What is a different way to call a class method from a different class's class method?
require_relative 'storage.rb'

class Receiver

 #{PRIVATE}
  private
  attr_accessor :first_name, :last_name, :number

 #{PUBLIC}
  public

    @@receivers = []

    def initialize(first_name, last_name, number)
      @first_name = first_name.downcase.capitalize
      @last_name = last_name.downcase.capitalize
      @number = number
      Receiver.add(@first_name,@last_name,@number)
    end

    class << self

      def add(first_name,last_name,number)
        first_name = {:first_name => first_name, :last_name => last_name, :number => number}
        @@receivers << first_name
        Storage.store({})
      end
   end
end

C:/Users/sutley/Desktop/Ruby Scripts/Ruby Procs/receiver.rb:30:in 'add': uninitialized constant Class::Storage (NameError)
Edit-----------
class Storage

  class << self

    def store object

    end

    def un_store first_name

    end

    def show_all
      end
    end

  end

Unfortunately I can't post all of the code. How ever this is all that's needed because it doesn't work even with the empty methods


text:
Q: UIActivityViewController => LaunchServices: invalidationHandler called I am playing around with the idea of Airdrop. There is an error while running the sample code by Apple:
https://developer.apple.com/library/ios/samplecode/sc2273/Introduction/Intro.html
The error message is:
LaunchServices: invalidationHandler called

The problem is obviously caused by UIActivityViewController. The related code is under #pragma mark - Actions of this file if you could have a look.
It only show the error message when running on devices (both iPhone and iPad). It is all fine if running on simulator (both iPhone and iPad). What's the cause of this? Any idea about how to resolve it? Could it be possibly a bug?
Similar questions are asked by the following, none of which seems to be able to answer this quesition:
LaunchServices: invalidationHandler called - iOS 8 share sheet
Sharing via UIActivityViewController to Twitter/Facebook etc. causing crash
Present UIActivityViewController- LaunchServices:invalidationHandler called

A: This is a bug on Apple's side.  From the developer forums:

That log message does not indicate any error on your part.

A: You have to get rid of the if statement that calls "isAvailableForServiceType:". It should look something like this. Good luck!
    SLComposeViewController *tweetSheet = [SLComposeViewController
                                           composeViewControllerForServiceType:SLServiceTypeTwitter];

    [tweetSheet setInitialText:@"Great fun to learn iOS programming at appcoda.com!"];
    [self presentViewController:tweetSheet animated:YES completion:nil];

    if ([tweetSheet respondsToSelector:@selector(popoverPresentationController)])
    {
        // iOS 8+
        UIPopoverPresentationController *presentationController = [tweetSheet popoverPresentationController];

        presentationController.sourceView = sender; // if button or change to self.view.
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Detecting when a player leaves a projectile and then removing entity I am building a 1.8.8 Bukkit/Spigot plugin that allows you to ride ender pearls and am stuck at detecting a dismount and removing the pearl. I have tried to catch the event but it doesn't compile. I need a way to remove the pearl when there is a dismount. Thank you!
package damotheryeeter.general.enderpearlride.events;

import org.bukkit.entity.Player;
import static org.bukkit.Material.ENDER_PEARL;
import org.bukkit.entity.EntityType;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import org.bukkit.inventory.ItemStack;

public class EnderThrowEvent implements Listener {
@EventHandler
public void onThrow(final ProjectileLaunchEvent e) {
    if (e.getEntityType().equals(EntityType.ENDER_PEARL)) {
        if (!(e.getEntity().getShooter() instanceof Player)) return;
        if (((Player) e.getEntity().getShooter()).hasPermission("enderpearlride.ride")) {
            e.getEntity().setPassenger((Player) e.getEntity().getShooter());
            if (((Player) e.getEntity().getShooter()).hasPermission("enderpearlride.infinite")) {
                final Player p = (Player) e.getEntity().getShooter();
                final ItemStack[] pearl = {new ItemStack(ENDER_PEARL, 1)};
                p.getInventory().addItem(pearl);
            }
        }
    }
}

A: The code for that is:
@EventHandler
public void onDismount(EntityDismountEvent e) {
    if(e.getEntity().getEntityType().equals(EntityType.ENDER_PEARL)) {
        e.getEntity().remove();
    }
}


text:
Q: JPA Annotations for Multiple One-to-One Self-Referential Relations I'm trying to define the model for a task object that has a reference to the previous task, and a reference to the next task. This is how I have attempted to model those relationships in my CompletableTask.java class:
@OneToOne(mappedBy = "previousTask", orphanRemoval = true)
@JoinColumn(name = "next_task_id")
private CompletableTask nextTask;

@OneToOne(mappedBy = "nextTask", orphanRemoval = true)
@JoinColumn(name = "previous_task_id")
private CompletableTask previousTask;

However, when I boot up my application and let Hibernate create the necessary schema updates for this, I receive the following error log:
org.hibernate.AnnotationException: Unknown mappedBy in: com.my_package.CompletableTask.nextTask, referenced property unknown: com.my_package.CompletableTask.previousTask

I have been able to resolve this issue by simply removing the mappedBy = "previousTask" argument from the nextTask's one-to-one annotation, but then no previous_task_id is present in the table that Hibernate generates, which I believe to be incorrect for my intended purposes.
Could someone please explain how I would go about modelling this? And in the case that it's impossible to achieve the desired schema that has references to both the next and previous tasks, what are my alternatives?

A: mappedBy denotes the attribute that "owns" the relationship in a bidirectional relationship.
Therefore it does not make sense to have mappedBy on both side.
Please remove one.


text:
Q: Build a raw socket I have to send a totally raw socket in C. I have a C array that contains all iso/osi layers and I want to send it exactly as is, without any layers being changed by the operating system.
However the first bytes of the packet are modified, while the other bytes are sent correctly. My code is below:
static const unsigned char pkt149[76] = {
0x00, 0x00, 0x03, 0x04, 0x00, 0x06, 0x00, 0x00, /* ........ */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, /* ........ */
0x45, 0x00, 0x00, 0x3c, 0x6f, 0x7b, 0x40, 0x00, /* E..<o{@. */
0x40, 0x06, 0x44, 0x00, 0xc0, 0xa8, 0x02, 0xf8, /* @.D..... */
0xc0, 0xa8, 0x02, 0xf8, 0xcd, 0x9e, 0x1f, 0x40, /* .......@ */
0xa2, 0xe1, 0xcd, 0x01, 0x00, 0x00, 0x00, 0x00, /* ........ */
0xa0, 0x02, 0xff, 0xd7, 0x87, 0x6f, 0x00, 0x00, /* .....o.. */
0x02, 0x04, 0xff, 0xd7, 0x04, 0x02, 0x08, 0x0a, /* ........ */
0x99, 0x86, 0x21, 0xfe, 0x00, 0x00, 0x00, 0x00, /* ..!..... */
0x01, 0x03, 0x03, 0x07                          /* .... */
};

int sock = 0;
    int res = 0;
    struct ifreq ifr;
    struct sockaddr_ll sll;
    unsigned char rxBuff[RX_BUFF_LEN];

    memset(&ifr, 0, sizeof(ifr));
    memset(&sll, 0, sizeof(sll));

    sock = socket (AF_PACKET, SOCK_RAW, IPPROTO_RAW);
    if (sock < 0)
    {
        perror ("Errore durante la creazione della socket RAW di livello datalink \n");
    }
    else
    {
        printf ("Socket RAW creata \n");
    }

    strncpy(ifr.ifr_name, "enp0s8", sizeof(ifr.ifr_name));

    if (ioctl(sock, SIOCGIFINDEX, &ifr) == -1)
    {
        perror ("Errore ioctl \n");
    }

    sll.sll_family = AF_PACKET;
    sll.sll_ifindex = ifr.ifr_ifindex;
    sll.sll_protocol = htons(ETH_P_ALL);

    if (bind(sock, (struct sockaddr *) &sll, sizeof(sll)) == -1)
    {
        perror ("Errore bind \n");
    }
    send(sock, pkt149, sizeof(pkt149), 0);

On wireshark the packet sent is the following:
00 04 00 01 00 06 00 00 00 00 00 00 00 00 00 00
08 00 45 00 00 3c 6f 7b 40 00 40 06 44 00 c0 a8
02 f8 c0 a8 02 f8 cd 9e 1f 40 a2 e1 cd 01 00 00
00 00 a0 02 ff d7 87 6f 00 00 02 04 ff d7 04 02
08 0a 99 86 21 fe 00 00 00 00 01 03 03 07
enter image description here
how can i send the package as is?  Thank you


text:
Q: How to programatically download files with increased speed in android Hi have implemented programatically downloading of file using inputstream and cipheroutputstream(for encryption). The download is happening very slow. Whereas if i try to download via download manager, it is very fast. What can i do to improve my code and increase the download speed of the file. Below is my code.
 private void saveFileUsingEncryption(String aMineType, long length) throws Exception {

    int bufferSize = 1024*4;

    //byte[] buffer = new byte[1024];
    byte[] buffer = new byte[bufferSize];
    int bytesRead = 0;
    long totalRead = 0;

    FileOutputStream outStream = null;

    File f = new File(Constants.DWLPATH);
    if (!f.exists()) {
        f.mkdirs();
    }

    try {

        Cipher aes = Cipher.getInstance("ARC4");
        aes.init(Cipher.ENCRYPT_MODE,  new SecretKeySpec("mykey".getBytes(), "ARC4"));

        if(contDisp==null || contDisp.length()==0) {
            // downloadFileName = downloadFileName.replaceAll("[^a-zA-Z0-9_]+", "");
            downloadFileName = downloadFileName + "." + getFileExtension(aMineType);

        }

        outStream = new FileOutputStream(Constants.DWLPATH +  downloadFileName,true);
        CipherOutputStream out = new CipherOutputStream(outStream, aes);

        while ((bytesRead = inputStream.read(buffer, 0, bufferSize)) >= 0) {

            out.write(buffer, 0, bytesRead);

            try{
                // Adjust this value. It shouldn't be too small.
                Thread.sleep(50);
            }catch (InterruptedException e){
              TraceUtils.logException(e);
            }
            totalRead += bytesRead;
            sb=sb.append("\n Total bytes Read:"+totalRead);
            Log.e("--",sb.toString());
           /* if (this.length > 0) {
                Long[] progress = new Long[5];
                progress[0] = (long) ((double) totalRead / (double) this.length * 100.0);

                publishProgress(progress);
            }*/

            if (this.isCancelled()) {
                if (conn != null)
                    conn.disconnect();
                conn = null;
                break;
            }

        }
        Log.e("Download completed","success");
        out.flush();
        //Utils.putDownloadLogs(requestUrl,mimeType,length, downloadFileName,"Download is Successful",sb.toString(), context);
        outStream.close();

        buffer = null;

    } catch (Exception e) {
        TraceUtils.logException( e);

        file_newsize = storedFileSizeInDB + totalRead;
        if (totalFileSize == 0)
            totalFileSize = length;

        callback.onRequestInterrupted(file_newsize,totalFileSize);

        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        // Utils.putDownloadLogs(requestUrl,mimeType,length,downloadFileName,"failure---" + errors.toString(),sb.toString(), context);

        throw e;

    } finally {
        if (outStream != null)
            outStream.close();
        outStream = null;
    }
}

A: You can use default download manager to download the file because its very easy to implement and provide better features like respond to the internet connection , provide accessibility to add notification in status bar , by running the query on download manager object you can find the total bytes and remaining bytes so you can calculate the progress and after completion of download by tapping the notification one can perform the desired operation.
And also there are many libraries are available for to achieve this like
PRDOWNLOADER
FetchDownloader
This libraires provide you the feature of pause,download, resume download , tracking the progress and cancel download
Also you can customize it as per your need.

A: Here is the DownloadAndEncryptFileTask.class to download with encryption
public class DownloadAndEncryptFileTask extends AsyncTask<Void, Void, Void> {

private String mUrl;
private File mFile;
private Cipher mCipher;

InputStream inputStream;
FileOutputStream fileOutputStream;
CipherOutputStream cipherOutputStream;

public DownloadAndEncryptFileTask(String url, File file, Cipher cipher) {
    if (url == null || url.isEmpty()) {
        throw new IllegalArgumentException("You need to supply a url to a clear MP4 file to download and encrypt, or modify the code to use a local encrypted mp4");
    }
    mUrl = url;
    mFile = file;
    mCipher = cipher;
}

private void downloadAndEncrypt() throws Exception {

    URL url = new URL(mUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    if (mFile.length() > 0) {
        connection.setRequestProperty("Range", "bytes=" + mFile.length() + "-");
    }
    connection.connect();

    Log.e("length", mFile.length() + "");

    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new IOException("server error: " + connection.getResponseCode() + ", " + connection.getResponseMessage());
    }

    inputStream = connection.getInputStream();
    if (mFile.length() > 0) {
        //connection.connect();
        fileOutputStream = new FileOutputStream(mFile, true);

    } else {
        fileOutputStream = new FileOutputStream(mFile);
    }

    CipherOutputStream cipherOutputStream = new CipherOutputStream(fileOutputStream, mCipher);

    byte buffer[] = new byte[1024 * 1024];
    int bytesRead;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        Log.d(getClass().getCanonicalName(), "reading from http...");

        cipherOutputStream.write(buffer, 0, bytesRead);
    }

    inputStream.close();
    cipherOutputStream.close();
    connection.disconnect();
}

@Override
protected Void doInBackground(Void... params) {
    try {
        downloadAndEncrypt();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

@Override
protected void onPostExecute(Void aVoid) {
    Log.d(getClass().getCanonicalName(), "done");
}
}

Call this class
new DownloadAndEncryptFileTask(
    myFeedsModel.getVideo().getVideo360(),
    new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), myFeedsModel.getFile_name()),
    OBJECT OF YOUR CIPHER


text:
Q: Is it possible to initialize a private array in a header file with a member which is initialized in the constructor? c++ I would like to declare an array in a header file but I would like have the size of the array declared when the class is constructed. Is this possible? I found a lot of array declarations on this site but not this in particular. When I try the code below I get the error "array bound is not an integer constant before ']' token"
foo.h
class foo{
   private:
      uint16_t _size;
      uint16_t array[_size];
   public:
      foo(uint16_t size);
      virtual ~foo();
}

foo.cpp
#include "foo.h"
foo::foo(uint16_t size)
:_size(size)
{
}

A: One particular way of doing it is this
class foo
{
public:
   foo(uint16_t size);
private:
   uint16_t _size;
   uint16_t* array;
};

foo::foo(uint16_t size) :_size(size)
{
    array = new int[_size];
}

That will allow you to dynamically create an array at runtime, I would suggest you use a std::vector though because generally they are a lot better than arrays in C++(IMO) but if you have a particular reason to use an array thats the way I'd do it. Using static means that if you wanted to use that class elsewhere then _size would share the same values between instances also I wouldn't think that would compile because only static functions can access static members.
EDT: in my haste to answer I forgot to say that you should add a destructor in your class to destroy the array when the class goes out of scope something like this
foo:~foo()
{
    delete[] array;
}

Got downvoted because I never added in a reference to rule of three. Ideally you shouldn't use dynamically initialised arrays anyway and just use vectors here's the link to the rule of three C++ rule of three

A: Ideally, you should use std::vector<uint16_t>: it lets you decide the size dynamically, like this:
vector<uint16_t> array;
...
foo(size_t size) : array(size) {}
...

Alternatively, you can use a pointer instead of the array, allocate it in the constructor, and  delete in the destructor:
uint16_t *array;
...
foo(size_t size) : array(new uint16_t[size]) {}
...
~foo() {delete[] array;}

This is not as good, because once you define the destructor, you need to deal with the rule of three.

A: You could use template parameter to define array size, if you really have to use array:
template<size_t N>
class foo{
private:
    uint16_t array[N];

public:
    foo()
    {
    }
};

foo<3> f;

std::vector is dynamic array in C++, it provides rich interfaces to operate array, there is little reason not to use std::vector.
class foo{
private:
    std::vector<uint16_t> array;

public:
    foo(uint16_t size) : array(size)
    {
    }
};

A: You can't do that. The size of an array must be a compile time constant. In your case the size of an instance of class foo depends on the size of the array. If you know the size of the contained array at compile time for every use of class foo, then you could use a template:
template <size_t N>
class foo {
    uint16_t array[N];
public:
    foo() {}
};

Otherwise you should use the resizable array offered by C++: std::vector:
class foo {
    std::size_t size;
    std::vector<uint16_t> array;
public:
    foo(std::size_t size_)
    : size(size_)
    , array(size_)
    {}
};

A: That's not how you initialize a static variable. Here's how (usually in the CPP file):
uint16_t foo::_size = /* something */;

But I don't think you want a static variable.
I'd suggest you to go with dynamic allocated arrays instead:
class foo{
   private:
      uint16_t _size;
      uint16_t* array;
      static uint16_t* copy(uint16_t* a, uint16_t s) {
          if (!a) return 0;
          uint16_t* ret = new uint16_t[s];
          for (int i = 0; i < s; i++) ret[i] = a[i];
          return ret;
      }
   public:
      foo(const foo& f) : _size(f._size), array(0) { array = copy(f.array, f._size); }
      foo(uint16_t size = 0) : _size(size), array(0) {
          if (size == 0) return;
          array = new uint16_t[_size];
      }
      ~foo() { delete[] array; }
}

Even a better solution would be to use one of the standard library containers such as std::vector.

A: Use a vector.
class foo{
   private:
      std::vector<uint16_t> array;
   public:
      foo(uint16_t size)
};

foo::foo(uint16_t size) : array(size)
{
}


text:
Q: functions as template argument, plus variadic template argument I'm writing a generalized function wrapper, that can wrap any function into a lua-style call, which has the form
int lua_function( lua_State *L)
And I wish the wrapper function is generated on-the-fly, so I'm thinking of passing the function as a template argument. This is trivial if you know the number (e.g, 2) of arguments:
template <typename R, typename Arg1, typename Arg2, R F(Arg1, Args)>
struct wrapper

However, I don't know the number, so I beg for variadic template argument for help
// This won't work
template <typename R, typename... Args, R F(Args...)>
struct wrapper

The above won't compile, since variadic argument has to be the last one. So I use two level template, the outer template captures types, the inner template captures the function:
template <typename R, typename... Args>
struct func_type<R(Args...)>
{
  // Inner function wrapper take the function pointer as a template argument
  template <R F(Args...)>
  struct func
  {
    static int call( lua_State *L )
    {
      // extract arguments from L
      F(/*arguments*/);
      return 1;
    }
  };
};

That works, except that to wrap a function like
double sin(double d) {}

the user has to write
func_type<decltype(sin)>::func<sin>::apply

which is tedious.
The question is: is there any better, user-friendlier way to do it? (I can't use a function template to wrap the whole thing, coz a function parameter can't be used as a template argument.)

A: Things like std::function and std::result_of use the following technique to do what you want regarding variadic templates:
template<typename Signature>
struct wrapper; // no base template

template<typename Ret, typename... Args>
struct wrapper<Ret(Args...)> {
    // instantiated for any function type
};

You could expand the above to add a non-type Ret(&P)(Args...) template parameter (pointers to function work just as well) but you'd still need a decltype at the user level, i.e. wrapper<decltype(sin), sin>::apply. Arguably it would be a legitimate use of the preprocessor if you decide to use a macro to remove the repetition.
template<typename Sig, Sig& S>
struct wrapper;

template<typename Ret, typename... Args, Ret(&P)(Args...)>
struct wrapper<Ret(Args...), P> {
    int
    static apply(lua_State*)
    {
        // pop arguments
        // Ret result = P(args...);
        // push result & return
        return 1;
    }
};

// &wrapper<decltype(sin), sin>::apply is your Lua-style wrapper function.

The above compiles with gcc-4.5 at ideone.
Good luck with implementing the apply that (variadically) pops the arguments (leave me a comment if you open a question about that). Have you considered using Luabind?

A: As @Juraj says in his comment, the function pointer can be a template argument, see the following simple example:
#include <iostream>
#include <boost/typeof/typeof.hpp>

void f(int b, double c, std::string const& g)
{
  std::cout << "f(): " << g << std::endl;
}

template <typename F, F* addr>
struct wrapper
{
  void operator()()
  {
    std::string bar("bar");
    (*addr)(1, 10., bar);
  }
};

int main(void)
{
  wrapper<BOOST_TYPEOF(f), &f> w;
  w();
  return 0;
}

working version: http://www.ideone.com/LP0TO
I'm using BOOST_TYPEOF as normally I always provide examples in the current standard, but it does something similar to decltype. Is this what you were after?


text:
Q: libcurl download file size exceed buffer size I have a question regarding this code at https://curl.haxx.se/libcurl/c/ftpget.html
In the call back function
static size_t my_fwrite(void *buffer, size_t size, size_t nmemb, void *stream)
{
  struct FtpFile *out=(struct FtpFile *)stream;
  if(out && !out->stream) {
    /* open file for writing */
    out->stream=fopen(out->filename, "wb");
    if(!out->stream)
      return -1; /* failure, can't open file to write */
  }
  return fwrite(buffer, size, nmemb, out->stream);
}

What if the file size exceed the buffer size? I think the function will not be called iteratively since it overwrites the file everytime. Is there a work-around of it? Thanks!

A: From curl documentation :

The callback function will be passed as much data as possible in all
  invokes, but you must not make any assumptions. It may be one byte, it
  may be thousands. The maximum amount of body data that will be passed
  to the write callback is defined in the curl.h header file:
  CURL_MAX_WRITE_SIZE (the usual default is 16K). If CURLOPT_HEADER is
  enabled, which makes header data get passed to the write callback, you
  can get up to CURL_MAX_HTTP_HEADER bytes of header data passed into
  it. This usually means 100K.


text:
Q: CSS3 Blur effect causes weird shadows on hover I got an html page where there is a DIV element covering the whole background with a background image, This DIV has also Blurred css3 effect on it.
When ever i hover on elements that sit above the blurred div i get alot of weird shadow bugs happening.
Chrome on OSX.
Attached screenshot:

Here is my background css:
#background {
    -webkit-transform: translate3d(0,0,0);
    background-repeat: no-repeat !important;
    background-position: center  !important;
    background-attachment: center fixed;
    -webkit-transform: scale(1.1);
    height: 100%;
    width: 100%;
    position: absolute;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    z-index: -1;
    box-shadow: inset 0px 0px 230px 75px rgba(0,0,0,0.8);
    overflow: hidden;
    -webkit-transition: -webkit-filter 0.4s ease-in-out;
}

.backgroundblur {
    -webkit-filter: blur(5px);
    -moz-filter: blur(5px);
    -o-filter: blur(5px);
    -ms-filter: blur(5px);
    filter: blur(5px);
}

A: Maybe you could load your HTML with this sample. But I guess that problem is in #background element, coz  there's shadow applied on it, and it look like your content is in that element also.
I tried to produce similar effect on     <http://jsfiddle.net/zlajaa1/4s941ewz/>    . Problem here is negative z-index value. So maybe you can try to play with that property also.
For more help, attach HTML with this please.


text:
Q: Error message when compiling while-loop expected identifier When trying to compile an infinite while loop in xcode iphone view based application, it gives me an error that reads expected identifier or '(' before 'while'.  I made it as simple as possible.  Sorry about the picture.  Code block was not working.  If you want to see an image of the code, here is the link.  http://www.freeimagehosting.net/uploads/931d5d8788.gif
#import "Lockerz_NotifierViewController.h"

@implementation Lockerz_NotifierViewController
NSMutableData *responseData;

while (1) {
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://amicionline.me"]
                                                cachePolicy:NSURLRequestUseProtocolCachePolicy
                                            timeoutInterval:60.0];
    // create a connection
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if(theConnection) {
        // create the datum
        responseData=[[NSMutableData data] retain];
    } else {
        // code this later
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [responseData setLength:0];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // make it work
    NSLog(@"Succeeded! Received %d bytes of data:",[responseData length]);

    // release it
    [connection release];
    [responseData release];

}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [responseData appendData:data];
}

A: What are you trying to do? You can't write code directly in an @implementation. You must put it inside a method, for example:
-(void)start {
   while (1) {
     ...
   }
}


text:
Q: Unable to use XSSF with Excel 2007 I am having tough time getting to read data from excel 2007. I am using XSSF to read data from a specific cell of excel but keep getting error -
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.xmlbeans.XmlOptions.setSaveAggressiveNamespaces()Lorg/apache/xmlbeans/XmlOptions;
    at org.apache.poi.POIXMLDocumentPart.(POIXMLDocumentPart.java:46)

This is my piece of code:
public static void main(String [] args) throws IOException {
    InputStream ins = new FileInputStream("C:\\Users\\Tarun3Kumar\\Desktop\\test.xlsx");
    XSSFWorkbook xwb = new XSSFWorkbook(ins);
    XSSFSheet sheet = xwb.getSheetAt(0);
    Row row = sheet.getRow(1);
    Cell cell = row.getCell(0);
    System.out.println(cell.getStringCellValue());
    System.out.println("a");
}

I have following jars added to build path -
poi-3.6
poi-ooxml-3.6
poi-ooxml-schemas-3.6
x-bean.jar
I could only figure out that setSaveAggressiveNamespaces has replaced setSaveAggresiveNamespaces....

A: there is other issue happen to be: xbean.jar and xmlbeans.jar both have XmlOptions, but only xmlbeans.jar have method you want. I changed path order for xmlbeans.jar first and worked.


text:
Q: Array values suddenly changing in C I'm making a program that has global arrays. In the function where I assign values to the arrays and print them, everything is fine. But as soon as I try to use these arrays in another function, suddenly the values are different.
    int *numeros;
    char *operadores;
    int num, num_operadores;

void crearArray() {

    int i;

    printf("How many numbers?\n");
    scanf("%d", &num);

    numeros = (int*)calloc(num, sizeof(int));
    operadores = (char*)calloc(num - 1, sizeof(char));
    num_operadores = num - 1;

    num += (num - 1);

    for (i = 0; i < num; i++) {

        if(i % 2 == 0 || i == 0) {
            printf("\t\nEnter a number: ");
            scanf("%d", &numeros[i]);
        }
        else {
            fflush(stdin);
            printf("\t\nEnter an operator: ");
            scanf("%c", &operadores[i]);
        }

    }

    printf("Array: ");

    for (i = 0; i < num; i++) {

        if(i % 2 == 0 || i == 0)
            printf("%d ", numeros[i]);

        else
            printf("%c ", operadores[i]);

    }

}

void crearArbol() {

    int i;

    printf("\n\nArrays:\n\t Numbers: ");

    for(i = 0; i < num_operadores + 1; i++)
        printf("\n\t\t Numeros[%d]: %d ", i, numeros[i]);

    printf("\n\t Operators: ");

    for(i = 0; i < num_operadores; i++)
        printf("\n\t\t Operadores[%d]: %c ", i, operadores[i]);

}

int main() {
    crearArray();

    crearArbol();

    return 0;
}

Of course, printing the array wasn't the main purpose for crearArbol but for now there's nothing in there but that and I can't seem to work out why it changes.
Example output:

How many numbers?
3
Enter a number: 1
Enter an operator: *
Enter a number: 2
Enter an operator: /
Enter a number: 3
Array: 1 * 2 / 3     (Printed array from first function crearArray)
Arrays:
  Numbers:
Numeros[0]: 1
Numeros[1]: 0
Numeros[2]: 2
Operators:
Operadores[0]:
Operadores[1]: *    (Printed array values from second function crearArbol)

Thanks in advance for any help!

A: You're writing and reading outside the bounds of the arrays. You're using i to alternately index numeros and then operadores, but that means i is always twice as big as it should be for either array. You need to divide i by two to convert it into a usable index.
num += (num - 1);

for (i = 0; i < num; i++) {

    if(i % 2 == 0 || i == 0) {
        printf("\t\nEnter a number: ");
        scanf("%d", &numeros[i / 2]);
    }
    else {
        fflush(stdin);
        printf("\t\nEnter an operator: ");
        scanf("%c", &operadores[i / 2]);
    }

}

Rather than doubling num and then alternating access to the two arrays based on whether i is divisible by two, I'd keep num as is and instead access both arrays each loop iteration.
for (i = 0; i < num; i++) {

    printf("\t\nEnter a number: ");
    scanf("%d", &numeros[i]);

    if (i < num - 1)
        fflush(stdin);
        printf("\t\nEnter an operator: ");
        scanf("%c", &operadores[i]);
    }

}

A: The reason for this behavior is that you are not reading the items into the correct indexes of the array: only indexes 0, 2, 4, ... of numeros have valid data, while indexes 1, 3, 5, ... of oepradores have operators. The remaining indexes have zeros, because you allocated with calloc.
The first function masks this problem by printing the same indexes that it reads, while the second function exposes the issue by printing "straight" indexes.
Obviously, the reading part is an issue, because it goes past the end of allocated arrays (an undefined behavior). You can fix it by modifying the reading loop to read both the number and the operator in the same go:
// Do not increment num
for (i = 0; i < num; i++) {
    printf("\t\nEnter a number: ");
    scanf("%d", &numeros[i]);
    if (i == num-1) {
        break; // Last number comes with no operator
    }
    fflush(stdin);
    printf("\t\nEnter an operator: ");
    scanf("%c", &operadores[i]);
}

Obviously, you would also need to modify the printing code of crearArray to match that of crearArbol.

A: Respectfully, the mental error was trying to treat two      separate arrays as if a single array. Find an example of an array of structures. Use separate index variables on separate arrays?!
A suggestion for compound conditionals: use (()) instead of relying on rules of precedent.
I really can not figure your use of fflush on an input stream. This also points out the lack of error checking.
As a general practice, learn how to dump your data from your debugger. As a source of debug ideas, save the code, then modify and see what happens...


text:
Q: Clone a github repository, then upload it to my own repository I have cloned a repository to download the code, now I want to work on it and save it in my own private repository on Github. I don't want to contribute to the original project or submit changes or anything, it's just a personal project. When I try to do this, however, my git isn't working because I think it's already associated with the repository that I did the clone command from. How do I properly do what I'm talking about?

A: If you don't want to appear as a fork of the repo, you can change your git origin :
$ git remote rm origin
$ git remote add origin git@github.yourusername/yourproject.git
$ git config master.remote origin
$ git config master.merge refs/heads/master

You can then push to yourusername/yourproject


text:
Q: Problem in retrieving datetime parameter from url iam passing some parameters in url to a page through curl, but to my surprise, iam not able to retrieve all of the parameters.
This is an example of my url:
http://localhost/a.php?include=true&F1=2011-01-23 12:20:00&F2=2011-01-25 01:00:00
But in my "a.php" page, when i printed:

$_SERVER["REQUEST_URI"]

iam getting it like this:   a.php?include=true&F1=2011-01-23
iam not getting full F1 parameter, and F2 parameter is not coming at all. I hope it is the problem with the space in the datetime parameters. If so, how to accomplish this?
Note that i cant change the datetime value as part of url, like i cant use timestamp instead of that.

A: Propobly it space problem. In url's space is encoded as '+'. Can you use urlencode in your curl script like this:
 $url = "http://localhost/a.php?include=true&F1=".urlencode("2011-01-23 12:20:00")."&F2=".urlencode("2011-01-25 01:00:00");

A: It might worth to try to urlencode the $_GET properly
$arr =
array
(
  'include'=>'true',
  'F1'=>'2011-01-23 12:20:00',
  'F2'=>'2011-01-25 01:00:00'
);
$url = 'http://localhost/a.php?'.http_build_query($arr);


text:
Q: docker container: changing network kernel settings, net.core.rmem_max I'm trying to set net.core.rmem_max=26214400 on a container
I have this docker-compose
    develop:
      sysctls:
       - net.core.rmem_max=26214400
      image: centos6

but when I do
docker-compose up -d develop

I get this error
ERROR: for develop_1  Cannot start service develop: OCI runtime create
failed: container_linux.go:348: starting container process caused
 "process_linux.go:402: container init caused \"open
 /proc/sys/net/core/rmem_max: no such file or directory\"": unknown

ERROR: for develop  Cannot start service develop: OCI runtime create
 failed: container_linux.go:348: starting container process caused
 "process_linux.go:402: container init caused \"open
 /proc/sys/net/core/rmem_max: no such file or directory\"": unknown

A: What docker image are you using? Not all namespaced kernel parameters on the host are available in the container. Most likely the one you mention is not.
You can quickly inspect which are indeed available by running:
docker run --rm develop ls -l /proc/sys/net/core

I'd also recommend checking the corresponding compose docs.


text:
Q: get term objects and post objects in query I'm trying til change the search results of the add link tinymce popup box to include some terms from custom taxonomies. I'm using the wp_link_query_args and wp_link_query filters.
My issue is that the query from wp_link_query_args is using the standard WP_query class to fetch the results.
I have searched everywhere for a solution but i can't seem to find anyway to include terms as object in a WP_query. Is this possible at all?
For clarification i'm not trying to get posts of certain terms. I'm trying to all posts AND the term objects.
For the code:
The WP_query arguments I'm hooking into is:
$pts = get_post_types( array( 'public' => true ), 'objects' );
$pt_names = array_keys( $pts );

$query = array(
    'post_type' => $pt_names,
    'suppress_filters' => true,
    'update_post_term_cache' => false,
    'update_post_meta_cache' => false,
    'post_status' => 'publish',
    'posts_per_page' => 20,
);

// THIS IS THE FILTER I'M HOOKING INTO
$query = apply_filters( 'wp_link_query_args', $query );
// AFTER THIS LINE I DON'T HAVE CONTROL OF CODE
// Do main query.
$get_posts = new WP_Query;
$posts = $get_posts->query( $query );


text:
Q: Method decorator that allows to execute a decorated method only once Typescript I have a task to Implement a method decorator that allows to execute a decorated method only once.
For example:
   class Test {
        data: any;
        @once
        setData(newData: any) {
            this.newData = newData;
        }
    }
    const test = new Test();
    test.setData([1,2,3]);
    console.log(test.data); // [1,2,3]
    test.setData('new string');
    console.log(test.data); // [1,2,3]

I tried a lot of combinations to make a function that being called twice do nothing,but it's not what i should have and unit tests are failing,so,this is what i have till now:
const once = (
    target: Object,
    propertyKey: string | symbol,
    descriptor: PropertyDescriptor
) => {
    const method = descriptor.value;

    descriptor.value = function (...args){
        // ???
    }
};

Unit tests:
describe('once', () => {
    it('should call method once with single argument', () => {
        class Test {
            data: string;
            @once
            setData(newData: string) {
                this.data = newData;
            }
        }
        const test = new Test();
        test.setData('first string');
        test.setData('second string');
        assert.strictEqual(test.data, 'first string')
    });

    it('should call method once with multiple arguments', () => {
        class Test {
            user: {name: string, age: number};
            @once
            setUser(name: string, age: number) {
                this.user = {name, age};
            }
        }
        const test = new Test();
        test.setUser('John',22);
        test.setUser('Bill',34);
        assert.deepStrictEqual(test.user, {name: 'John', age: 22})
    });

    it('should return always return first execution result', () => {
        class Test {
            @once
            sayHello(name: string) {
                return `Hello ${name}!`;
            }
        }
        const test = new Test();
        test.sayHello('John');
        test.sayHello('Mark');
        assert.strictEqual(test.sayHello('new name'), 'Hello John!')
    })
});

Could you help me please? Thanks in advance!

A: Try something like this:
const once = (
  target: Object,
  propertyKey: string | symbol,
  descriptor: PropertyDescriptor
) => {
  const method = descriptor.value;
  let isFirstTime = true;

  descriptor.value = function (...args: any[]) {
    if (!isFirstTime) { return; }
    isFirstTime = false;
    method(...args);
  }
};

A: reflect-metadata is pretty handy for this scenario. You could try something like this:
import 'reflect-metadata';

const metadataKey = Symbol('initialized');

export function once(
    target: any,
    propertyKey: string,
    descriptor: PropertyDescriptor
) {
    const method = descriptor.value;
    descriptor.value = function(...args) {
        const initialized = Reflect.getMetadata(metadataKey, target, propertyKey);

        if (initialized) {
            return;
        }

        Reflect.defineMetadata(metadataKey, true, target, propertyKey);

        method.apply(this, args);
    }
}

You can find some more information on it here: https://www.typescriptlang.org/docs/handbook/decorators.html#metadata

A: I have solved a similar problem in this way:
function once(_target: any, _methodName: string, descriptor: PropertyDescriptor): PropertyDescriptor {
    const originalMethod = descriptor.value;
    let isFirstTime = true;
    descriptor.value = function (...args: any[]) {
        if (isFirstTime) {
            isFirstTime = false;
            this.previousValue = originalMethod.apply(this, args);
        } else {
            return this.previousValue;
        }
    };
    return descriptor;
}


text:
Q: how to name the output dataframe generated by python-ply How can I name the data frame generated by the following code?
import re
import os
import csv
import codecs
import numpy as np
import matplotlib as p
import pdb
import pandas as pd
from pandas_ply import install_ply, X, sym_call

install_ply(pd)

(data_merged
    .groupby('index')
    .ply_select(
        count = X.index.count(),
        p_avg = X.item_price.mean()
        ))

A: Looking at your example, I assume that you mean to name the output variable of the dataframe, which would be data_out in the following:
data_out = (data_merged
                .groupby('index')
                .ply_select(
                    count = X.index.count(),
                    p_avg = X.item_price.mean()
                )
           )

Note that this is not actually giving the DataFrame a name, it's just naming the variable. You could create another variable that holds a reference to data_out (a pointer) that would have a different name. This is true because data_out is a mutable object.
Series are named and its name is stored in the name attribute. DataFrames are not named, but their columns are, since they are Series.


text:
Q: ошибка скрипта активного пункта меню в мою версии как устранить ошибку на мобильном.
если в мобильной версии убрать $("ul li a.active").parents("ul").show(); то сайт работает, если этот кусок кода оставить то в моб версии не работает. Может как проверку сделать, если класс active у ul li a ?
вот скрипт
$(document).ready(function(){
  var vmenu = $('#menu > li.sub > .icon-angle-down');
  vmenu.on('click',function(){
  $(this).toggleClass('active');
  $('#menu li ul').slideUp();
   if ($(this).next().is(":visible")){
       $(this).next().slideUp();
   } else {
   $(this).next().slideToggle();
   }
  });

    $("ul li a.active").parents("ul").show();
});

A: if ( $(".vertical-menu ul li a").hasClass("active") ) {

$(".vertical-menu ul li a.active").parents("ul").show();
}

так вроде работает


text:
Q: How to Convert Rows into Columns using SQL Select Query? Master Table
Code   UserName

1      UserOne

2      UserTwo

3      UserThree

Details Table
Code  UserCode  ParamName  ParamValue

1  1  NameOne  ValueOne

1  1  NameTwo  ValueTwo

1  1  NameThree  ValueThree

and so on
The above is my Master and Details table. I wanna write a query which will convert the rows of details table into columns. The desired output is given below:
Code  UserCode  NameOne  NameTwo  NameThree     and so on

1  1  ValueOne  ValueTwo  ValueThree     and so on

How can I achieve this? Any suggestion will be great in advance.

A: This is a common problem, without know anyting about BDMS to use,  i suggest two low-level solution:

*

*adding column by JOIN

*adding column by subselect

Adding column by subselect consist in adding a subselect  to take  each dato do you need to traspose into  column.
Adding column by JOIN consist into add a left join to data (whit right data cut), ad expose field you need into columns.
These solution are each static and valid only if you have a fixed number of column to traspsose. A way to let that dinamy could be to intruduce a store procedure.

A: I hope the below query will help you achieve what you want
 SELECT DISTINCT
    (SELECT ParamValue FROM tblDetails WHERE ParamName ='TestOne' AND UserCode = tb.UserCode) AS TestOne,
    (SELECT ParamValue FROM tblDetails WHERE ParamName ='TestTwo' AND UserCode = tb.UserCode) AS TestTwo,
    (SELECT ParamValue FROM tblDetails WHERE ParamName ='TestThree' AND UserCode = tb.UserCode) AS TestThree
 FROM tblDetails tb

or you can use PIVOT if the ParamName can have many values which cannot be guaranteed in advance.

A: A few general / common strategies...
You can use a PIVOT query...
You can use a CASE (TSQL) or DECODE (PLSQL) type of statement...
SELECT
   ...
   CASE Parmname WHEN 'NameOne' THEN [ValueOne] ELSE '' END as NameOne,
   CASE Parmname WHEN 'NameTwo' THEN [ValueTwo] ELSE '' END as NameTwo
   ...

You can use DERIVED TABLES...
SELECT
   ...
   N1.Parmname,
   N2.Parmname,
   ...
FROM
   ...
   LEFT JOIN (SELECT * FROM tbl_Detail WHERE Parmname = 'NameOne') N1
   ON...
   LEFT JOIN (SELECT * FROM tbl_Detail WHERE Parmname = 'NameTwo') N2
   ...

...etcetera


text:
Q: ASP.Net Postback Broke After Changing Form Attribute I have an ASP.Net form which looks like the following when rendered (many lines of markup removed for brevity):
<form onsubmit="document.body.style.cursor='wait';showLoader();" action="mypage.aspx">
<!-- form elements and controls -->
<input type="submit" />
</form>

In mypage.aspx.cs's Page_Load I am doing:
if(Page.IsPostBack)
{
    Foo();
} else {
    Bar();
}
Quux();

Without modifying the HTML page using the Chrome Dev Tools, if I submit the form it executes Bar(). But If I removed or replaced the onsubmit attribute in the form with my own, ASP.Net thinks that the page is doing a post back and executes Foo().
I find this behavior weird because the inline JS code in onsubmit does not change anything related to the form submission. Its function is only to add a loading GIF while the form is reloading. Could there be something I am missing here?

A: Instead of adding a submit button, try adding a regular button, and call your gif functionality from it:
<input type="button" onclick="document.body.style.cursor='wait';showLoader();" value="Click Me" />

This will not post anything, which is what you want. <input type='submit'> will always cause a postback, unless you cancel it with JavaScript.
JSFiddle: http://jsfiddle.net/0gd8t7ew/


text:
Q: Image of a convergent sequence in an increasing function Suppose I have a function $f:[a,b) \to \mathbb{R}$ that is increasing on its domain and a sequence $a_n \subset [a,b)$ such that $a_n \to b$ and $f(a_n)\to l\in \mathbb{R}$.
How would I go about showing that $l=sup(im \ f)$?
Any hints would be well appreciated, not full answers.

A: Let $x_0 \in [a,b)$ be arbitrary. We can always pick $N$ s.t. $n > N \implies a_n \in (x_0,b) \implies f(a_n) \geq f(x_0)$.

A: For any $x\in [a,b)$, you have $a_n$ such that $x< a_n$, and hence $f(x) \le f(a_n) \le l$.


text:
Q: filling list / Array by loop I'm trying to add selected values from list box to array or list
and I'm getting a strange error
here is my code
private void button3_Click(object sender, EventArgs e)
        {
            List<string> _AttName = new List<string>();
            for (int _i = 0; _i < listBox1.SelectedItems.Count; _i++)
            {

                if (listBox1.SelectedItem != null)
                {
-> Failes here ->   _AttName.Add(listBox1.SelectedValue.ToString());
                    listBox1.SetSelected(listBox1.SelectedIndex, false);

                }
            }
        }

or
private void button3_Click(object sender, EventArgs e)
        {
            string[] _AttName = new string[listBox1.SelectedItems.Count];
            for (int _i = 0; _i < listBox1.SelectedItems.Count; _i++)
            {

                if (listBox1.SelectedItem != null)
                {
                    _AttName[_i] = listBox1.SelectedValue.ToString();
                    listBox1.SetSelected(listBox1.SelectedIndex, false);

                }
            }
        }

here is the error I get

A: Problem : you will get this error because while binding the Items into the ListBox you have only binded the DisplayMemeber but not ValueMember.
So you don't have any Value associated to the Items in the ListBox.
Solution : you can use SelectedItem property to get the Item.
Replace This:
_AttName.Add(listBox1.SelectedValue.ToString());

With This:
_AttName.Add(listBox1.SelectedItem.ToString());

A: Try this:
   if (listBox1.SelectedItem != null && listBox1.SelectedValue != null)
   {

         _AttName.Add(listBox1.SelectedValue.ToString());
         listBox1.SetSelected(listBox1.SelectedIndex, false);
   }

Other solution:(Instead of using ToString(), use Convert.ToString())
   if (listBox1.SelectedItem != null)
   {
         _AttName.Add(Convert.ToString(listBox1.SelectedValue)); // Convert.ToString() will handle the null.
         listBox1.SetSelected(listBox1.SelectedIndex, false);
   }


text:
Q: Computed column of type Date in sql I have parameters column in my db. It contains different params as varchar including "BestBeforeDate". Now I want to be able to filter the rows based on BestBeforeDate. I'm trying to create a computed column of type 'Date' and then index it. I do:

alter table stocklines add BestBeforeDate as CONVERT(date,
  JSON_VALUE(Parameters, '$.BestBeforeDate'), 112) persisted

and I'm getting an error: JSON text is not properly formatted. Unexpected character '.' is found at position 22. but I don't have any dots in my Best BeforeDate json property...
Table Design:

A: The problem was that one of my Properties columns containes an invalid Json: "{ Param4: "54"" and then no closing Square bracket... its interresting why the exception said '.' is unexpected character though. There are no any dots in Parameters column for every row...


text:
Q: Emoji to JSON encoded, post to web server Please help me with my problem in posting a JSON decoded emoji character.
I have a UITextView, this text view may have a emoji character. I am posting the data to a web server with the UITextView.text presented as JSON, the problem is when the text has a an emoji, I am not able to get the data. What I do is:
$postData = file_get_contents("php://input") to get the data.

then I use
$post = json_decode($postData,true);

to decode the data and have a assoc array and insert the data in database.
here is a code snippet when I insert my data into database.
$postData = file_get_contents("php://input");
//$postData = '{"body":"characters here ","subject":"subject here","username":"janus","from_id":"185","to_id":"62"}';
    $post = json_decode($postData,true);
        $data=array(
                'user_id_from'=>mysql_real_escape_string($post['from_id']),
                'user_id_to'=>mysql_real_escape_string($post['to_id']),
                'subject'=>mysql_real_escape_string($post['subject']),
                'message'=>mysql_real_escape_string($post['body']));

                $messages_obj->insert($data);

Without an emoji character found, it works fine. no problem. the problem is when an emoji character found, the data in $post (decoded data) is null.
I tried to use dummy data (line 2 in code snippet)
//$postData = '{"body":"characters here ","subject":"subject here","username":"janus","from_id":"185","to_id":"62"}';

and I succesfully inserted the emoji characters in database. I dont know why but It dont work the same when the data is from the device ($postData = file_get_contents("php://input"))
This is how I encode and post my data in client.
    NSMutableDictionary *messageDetails = [[NSMutableDictionary alloc] init];
[messageDetails setObject:[loginItems objectForKey:@"user_id"] forKey:@"from_id"];
[messageDetails setObject:recipientID forKey:@"to_id"];
[messageDetails setObject:@"subject here" forKey:@"subject"];
[messageDetails setObject:newMessageField.text forKey:@"body"];
    [messageDetails setObject:[loginItems objectForKey:@"username"] forKey:@"username"];

NSString *strPostData = [messageDetails JSONRepresentation];
[messageDetails release];

NSData *postData = [NSData dataWithBytes:[strPostData   UTF8String] length:[strPostData  length]];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:postData];

A: Once the data is sent to your php script you need to convert it to a multibyte string:
$content = mb_convert_encoding($content, 'UTF-8');

You can use this function:
function cb($content){

  if(!mb_check_encoding($content, 'UTF-8')
   OR !($content === mb_convert_encoding(mb_convert_encoding($content, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {

    $content = mb_convert_encoding($content, 'UTF-8');

  }
  return $content;
}

Edit: The data was probably of type application/x-www-form-urlencoded for us and that function converted it correctly.

A: emoji characters are most likely transcoded in UNICODE, so it should be sufficient to just send, receive and manage your data in UTF-8.
When receiving with this
$postData = file_get_contents("php://input")

(I suppose that is a real URL), make sure your php script sends an Content-Encoding header (like the following, choose a MIME-type that suits you)
 header("Content-Type: text/html; charset=utf-8");

A: Please follow following steps:

*

*Convert Emoji characters to base64 and send to server.

*On server side save base64 in database without decode.

*When you want to display Emoji on Application then retrieve same base64 data from server.

*Decode retrieve string and display on app.

*Your Emoji character will display properly.


text: Q: How to access a shared mailbox via Office365 Rest API? We can access the shared mailbox if it is shared with a user by using user's OAuth. Whereas here I want to access a shared mailbox which doesn't have a user via Office 365 Rest API. Is it possible via Rest API? or Can we achieve the same via EWS or Graph APIS?


text:
Q: BadImageFormatException - Merging C# Console project with C# Windows Form project I have a Console app that I am able to compile and run without issue using C# and .Net Core.  This code takes advantage of a DLL that's used to execute some API calls to another application.  I've been tasked with creating  Windows Form application that does the same operations, but when i use the same code and add it to my windows form project, I get an exception when I try to load it:  BadImageFormatException
I have no idea how to work around this or why it's coming up.  I've tried changing the CPU setting, but nothing works.  It's worth noting that the settings between the console and windows projects are the same regarding the CPU type.  One thing that is different is that when I compile the console App, a DLL is formed by the project.  This DLL is not created when I compile the Windows project.

A: Found that the issue was that the library was x64 and for teh console app, it doesn't matter how I compile it, but for the windows app, I had to set it to x64. I believed it to be a 32-bit since it was an old app, which is why I tried x86.


text:
Q: Handling files for multiple users at once (logistic prob) Hey my app creates files on server that are shown to users right away in html element called iframe.
So far I have been storing all files into same folder, overwriting old ones each time user requested new one. Problem is that if more than one user tried  to generate file at once, one of them might not get the right file, or no file at all. I guess i should create random temp folder for each generation of files. That would work, but my server might get filled up really quickly in like 100 generations of files. I need to delete this random temp folder once user is done loading up file in iframe, but how do I call php function on  load?
Any other alternative method/idea, would help me alot. How do others handle such problems?

A: I would create one single temp folder, and generate random file names (md5, GUID, don't matter).
The same script that generate the file on the folder to visualization, before the generation itself, should check all the files on the folder, excluding all the files which were generated >= 1 day ago.
Check the filemtime function and this question if you have any doubts about how to get the file creation/modification date.


text:
Q: How to change animated status bar value with same class but different part I do need for these status bars to work for each own. Maybe also the buttons could worked. I tried to acquire the value of "data-bar" without succeed (the script does still can process the "data-max"). And seems that the script does apply to all bars, not individually, while I need that it differs for each bar.

In html:

<button onclick="$('.stat-bar').attr('data-bar', '50');">Set Bar Value</button>

<button onclick="$('.stat-bar').attr('data-bar', '30');">Set Bar Value</button>

<button onclick="$('.stat-bar').attr('data-bar', '100');">Set Bar Value</button>

In script:

In css:

A: You can use each loop to iterate through your divs and get required values i.e : attributes then use $(this).find("someclass") to get reference of divs where you need to change widths and texts.
Demo Code :

$(document).ready(function() {
  $(".stat-bar").html(
    "

" +
    "

" +
    "

" +
    "

"
  );

  setInterval(function() {
    //loop through stat bar
    $(".stat-bar").each(function() {
      //get datas from divs
      var maxStat = parseInt($(this).attr("data-bar-max"));
      var currentStat = parseInt($(this).attr("data-bar"));
      //depend on value change currentstat
      currentStat > maxStat ? currentStat = maxStat : currentStat = currentStat;
      var a = currentStat * (100 / maxStat);
      //find statbartext inside div
      $(this).find(".stat-bar-text").html("" + currentStat + "" + "/" + "" + maxStat + "" + "  " + "" + "(" + Math.round(a) + "%" + ")" + "");

      ///same find and apply effect there
      $(this).find(".stat-bar-main-shade-min").animate({
        "width": a + "%"
      }, 800);
      $(this).find(".stat-bar-main-shade-plus").animate({
        "width": a + "%"
      }, 300);
      $(this).find(".stat-bar-main").animate({
        "width": a + "%"
      }, 700);
    })
  }, 2000); // END 2 second interval change

});
.stat-bar {
  background-color: #ACB597;
  height: 26px;
  width: 60vw;
  margin: 0 auto;
  overflow: hidden;
  border: solid 1px #686E59;
  border-radius: 4px;
  box-shadow: inset 0 0 0 0.5px #888E79;
}

.stat-bar-main {
  background-color: #464D51;
  height: 30px;
  width: inherit;
  bottom: 50px;
  position: relative;
}

.stat-bar-main-shade-min {
  height: 100%;
  width: 100%;
}

.stat-bar-main-shade-plus {
  height: 100%;
  width: 100%;
  bottom: 24px;
  position: relative;
}

.stat-bar-main-shade-min,
.stat-bar-main-shade-plus {
  background: linear-gradient(90deg, rgba(70, 77, 81, 1) 95%, rgba(70, 77, 81, 0) 100%);
  opacity: 0.35;
}

.stat-bar-text {
  color: rgba(255, 255, 255, 0.8);
  font: 400 10px "opensans";
  letter-spacing: 0.09em;
  line-height: 24px;
  height: 24px;
  bottom: 78px;
  position: relative;
  box-shadow: inset 0 0 5px transparent;
}

<button onclick="$('.stat-bar').attr('data-bar', '50');">Set Bar Value</button>

<button onclick="$('.stat-bar').attr('data-bar', '30');">Set Bar Value</button>

<button onclick="$('.stat-bar').attr('data-bar', '100');">Set Bar Value</button>


text:
Q: Add category to custom post type automatically, using category slug I'm using this excellent function to automatically add a category to my custom post type "Videos" on publish, if there's no category already chosen. This works great:
function add_video_category_automatically($post_ID) {
    global $wpdb;
    if(!has_term('','category',$post_ID)){
        $cat = array(394);
        wp_set_object_terms($post_ID, $cat, 'category');
    }
}
add_action('publish_videos', 'add_video_category_automatically');

But, I'd really like to get the category ID via the slug, so that I don't have to change it manually when I'm testing on localhost vs the live site (which may have a different ID for that category as localhost and the live site aren't in sync).
I've tried a number of options but all of them result in a category of "394" being assigned to new posts, rather than "Videos". Here's my latest attempt. Can you tell me where I'm going wrong?
function add_video_category_automatically($post_ID) {
    global $wpdb;
    if(!has_term('','category',$post_ID)){
        $category = get_term_by( 'slug', 'videos', 'category' );
        $cat = array($category->term_id);
        wp_set_object_terms($post_ID, $cat, 'category');
    }
}
add_action('publish_videos', 'add_video_category_automatically');

Thank you!

A: wp_set_object_terms Works better with term slug instead of term id so change this line:
$cat = array($category->term_id);

to:
 $cat = array($category->slug);


text:
Q: How does it know what's next in this linked list? I understand most of the code, but what I don't understand is what's happening in the append_after function. How exactly are the elements in the linked list being appended after each other?
As far as I can see last_node.next is never being instructed to point to the next element. Also it says "While last_node.next is not None" but isn't it None by default? I'm not seeing what would make it not "None" if I didn't specifically code it to do that.

class node:

    def __init__(self, data):

        self.data = data
        self.next = None

class linked_list:

    def __init__(self):

        self.head = None

    def display(self):

        node = self.head
        while node is not None:
            print(node.data)
            node = node.next

    def append_after(self, data):

        new_node = node(data)
        if self.head is None:
            self.head = new_node
            return

        last_node = self.head # I'm assuming this starts at the letter "A"?
        while last_node.next is not None: # What makes it not None?
            last_node = last_node.next
        last_node.next = new_node # It comes here after finishing the loop?

ll = linked_list()

ll.append_after("A")
ll.append_after("B")
ll.append_after("C")
ll.append_after("D")
ll.display()

OUTPUT

A
B
C
D

Below is a different way to call the objects. If I call the objects like I do in the example below I can easily understand it because I can clearly see what's being defined as the next element, but I don't understand how the append_after function returns the same result.
ll = linked_list()

ll.head = node("A")
data2 = node("B")
data3 = node("C")
data4 = node("D")

ll.head.next = data2
data2.next = data3
data3.next = data4
ll.display()

I'm using Python 3 and I've already looked at similar questions but they weren't explained very well. Is something happening under the hood that I don't understand?

A: It may help to visualise the process. When ll = linked_list() is executed, an instance of linked_list is created, its head attribute is set to None and the reference to that instance is assigned to ll. We can picture the state as follows:
 ll
  ↓
┌────────────┐
│ head: None │
└────────────┘

Now ll.append_after("A") is called. During this call self has the reference to the linked list, and with new_node = node("A") the new node is created with its data attribute set to "A" and its next attribute set to None. Let's already picture that state:
 self (ll)
  ↓
┌────────────┐
│ head: None │
└────────────┘

    ┌────────────┐
    │ data: "A"  │
    │ next: None │
    └────────────┘
      ↑
     new_node

Because self.head is None, we get into the if block, where self.head = new_node is executed. This makes the new node instance a member of the list:
 self (ll)
  ↓
┌────────────┐
│ head: ─┐   │
└────────│───┘
         ▼
    ┌────────────┐
    │ data: "A"  │
    │ next: None │
    └────────────┘
      ↑
     new_node

The append_after function returns, and the main program makes the call ll.append_after("B"). Again a new node is created with new_node = node("B"). This leads to this state:
 self (ll)
  ↓
┌────────────┐
│ head: ─┐   │
└────────│───┘
         ▼
    ┌────────────┐    ┌────────────┐
    │ data: "A"  │    │ data: "B"  │
    │ next: None │    │ next: None │
    └────────────┘    └────────────┘
                        ↑
                       new_node

This time the if condition (self.head is None) is not true, so we get to last_node = self.head, introducing another name that references the first node in the list:
 self (ll)
  ↓
┌────────────┐
│ head: ─┐   │
└────────│───┘
         ▼
    ┌────────────┐    ┌────────────┐
    │ data: "A"  │    │ data: "B"  │
    │ next: None │    │ next: None │
    └────────────┘    └────────────┘
      ↑                 ↑
     last_node         new_node

Now the while loop starts, but its condition is false, because last_node.next is None -- which is an indication that it currently is the last node in the list. And that's what we need: we want to have a reference to the last node in the list so we can attach the new node just after it.
After the while loop (which didn't make iterations) we execute last_node.next = new_node. This performs the attachment:
 self (ll)
  ↓
┌────────────┐
│ head: ─┐   │
└────────│───┘
         ▼
    ┌────────────┐    ┌────────────┐
    │ data: "A"  │    │ data: "B"  │
    │ next: ────────► │ next: None │
    └────────────┘    └────────────┘
      ↑                 ↑
     last_node         new_node

The function returns. Let's do one more call: ll.append_after("C"). Again a new node is created, the if condition is False, and last_node gets again a reference to the first node in the list. So just before the while loop starts we have this state:
 self (ll)
  ↓
┌────────────┐
│ head: ─┐   │
└────────│───┘
         ▼
    ┌────────────┐    ┌────────────┐    ┌────────────┐
    │ data: "A"  │    │ data: "B"  │    │ data: "C"  │
    │ next: ────────► │ next: None │    │ next: None │
    └────────────┘    └────────────┘    └────────────┘
      ↑                                   ↑
     last_node                           new_node

This time the while condition is true, which means that last_node is not what its name suggest -- it is not the last node in the list, so an iteration of the loop is executed, with last_node = last_node.next:
 self (ll)
  ↓
┌────────────┐
│ head: ─┐   │
└────────│───┘
         ▼
    ┌────────────┐    ┌────────────┐    ┌────────────┐
    │ data: "A"  │    │ data: "B"  │    │ data: "C"  │
    │ next: ────────► │ next: None │    │ next: None │
    └────────────┘    └────────────┘    └────────────┘
                        ↑                 ↑
                       last_node         new_node

Now the while condition is true, which means that last_node is truly the last node of the list. It is here that we need to attach the new node. So after last_node.next = new_node is executed, we get:
 self (ll)
  ↓
┌────────────┐
│ head: ─┐   │
└────────│───┘
         ▼
    ┌────────────┐    ┌────────────┐    ┌────────────┐
    │ data: "A"  │    │ data: "B"  │    │ data: "C"  │
    │ next: ────────► │ next: ────────► │ next: None │
    └────────────┘    └────────────┘    └────────────┘
                        ↑                 ↑
                       last_node         new_node

The call ll.append_after("D") will go through the same process: last_node will start again from the left, and via the loop it will reach the last node in the list, and then the new node will be appended there.
I hope this clarifies it.


text:
Q: Issue with number values importing csv files in R As usually, I am importing a .csv file from Excel. Since I will be performing some econometric regressions, I m not importing just the values, but also some columns with labels.
df <- read.csv("peasantsworkalot.csv", header=TRUE)

where the df looks like the following
country <- c("AT", "AT", "AT", "AT")
code <- c("AT1", "AT1", "AT2", "AT2")
c <- c("Village1", "Village1", "Village2", "Village2")
d <- c("Year1", "Year1", "Year2", "Year2")
e <- c(65322.09, 62322.01, 84561.06, 86000.02)
df <- cbind(country,code,c,d,e)
df

[1,] "AT" "AT1" "Village1" "Year1" "65322.09"
[2,] "AT" "AT1" "Village1" "Year1" "62322.01"
[3,] "AT" "AT2" "Village2" "Year2" "84561.06"
[4,] "AT" "AT2" "Village2" "Year2" "86000.02"

Whenever I try to make any kind of operation with the values in the e column, I got the following message:
[1] NA
Warning message:
In Ops.factor( ):
  + not meaningful for factors

I suppose that, for somewhat reason it reads the values as non numeric. Therefore I tried
as.numeric(df)

or
as.numeric(df[,5])

The first does not work and gives

Error: (list) object cannot be coerced to type 'double'

The second works but it changes the values. For instance 65322.09 becomes 259 , I don't know for whatever reason.
First time this happens and not for any .csv files. Some just work fine.

A: In your read.csv function include this read.csv("readThis.csv", stringsAsFactors=FALSE).  Also read the information in the comments.  You definitely should work up your knowledge stat.

A: To convert a column to numeric you can run:
df[,5] <- as.numeric(df[,5])

However, if that column is a factor, it will lead to undesired results (see help("factor")). So if it's a factor column, the most straightforward approach is to convert it to character first, then to numeric:
df[,5] <- as.numeric(as.character(df[,5]))

A: If the .csv file contains NA, as for instance in the form  ..., the read.csv function must include read.csv("readThis.csv", na.string="..."). This will preserve the numeric values in the .csv file. Otherwise, they will be switched to non numeric.


text:
Q: trying to make a schema I have a schema of a (course) which is this:
  targetNamespace="http://www.nova.edu/course"
  xmlns="http://www.nova.edu/course"
  xmlns:ins="http://www.nova.edu/instructor"
  xmlns:mat="http://www.nova.edu/materials"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  >
  <xs:import schemaLocation="InstructorSchema.xsd" namespace="http://www.nova.edu/instructor" />
  <xs:import schemaLocation="MaterialsSchema.xsd" namespace="http://www.nova.edu/materials" />

  <xs:element name="course">
    <xs:complexType>
      <xs:sequence>
        <xs:element type="xs:string" name="title"/>
        <xs:element type="xs:string" name="program"/>
        <xs:element type="xs:short" name="number"/>
        <xs:element name="term">
          <xs:complexType>
            <xs:sequence>
              <xs:element type="xs:int" name="crn"/>
              <xs:element type="xs:int" name="code"/>
              <xs:element type="xs:string" name="name"/>
              <xs:element type="xs:short" name="year"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="schedule">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="dates">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element type="xs:date" name="startdate"/>
                    <xs:element type="xs:date" name="enddate"/>
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
              <xs:element type="xs:string" name="day"/>
              <xs:element name="time">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element type="xs:string" name="starttime"/>
                    <xs:element type="xs:string" name="endtime"/>
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="location">
          <xs:complexType>
            <xs:sequence>
              <xs:element type="xs:string" name="building"/>
              <xs:element type="xs:short" name="room"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element ref="ins:instructor" />
        <xs:element ref="mat:materials" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

now am trying to Create a new schema that defines a Courses element that is a collection of zero or more (course) elements.
targetNamespace="http://www.nova.edu/allcourses"
  xmlns="http://www.nova.edu/allcourses"
  xmlns:cor="http://www.nova.edu/course"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  >
    <xs:import schemaLocation="CourseSchema.xsd" namespace="http://www.nova.edu/course" />

     <xs:element name="courses">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="course" minOccurs="0" maxOccurs="unbounded">
                <xs:complexType>
                    <xs:sequence>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
</xs:element>
</xs:schema>

am not sure if I should add more elements in my new schema in order for it to work well. The idea is just to be able have multiple courses and each course is based on the (course)schema above.

A: In your courses element, use
<xs:element ref="course" minOccurs="0" maxOccurs="unbounded"/>

to refer to the existing declaration of element course, rather than redefining it locally.


text:
Q: AWS S3: General practice on limiting users access to only their folders? I'm creating an application where users will have a private photo album. I am using S3 for storing these photos.
All the photos will live under the same bucket, but in different subfolders that will be named something like {userId}/pics
My question is: Is it normal / accepted to just open up read access of this bucket to the public using the bucket policy? Or should I be limiting access to the folders so that only the user with userId can read from it so random people can't just guess the URL and view the pictures (unlikely, but possible)?

A: Users of your application will need to authenticate with application credentials (eg from Amazon Cognito or your own database), not IAM credentials. Never provide IAM credentials to anybody outside of your organization, or perhaps close working partners. Therefore, you will not be able to create a policy that lets specific users access a folder.
Security through obscurity is never a good idea. You might think that using a random URL makes things secure, but if the URL gets out "in the wild", anyone on the Internet can access it. Plus, it is still guessable.
Also, your security model does not fit a situation where users might want to share photos with other users, or provide non-users with access to a specific photo (like sharing a link from Dropbox).
The better security model would be:

*

*All photos are kept private

*Users authenticate to the application

*When a user requests access to a photo, the application confirms that they are authorized to access the photo and then generates a Pre-signed URL to the photo

Pre-Signed URLs are time-limited URLs that grant access to an object for a defined duration. Once the expiry period passes, the URL will no longer provide access.
For example, when a user wishes to view their private photos, the application can generate <img /> tags with a pre-signed URL. The user will see their images as normal, but nobody else will be able to access the photos. Even if somebody gets hold of the URL, it will no longer work after the expiry period.
See: Share an Object with Others - Amazon S3


text:
Q: A generic testdata builder -- does it obscure the beauty of the pattern? I have made a generic databuilder for unit test, because I got tired of implementing constructors and Build methods again and again. Does this obscure the beauty of the pattern (that I really DO love)?
Here is my generic builder (built in C# with Moq):
public class GenericMockBuilder<T> where T: class
{
    private readonly Mock<T> _objectMock = new Mock<T>();

    protected Mock<T> ObjectMock
    {
        get { return _objectMock; }
    }

    public T Build()
    {
        return _objectMock.Object;
    }
}

And here is an example interface and its concrete builder that inherrits the generic one:
public interface IFoo
{
    int Bar();
}

public class FooBuilder: GenericMockBuilder<IFoo>
{
    public FooBuilder WithBar(int barValue)
    {
        base.ObjectMock.Setup(x => x.Bar()).Returns(barValue);
        return this;
    }

}

The builder will construct a foo mock like this:
        IFoo fooMock = new FooBuilder().WithBar(12).Build();

I would love to hear oppinions and suggestions for improvement.
EDIT (Eventraising example added):
public class FooBuilderWithEvent: GenericMockBuilder<IFoo>
{

    public FooBuilderWithEvent RaiseEvent(FooEventArgs fooEventArgs)
    {
        base.ObjectMock.Raise(m => m.FooEvent += null, fooEventArgs);
        return this;
    }

}

Building Mock and raising event would look like this:
        FooBuilderWithEvent fooBuilderWithEvent = new FooBuilderWithEvent();
        IFoo fooMock = fooBuilderWithEvent.Build();

        //Create testobject and prepare for event here

        fooBuilderWithEvent.RaiseEvent(new FooEventArgs());

A: pros

*

*Nice domain-specific fluent interface

cons

*

*Another interface, which nobody familiar with (me, and I think many other developers do not see anything complex on mock setup with standard fluent interface of Moq)

*Creating builder class for each mocked interface (yes, you can create builders only for complex mocks, but using of two different mocking interfaces could confuse developers)

*Creating setup method for each mocked member

Don't know why you are asking for Moq sample, because you already have all this code inside builder:
var mock = new Mock<IFoo>();
mock.Setup(foo => foo.Bar()).Returns(42);

If lambdas and mock.Object calls are confusing to you, try RhinoMocks:
Exect.Call(foo.Bar()).Return(42);

Also I have a question - how are you going to raise events with only mocked object instance?

A: Having to build a facade over the mocking framework indicates that it's not right for you. Why not try another one. I personally have switched from Moq to NSubstitute:
Your own example:
IFoo fooMock = Substitute.For<IFoo>();
fooMock.WithBar(12).Returns(10);

Or if you only want to check that the method is called:
//arrange
IFoo fooMock = Substitute.For<IFoo>();

//act
fooMock.WithBar(12);

//assert
fooMock.Received().WithBar(12);


text:
Q: Facebook SDK Login $helper->getSessionFromRedirect() always NULL I still learning about this SDK Login.
I use code from here (the solution).
Already try different source and still got same problem.
PHP :

// added in v4.0.0
require_once( 'Facebook/FacebookSession.php' );
require_once( 'Facebook/FacebookRedirectLoginHelper.php' );
require_once( 'Facebook/FacebookRequest.php' );
require_once( 'Facebook/FacebookResponse.php' );
require_once( 'Facebook/FacebookSDKException.php' );
require_once( 'Facebook/FacebookRequestException.php' );
require_once( 'Facebook/FacebookOtherException.php' );
require_once( 'Facebook/FacebookAuthorizationException.php' );
require_once( 'Facebook/GraphObject.php' );
require_once( 'Facebook/GraphSessionInfo.php' );

// added in v4.0.5
use Facebook\FacebookHttpable;
use Facebook\FacebookCurl;
use Facebook\FacebookCurlHttpClient;

// added in v4.0.0
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookOtherException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphSessionInfo;

// start session
session_start();

// init app with app id and secret
FacebookSession::setDefaultApplication( 'xxxxxxxxxxxxxxxxxx','xxxxxxxxxxxxxxxxx' );

// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( 'http://os.topclass.com/' );

// see if a existing session exists
if ( isset( $_SESSION ) && isset( $_SESSION['fb_token'] ) ) {
  // create new session from saved access_token
  $session = new FacebookSession( $_SESSION['fb_token'] );

  // validate the access_token to make sure it's still valid
  try {
    if ( !$session->validate() ) {
      $session = null;
    }
  } catch ( Exception $e ) {
    // catch any exceptions
    $session = null;
  }

} else {
  // no session exists

  try {
    $session = $helper->getSessionFromRedirect();
  } catch( FacebookRequestException $ex ) {
    // When Facebook returns an error
  } catch( Exception $ex ) {
    // When validation fails or other local issues
    echo $ex->message;
  }

}

// see if we have a session
if ( isset( $session ) ) {
    var_dump($session);exit;
  // save the session
  $_SESSION['fb_token'] = $session->getToken();
  // create a session using saved token or the new one we generated at login
  $session = new FacebookSession( $session->getToken() );

  // graph api request for user data
  $request = new FacebookRequest( $session, 'GET', '/me' );
  $response = $request->execute();
  // get response
  $graphObject = $response->getGraphObject()->asArray();

  // print profile data
  echo '
' . print_r( $graphObject, 1 ) . '
';

  // print logout url using session and redirect_uri (logout.php page should destroy the session)
  echo 'getLogoutUrl( $session, 'http://os.topclass.com/logout/' ) . '">Logout';

} else {
  // show login url
  echo 'getLoginUrl( array( 'email', 'user_friends' ) ) . '">Login';
  var_dump($session);exit;
}

Problem :
the session always NULL i already try login fb and var_dump($session);but result is NULL
I sure app id and secret already correct.
in developer fb
App domain : os.topclass.com
Site UrL : http://os.topclass.com/
Where i did mistake? please need help.
UPDATE PROBLEM :
 $session = $helper->getSessionFromRedirect(); --> this alwys return NULL


text:
Q: use mathsf as default mathfont Using \mathsf explicitly inside math environment, I can have mathsf (Roboto light condensed in this case) as a math font. I am looking for a way to get this as default, so that, I don't need to put \mathsf in each math environment.
\documentclass[10pt]{standalone}
\usepackage[light,condensed]{roboto}
\begin{document}
Without Mathsf $C_6H_6$\\

With Mathsf  $\mathsf{C_6H_6}$
\end{document}

A: Is this helpful?
\documentclass[10pt]{book}
\usepackage[light,condensed,sfdefault]{roboto}
\usepackage[italic]{mathastext}

\begin{document}
Without Mathsf $C_6H_6$\\

With Mathsf  $C_6H_6$
\end{document}


text:
Q: Magento 2 replace a core javascript I was trying to replace magento 2 core javascript file for Swatches render which is located at app/code/Magento/Swatches/view/frontend/web/js/SwatchRenderer.js . And I followed official guide for this - http://devdocs.magento.com/guides/v2.0/javascript-dev-guide/javascript/custom_js.html , but it did not work.
I have uploaded my module on GIT. Can someone check and tell me what is the issue ? Here is the GIT Link for the module created - https://github.com/chamalC/magento-2-replace-javascript/tree/master/app/code/Muaw/CustomSwatches

A: Try below code in your requirejs-config.js
 var config = {
     map: {
    '*': {
        swatchRenderer: 'Muaw_CustomSwatches/js/SwatchRenderer'
    }
}};

A: The code works for me on Magento 2.1.5
var config = {
    map: {
        '*': {
           'Magento_Swatches/js/swatch-renderer':'Vendor_Module/js/swatch-renderer'
        }
    }
};

A: There is an Easy way out for that when you do that changes while creating a custom Theme,
Firstly override the template File in which the Js is being called i.e
module-swatches/view/frontend/templates/product/view/renderer.phtml
and change the line
"Magento_Swatches/js/swatch-renderer"

to
"Magento_Swatches/js/swatch-renderer-custom"
Secondly create a js file in web/js Directory named swatch-renderer-custom.js
Then if you apply any code in that js file then your code will be called....

A: Try below based on docs of magento 2 inside requirejs-config.js file,
You have to do below,
var config = {
    map: {
        '*': {
            swatchRenderer:'Magento_Swatches/js/SwatchRenderer'
        }
    }
};

A: Using Mixins:
var config = {
    config: {
        mixins: {
            'Magento_Swatches/js/swatch-renderer': {
                'Ayasoftware_EnhancedConfigurable/js/swatches': true
            }
        }
    },
    }
};


text:
Q: Change URL of Umbraco homePage I am using Umbraco with my current website so two folders in IIS one for my current website and one for Umbraco as Umbraco homepage is serving blog in my website but the URL is mywebsite.com/homepage. How can I can I change URL to mywebsite.com/blog
I tried to change Name and Alias property under templates.
But it is not changing the URL.

A: Sounds to me your iis application is bound to "mywebsite.com/homepage" instead of "mywebsite.com/blog". Can you check this? Also you can check the hostname that Umbraco is bound to (right mouse on rootnode and select Hostnames).


text:
Q: Overriding HashMap equals method in Java I noticed in the source code for HashMap it lists the equals method as final. Why is it that when I override it  I do not get a compile error?
public class Test extends HashMap<Object, Object> {

    @Override
    public boolean equals(Object o) {
        return false;
    }
}

Java HashMap equals method:
public final boolean equals(Object o) {
    if (!(o instanceof Map.Entry))
        return false;
    Map.Entry e = (Map.Entry)o;
    Object k1 = getKey();
    Object k2 = e.getKey();
    if (k1 == k2 || (k1 != null && k1.equals(k2))) {
        Object v1 = getValue();
        Object v2 = e.getValue();
        if (v1 == v2 || (v1 != null && v1.equals(v2)))
            return true;
    }
    return false;
}

A: That's the equals method for HashMap.Entry, not HashMap itself - look at how it's trying to use the reference passed into it as a Map.Entry.


text:
Q: Problems when using variables with awk in shell scripts I am trying to code the simple shell scripts in a automatic way.
Parsing my string and concatenating the parsed string into original file context.
However, when I did it by using awk command, it didn't work although I identified the string I looked for was parsed well.
Below is my code.
for file in ./*.txt
do
    fileName="$( string $file | rev | cut -d. -f2 | rev)"
    echo $fileName
    awk '{print($2"\t"$3"\t"$4"\t""0""\t""0""\t"$5"\t"$6"\t"$7"\t"$8"\t"$fileName)}' $file
done

Can you give some tips?

A: Pretty sure you are just trying to reference the shell variable $filename.  One choice is to change quote styles (begin with single quotes, and end with double quotes) and use:
awk '{print $2, $3, $4, "0", "0", $5, $6, $7, $8, "'"$fileName\" }" OFS=\\t $file

You need to have double quotes around $fileName so that the shell interpolates it as a variable.  You can use double quotes on the whole thing and write awk "{print \$2, ... as well.  There a many ways to do the necessary quoting, but it is far more readable to pass the shell variable in as an awk variable:
awk '{print $2, $3, $4, "0", "0", $5, $6, $7, $8, f }' OFS=\\t f="$fileName" $file


text:
Q: Pass pipe output directly to purrr map function This question is in line with my previous question here. However, I try to combine the output of the pipe call with purrr's map function into a single pipeline. For example:
library(tidyverse)
library(purrr)

my_tbl <- tibble(a = rep(c(0, 1), each = 5),
             b = rep(c(0, 1), times = 5),
             c = runif(10),
             d = rexp(10)) %>%
    mutate_at(vars(1,2), as.factor)

map(names(my_tbl)[-1], ~glm(reformulate(.x, "a"), data = my_tbl, family = "binomial")) %>% summary()

I tried with
my_tbl <- tibble(a = rep(c(0, 1), each = 5),
             b = rep(c(0, 1), times = 5),
             c = runif(10),
             d = rexp(10)) %>%
    mutate_at(vars(1,2), as.factor) %>%
    {map(names(.)[-1], ~glm(reformulate(.x, "a"), data = ., family = "binomial")) %>% summary()}

but I got:
Error in eval(predvars, data, env) :
  invalid 'envir' argument of type 'character'

A: You do not need purrr in this case:
custom_fun <- function(x) {
  glm(reformulate(names(x)[-1], "a"), data = x, family = "binomial") %>%
    summary
}

my_tbl <- tibble(a = rep(c(0, 1), each = 5),
                 b = rep(c(0, 1), times = 5),
                 c = runif(10),
                 d = rexp(10)) %>%
  mutate_at(vars(1,2), as.factor) %>%
  custom_fun()

You could use purrr with the following:
my_tbl <- tibble(a = rep(c(0, 1), each = 5),
                 b = rep(c(0, 1), times = 5),
                 c = runif(10),
                 d = rexp(10)) %>%
  mutate_at(vars(1,2), as.factor) %>%
  nest(data = everything()) %>%
  mutate(res = map(data, custom_fun))


text: Q: Multidimensional array and memory usage I am working on building a class that holds a collection of objects in a grid that can be either 2D or 3D.  I am using multidimensional arrays as the collection of objects will not change size once initialized.  Currently, I am declaring the 2D arrays as: myArray[x][y][1].  This allows the same functions to work independent of the actual dimensions of my collection.  Is there a major difference in the amount of memory allocated this way over myArray[x][y]?  I am working on this in Java but I have been considering switching over to C++ once I get the logic working the way I want.


text:
Q: removing same fetched data php <?php
$con = mysqli_connect("localhost","root","","final_osa");
$s_stud = $con->query("SELECT * FROM violations_tbl GROUP BY violation_type");
while($data = $s_stud->fetch_assoc() ){
    $bilang = $con->query("SELECT COUNT(*) FROM violations_tbl WHERE `violation_type` ='".$data['violation_type']."' ");
    $result = $bilang->fetch_assoc();
    if($result['COUNT(*)'] > 1 ){
        echo "
";
            echo "";
                $query=$con->query("SELECT `violation_type` FROM `violations_tbl` WHERE `violation_type`='".$data['violation_type']."'");
                while($row=$query->fetch_assoc() ){
                    echo $row['violation_type'].", ";
                }
                echo "	";
                echo "
";
    }
}
?>

How can i eliminate same fetched data and echo only one? thanks
here is the one that it echoes. it should be that it will echo only one because its the same
What i'm trying to do here is get the mos violated rule in school thanks

A: If you want all the violations in order of most violated to least violated
$s_stud = $con->query("SELECT violation_type, count(violation_type) as num_violations
                      FROM violations_tbl
                      GROUP BY violation_type
                      ORDER BY num_violations DESC");

while($row= $s_stud->fetch_assoc() ){
    //echo the violation and the count
    if($row['num_violations'] > 1 ){
        echo "
";
        echo "$row[violation_type]	";
        echo "$row[num_violations]	";
        echo "
";
    }
}

If you only want the MOST violated you could add a LIMIT 1 to the query and remove the looping.
$s_stud = $con->query("SELECT violation_type, count(violation_type) as num_violations
                      FROM violations_tbl
                      GROUP BY violation_type
                      ORDER BY num_violations DESC
                      LIMIT 1");

$row= $s_stud->fetch_assoc();
//echo the violation and the count
echo "
";
echo "$row[violation_type]	";
echo "$row[num_violations]	";
echo "
";


text:
Q: How to use DatePicker widget in android? enter code hereI have used the DatePicker widget in android.Upon clicking that I want the datePickerdialog to show up and date should be set and the same I want to set to a textview.
Thanks in advance.
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);

DatePickerDialog dpd = new DatePickerDialog(this,new   DatePickerDialog.OnDateSetListener() {
        @Override
        // TODO Auto-generated method stub
public void onDateSet(DatePicker view, int year,int monthOfYear, int dayOfMonth) {
                      startDateTextView.setVisibility(View.VISIBLE);
startDateTextView.setText(dayOfMonth + "-"+ (monthOfYear + 1) + "-" + year);
}
}, year, month, day);
dpd.show();

the above code i used,bt this works before i click on datepicker. please let me know how to use OnClickListener of datepicker to this

A: Try below code.
package com.example.datetimepicker;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;

import java.text.DateFormat;
import java.util.Calendar;

public class MainActivity extends Activity {

    Button date,time;
    TextView preview;
    int year,monthofyear,dayofmonth,hourofday,minute;
    Calendar cal = Calendar.getInstance();
    DateFormat dt = DateFormat.getInstance();

    TimePickerDialog.OnTimeSetListener tpd;
    DatePickerDialog.OnDateSetListener dpd;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        date = (Button)findViewById(R.id.date);
        date.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                new DatePickerDialog(MainActivity.this,dpd,
                        cal.get(Calendar.YEAR),cal.get(Calendar.MONTH),
                        cal.get(Calendar.DAY_OF_MONTH)).show();

            }
        });
        time = (Button)findViewById(R.id.time);
        time.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new TimePickerDialog(MainActivity.this,tpd,
                        cal.get(Calendar.HOUR_OF_DAY),cal.get(Calendar.MINUTE),
                        false).show();
            }
        });
        preview = (TextView)findViewById(R.id.textView1);

        dpd = new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                    int dayOfMonth) {
                // TODO Auto-generated method stub
                cal.set(Calendar.YEAR, year);
                cal.set(Calendar.MONTH, monthOfYear);
                cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);

                preview.setText(new StringBuilder().append(year+"/")
                        .append(monthOfYear+"/").append(dayOfMonth));
            }
        };

        tpd = new TimePickerDialog.OnTimeSetListener() {

            @Override
            public void onTimeSet(TimePicker arg0, int hourofday, int minute) {
                // TODO Auto-generated method stub
                cal.set(Calendar.HOUR_OF_DAY, hourofday);
                cal.set(Calendar.MINUTE, minute);

                preview.setText(new StringBuilder().append(hourofday+"/")
                        .append(minute));
            }
        };
    }
}

A: you can use like this:
//variables
DatePicker dpResult;
static final int DATE_DIALOG_ID = 999;

//methods
public void setCurrentDateOnView() {

        dpResult = (DatePicker) findViewById(R.id.dpResult);
        dpResult.setVisibility(View.GONE );
        final Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        day = c.get(Calendar.DAY_OF_MONTH);

        // set current date into datepicker
        dpResult.init(year-7, month, day, null);

    }

@Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            // set date picker as current date
            return new DatePickerDialog(this, datePickerListener, year, month,
                    day);
        }
        return null;
    }

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

        // when dialog box is closed, below method will be called.
        public void onDateSet(DatePicker view, int selectedYear,
                int selectedMonth, int selectedDay) {
            year = selectedYear;
            month = selectedMonth;
            day = selectedDay;

            // set selected date into textview
            mbirthdayView.setText(  (day)+(".")+(month + 1)+(".")+(year));

            // set selected date into datepicker also
            dpResult.init(year, month, day, null);

        }
    };

and finally you can call datepicker like this:
showDialog(DATE_DIALOG_ID);


text:
Q: How to specify the fields I want with my facets I'm using elasticJS and I want to get min/max values using facets : "StatisticalFacet".
// javascript
var client = ejs.Request().indices('index').types('types');
client.query(ejs.MatchQuery('field', 'test');
client.facet(ejs.StatisticalFacet('exemple').field('field').doSearch();

I want to know how to specify to the facet that I only want the min and max results, so I can save time during the request.
EDIT: Apparently, There's no option to do that yet.
Thanks.

A: Documentation for the elastic.js Statistical Facet can be found at elastic.js: Module: StatisticalFacet I did not see where you can specify to limit the results of the statistical facet to only the min and max results in this documentation or in the Statistical Facet documentation for elasticsearch itself either,


text:
Q: ReactJS: how listen that child component updates? I'm using a 3rd-party component in my application. And I want to perform some actions in the parent component when it's child component updates (i.e. fires componentDidUpdate) but it turns out parent component's componentDidUpdate doesn't fire when the child updates internally.
Is there anyway to listen from the parent that the child component has updated? Assuming that I can't modify the child component code.

A:
Is there any way to listen from the parent that the child component has updated?

The answer is: there is no way.
However, we absolutely could implement that functionality by leveraging componentDidUpdate() method of the child component.
We pass down a callback function as a prop from the parent component to the child component. Then whenever the child component has updated, we will invoke that callback function in the componentDidUpdate() method of the child component. In this way, the parent can listen when the child component has updated.


text:
Q: Algorithm to search very long blacklist in another very long data set I have two data sets. The first data set has approx. 50.000 movie and song titles and the second one have 20.000 blacklist strings. I am looking for the best algorithm to detect movie/song title which contains blacklisted word(s).
Example:
Dataset #1
The Lord Of The Rings
E.T.
Star Wars
...
(50k items)

Blacklist Data set
Lord
Home Alone
Matrix
ar
...
(20k items)

Items in these data sets may be a character or a few words. String search algorithms like Boyer-Moore is not helping me with this since I have more than 1 needle to search in the haystack. I (probably) need to find an algorithm to find all combinations efficiently and later make a string search (regex maybe?) for each combination.