text:
Q: SerializationFailure error while posting data with Alamofire I am trying to save some text data and an image to server using Alamofire but I am getting following error:

FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))

My Code:
internal func postContent(forApi Name:String, image:UIImage?, withData payload:[String: String], success: ((_ response:[String: AnyObject])->Void)?, failure: ((Error)->Void)?) {
    //create Alamofire request
    //if everything was fine call success block with people array passed into it
    //if failure occurred, call failure block with error.
    if(isConnectedToNetwork()){
        let url = SharedConstants.baseURL+Name
        print("url "+SharedConstants.baseURL+Name)

        Alamofire.upload(multipartFormData: { (multipartFormData) in
            if let img = image {
                multipartFormData.append(UIImageJPEGRepresentation(img, 0.5)!, withName: "photo_path", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
            }

            for (key, value) in payload {
                multipartFormData.append(value.data(using: .utf8)!, withName: key)
            }
        }, to: url, method: .post , headers:nil, encodingCompletion: { (result) in
            switch result {
            case .success(let upload, _, _):

                upload.responseJSON(completionHandler: { (response) in
                    print(response.request)  // original URL request
                    print(response.response) // URL response
                    print(response.data)     // server data
                    print(response.result)   // result of response serialization

                    if let JSON = response.result.value {
                        print(JSON)
                        success!(JSON as! [String: AnyObject])
                    }
                    else{
                        failure!(ErrorType.noRecordFound)
                    }
                })
            case .failure(let error):
                print(error)
            }
        })
    }
    else{
        failure!(ErrorType.internetNotWorking)
    }
}

Thanks in advance

A: The iOS code is correct, there was problem in backend code. The json was not being properly formed. I corrected the json formation in backend and it started working fine.

A: let headers:HTTPHeaders = ["Authorization": "Bearer " + token2Save]
let moreheaders:Parameters = ["Dropbox-API-Arg": ["path":sourcePath]]

Alamofire.request("https://content.dropboxapi.com/2/files/download", parameters: moreheaders, encoding: URLEncoding(destination: .queryString), headers: headers).responseJSON { feedback in
        guard feedback.result.value != nil else {
            print("Error: did not receive data", print("request \(request) feedback \(feedback)"))
            return

URLEncoding(destination: .queryString), headers: headers).responseJSON
Replace responseJSON with responseString and check your response  from webservice.. it will lead to get the error line.

Refer:
https://stackoverflow.com/a/43041931/5215474

Replace responseJSON with responseString and check your response  from
  webservice.. it will lead to get the error line.

A: FrontEnd send parameters:
 {
"delivery_method": [{
    "vehicle_type": "walk",
    "vehicle_id": "1",
    "vehicle_color": "",
    "vehicle_brand": "",
    "vehicle_image": "",
    "vehicle_number": "",
    "mode_type": "1",
    "vehicle_model": ""
}, {
    "vehicle_type": "scooter",
    "vehicle_id": "4",
    "vehicle_color": "",
    "vehicle_brand": "",
    "vehicle_image": "",
    "vehicle_number": "",
    "mode_type": "1",
    "vehicle_model": ""
}]
}

When I parse JSON like this JSON.parse(params[:delivery_method]) throw error. So we can create a parameter to json.
data=JSON.parse(params[:delivery_method].to_json) # no exception.

A: Check the path in the url may be you are missing some folder.


text:
Q: Groovy download files I just had a quick question about downloading files. I was reading this page:
http://groovy.codehaus.org/Simple+file+download+from+URL
Can someone explain what the difference is between the two ways explained on that page? (Aside from overriding the leftshift operator) Is there any significance for doing it one way or the other?

A: The former method is far cleaner and is what you would do in most cases.
The second is effectively enhancing the File object within the use closure. I can't see where it would be useful in this context, but say in your code you were often putting content from urls into files, or you had a dsl where you wanted to allow for that functionality, you could use categories to extend the file object.
Personally, I see the example as really just showing (a rather impractical) use for categories.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a non-convex domain for which this function is not injective? I am asked to prove the following: Let $\Omega\subseteq\mathbb C$ a convex open subset and let $f$ be a holomorphic function in $\Omega$ such that $|f'(z)-1|<1$ for all $z\in\Omega$. Then $f$ is injective.
I proved this result, but then, I am asked to give a counterexample of a holomorphic $f$ in a non-convex connected open subset $\Omega\subseteq\mathbb C$ such that $|f'(z)-1|<1$ for all $z\in\Omega$ but $f$ is not injective.
I tried to think of $f$ in a way that involves the logarithm function, since the discontinuity of the argument may result in $f$ not being injective. I thought about the function $f(z)=\log(z)+z$, fixing the argument in $[-\pi,\pi]$. We have
$$ |f'(z)-1|=|1/z+1-1|=|1/z|<1\iff |z|>1.$$
So we may choose $\Omega=\{z\in\mathbb C\,\colon |z|>1\}$. This set is open, not convex and connected. The problem is I don't know how to check that $f$ is not injective in $\Omega$; in other words, how to determine the points $z_1,z_2\in\Omega$ such that $f(z_1)=f(z_2)$. I would be very glad if someone can help me with that. Thank you.

A: Let's consider $f(z)=z^{3/2}$ where $z \notin (-\infty,0]$ defined as usual by the principal branch of the logarithm so in particular if $z=re^{i\theta}, |\theta| < \pi, r>0$ then $f(z)=r^{3/2}e^{3i\theta/2}$. Clearly $f(re^{2\pi i/3})=r^{3/2}e^{\pi i}=-r^{3/2}=f(re^{-2\pi i/3})$ for any $r>0$.
Now $f'(z)=\frac{3z^{1/2}}{2}$ and we notice that $|a-1|<1$ is equivalent to $2\Re a >|a|^2$ so using that $2\Re f'(z)=3\sqrt r \cos (\theta/2)$ and $|f'(z)|^2=9r/4$ we get that $|f'(z)-1|<1$ is satisfied as long as $\cos (\theta/2) >3\sqrt r /4$  so if we consider the domain $D$ given by $|\theta| < 3\pi/4, 0<r<(\frac{4 \cos 3\pi/8}{3})^2$ we satisfy the relation $|f'(z)-1|<1$ and $f$ is not injective since $re^{2\pi i/3}, re^{-2\pi i/3} \in D$ for any $r$ as above and $f(re^{2\pi i/3})=f(re^{-2\pi i/3})=-r^{3/2}$


text:
Q: Why is there a narrowing conversion warning from int to short when adding shorts? (C++) I have a code similar to this for the following array:
long int N = 424242424242; //random number
short int* spins = new short int spins[N];
std::fill(spins, spins+N, 1);

Now let's suppose for some reason I want to add a couple of elements of that array into a short int called nn_sum:
short int nn_sum = spins[0] + spins[1];

However, when I do this on CLion IDE, Clang-Tidy marks it yellow and tells me:
Clang-Tidy: Narrowing conversion from 'int' to signed type 'short' is implementation-defined

Why is this happening? Why is there any narrowing at all? Does C++ convert the shorts to ints when adding them? If so why, and is there something I can do to make it work better? Maybe even ditch the shorts entirely?
Keep in mind that I have code like this in a very computationally intensive part of the application so I want to make it as efficient as possible. Any other suggestion would also be appreciated.

A: This happens because of integer promotion. The result of adding two short values is not short, but int.
You can check this with cppinsights.io:
short a = 1;
short b = 2;
auto c = a + b;  // c is int

Demo: https://cppinsights.io/s/68e27bd7


text:
Q: Can't add TimePicker component from 'element-ui' library. How To add it correctly? I need to add one component from 'element-ui' library to my project (Laravel + Vue). I'm interested in TimePicker.
I added to my bootstrap.js file next code:
/**
 * Element, a Vue 2.0 based component library for developers, designers
 * and product managers.
 */
import { TimePicker } from 'element-ui'
import lang from 'element-ui/lib/locale/lang/en'
import locale from 'element-ui/lib/locale'

// configure language
locale.use(lang)

// import components
Vue.component(TimePicker.name, TimePicker)

All this code was written according to the docs.
But I get error message in my browser:

[Vue warn]: Unknown custom element:  - did you register
  the component correctly? For recursive components, make sure to
  provide the "name" option.

I tried to import 'Button' component with the same set of code and it was working. But it doesn't work for TimePicker.
What I do wrong? Why It doesn't work

A: I found the problem. In my case, the name of the component that I was using in 'template' was wrong. I named it as "time-picker" instead of "el-time-picker"
Don't forger to add prefix 'el-' to the name of your components when using them in your <template>-s.
Full answer:
1)To add component globally to your app, add to your js file this code (the names of the components and other examples you can fined here ):
import { TimePicker } from 'element-ui'
import lang from 'element-ui/lib/locale/lang/en'
import locale from 'element-ui/lib/locale'

// configure language
locale.use(lang)

// import components
Vue.component(TimePicker.name, TimePicker)

*Add new component to your vue.js file, in <templete> section.:
<el-time-picker></el-time-picker>


text:
Q: Как лучше парсить математическое выражение Пишу что-то типа калькулятора. Нужно парсить математическое выражение. Хочу сначла токенезировать его, т.е. разбить на операции, операнды, функции, константы и так далее. И потом оперировать уже не со строкой, а со списком токенов. Думал разобрать его регулярками, но я в них совсем не силен(если это окажется лучшем исходом, то разобраться не проблема) и, мне кажется, что тогда придется ужесточать синтаксис. То есть выражение типа 10*15 +19 *sin(90 ) разобрать будет проблематично. Поэтому написал конечный автомат, но по мере расширения возможностей "калькулятора" и там возникает проблема, т.к. слишком много неоднозначностей в синстаксисе и приходится очень много менять в условии изменения состояний.
Очень хочется найти элегантное решение, у которого не будет проблем с расширением и код можно будет нормально читать. Собственно с этим вопросом я и обращаюсь.
Если кому-то будет важно, то пишу на Java

A: Немного странно, что Вы не нашли информации по разбору выражений. Есть очень известный алгоритм Дейкстры или алгоритм сортировочной станции, который решает задачу приведения инфиксной нотации (ту, что приводите Вы) в обратную польскую запись. Данная запись представляется, так сказать в виде "стека" и позволяет легко вычислить выражение. Реализация алгоритма Дейкстры, конечно, не самая приятная. Но, к счастью, есть кучи готовых библиотек. Например.
Если Вы хотите просто вычислить значение выражения, то Вам достаточно в лоб вычислить выражение, записанное в обратной польской записи. Если же хотите сделать это оптимально (быстро), то придётся поизвращаться и построить дерево разбора. Но думаю, что задача стоит именно в вычислении значения выражения.
Примеры обратной польской записи.
Пример 0.
Инфиксная форма
Операнд1 Операция Операнд2
Постфиксная форма
Операнд1 Операнд2 Операция

Пример 1.
Инфиксная форма.
2 + 2
Постфиксная форма.
2 2 +

Пример 2.
Инфиксная форма.
(2 + 2) * sin(x)
Постфиксная форма.
2 2 + sin(x) *

Пример 3.
Инфиксная форма.
2 + 2 * sin(x)
Постфиксная форма.
2 2 sin(x) * +

Пример 4.
Инфиксная форма.
((2 + 2) * sin(x) * 2 + 14)
Постфиксная форма.
2 2 + sin(x) * 2 * 14 +

Таким образом, чтобы вычислить значение выражения, необходимо начать разбить строку на токены, преобразовать её к обратной польской нотации (алгоритм Дейкстры) и вычислить путём добавления в стек всех встречающихся операндов и извлечения двух последних при встрече операции.
Выражение:
2 2 + sin(x) * 2 * 14 +
Шаг 0 (Пустой стек).
Стек:
Шаг 1 (Добавляем операнд).
Стек: 2
Шаг 2 (Добавляем операнд).
Стек: 2 2
Шаг 3 (Встретили операцию. Извлекаем 2 последних операнда и вычисляем их значение, которое добавляем в стек).
Стек: 4
Шаг 4 (Добавляем операнд).
Стек: 4 sin(x)
Шаг 5 (Вычисляем значение. Пусть x == -pi / 2).
Стек: -4
Шаг 6 (Добавляем операнд).
Стек: -4 2
Шаг 7 (Вычисляем значение).
Стек: -8
Шаг 8 (Добавляем операнд).
Стек: -8 14
Шаг 9 (Вычисляем значение).
Стек: 6

Значение выражения: 6

Замечу, что нужно быть осторожным с операциями, так как некоторые из них не коммутативны (например, возведение в степень).

A: Спасибо за комментарии и ответ, они по делу, но вы не поняли сути самой проблемы. Проблема заключалась в том, что мне нужно была максимальная гибкость и возможность расширения текущей версии программы. У меня в планах нечто много более обширное, чем банальный калькулятор. Поэтому мне нужно чтобы парсер был максимально абстрагирован он банальный решений типа буква - значит это функция.

Сделал так:
Процесс перехода от входного выражения в инфиксной форме я разбил на 3 этапа:

*

*Токенизация

*Трансляция в постфиксную форму (обратную польскую
нотацию)

*Расчет выражения в постфиксной форме

Подробно:

*

*На первом этапе входное выражение разбивается на атомарные части выражения (в моем случае я выделил операнды, константы, операторы, функции и скобки). Для хранения токенов был создан интерфейс "Выражение"(Expression), который реализовывали классы, описанные выше. На выходе выражения представляло из себя список токенов, который передается на следующий этап.

*Далее список выражений переводится в постфиксную запись, при помощи валгоритма Дейкстры. На этом этапе математические константы заменялись их численным значением. После этого выражение передается в расчетный модуль для вычисления конечного значения.

*На этом этапе, входное выражение, представленное в постфиксной форме, рассчитывалось на стеке при помощи данного алгоритма. В результате получаем численный ответ.

Если кого-нибудь заинтересует, то можете посмотреть реализацию на Java в моем репозитории. Также буду раз, если предложите идеи для дальнейшего развития ;)


text:
Q: Loading Raw image with Image I/O objective C return wrong resolutions I'm trying to load RAW image to an iOS project for displaying. Currently, I'm using this piece of code to load the raw image.
CFDictionaryRef optionsRef = (__bridge CFDictionaryRef) @{
                                                                  //                                                               (id) kCGImageSourceShouldAllowFloat: @YES,
                                                                  (id) kCGImageSourceCreateThumbnailWithTransform : @YES,
                                                                  (id) kCGImageSourceCreateThumbnailFromImageAlways : @YES,
                                                                  (id) kCGImageSourceThumbnailMaxPixelSize : @(MAX(SCREEN_HEIGHT, SCREEN_WIDTH) * ([UIScreen mainScreen].scale))
                                                                  };

        CGImageSourceRef imageSourceRef = CGImageSourceCreateWithURL((CFURLRef)imageUrl, NULL);

        if (!imageSourceRef)
            return nil;

        NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                                 [NSNumber numberWithBool:NO], (NSString *)kCGImageSourceShouldCache,
                                 nil];
        CFDictionaryRef imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSourceRef, 0, (CFDictionaryRef)options);
        if (imageProperties) {
            NSNumber *width = (NSNumber *)CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelWidth);
            NSNumber *height = (NSNumber *)CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelHeight);
            NSLog(@"Image dimensions: %@ x %@ px", width, height);
            CFRelease(imageProperties);
        }

The problem is, this code works flawlessly with some images, while it behaves strangely with others. For example, with one image I load, it show the width is 128 and the height is 96 , while the correct width height are 4320 × 3240.
I'm not sure what is the problem here because all I did was just load the image to CGImageSourceRef. :(

A: By raw you mean camera raw? (E.g. Nikon NEF files?)
As far as I know iOS does not have a raw image parsing engine. The only thing it will be able to do is to load the embedded JPEG thumbnail. You are probably seeing the size of the thumbnail, not the size of the full raw image.
Disclaimer: I've never tried to open a camera raw image in iOS, so my answer about what iOS is doing is based on imperfect memory of what I've read.

A: Nikon has libraries available for download, and I think they are in source form.  Probably C or C++, so it would take a little work to compile them and figure out how to use them from iOS but it should be possible.  You should be able to find them on the Nikon website.


text:
Q: Error: Car.Form1 is inaccessible due to its protection level C# I cant figure out 2 errors in this code can someone help me please?
error 1: Car.Form1 is inaccessible due to its protection level
error 2: The type or namespace name 'Point' could not be found (are you missing a using directive or an assembly reference?
Thanks for the help!
Main class
namespace Car
{
public partial class Form1 : Form
{
    int x = 0;
    int y = 500;
    int turn = 0;

    public Form1()
    {
        InitializeComponent();
    }
    public void Form1_KeyDown(object sender, KeyEventArgs e)
    {

            if (e.KeyCode == Keys.Right)
            {
                x += 32;
                turn = 1;
            }
            else if (e.KeyCode == Keys.Left)
            {
                x -= 32;
                turn = 2;
                Wheel1.Image.RotateFlip(RotateFlipType.Rotate270FlipNone);
                Wheel2.Image.RotateFlip(RotateFlipType.Rotate270FlipNone);
            }
            else
            {
                turn = 0;
            }
            if (x <= -250)
            {
                x = 1040;
            }
            else if (x >= 1041)
            {
                x = -250;
            }

    }

    public void Form1_Load(object sender, EventArgs e)
    {

    }
}
}

car class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Car
{
     public class Car : Form
     {
        public Car(Form1 form1)
        {
            form1.Car.Location = new Point(form1.x, form1.y);
        }
     }
}

A: According to form1.Car.Location I believe Car is some control on your form. By default all controls are private and not visible outside of form class. Fast solution: select your Car control in designer, and go to its properties. Find property Modifiers and change it to public. That will generate public field for your control, but it will also break encapsulation of your form. Better create method on form for moving car to new location. Something like:
public void MoveCar(Point location)
   {
       Car.Location = location;
   }
Point is declared in System.Drawing namespace.


text:
Q: invalid_grant issue in GoogleStrategy using Passport, Fastify I'm using passport.js to use google OAuth in my application. I'm using Nodejs, Fastify. I'm getting this response while I'm trying to log in. I tried refreshing Secret, Client ID by deleting and making new Credentials in Google Cloud Console. Nothing worked.
I'm getting this

"name":"TokenError","code":"invalid_grant","status":500},"msg":"Bad Request"

Help me with this.
Thank You in advance.
Fastify log here:

{"level":50,"time":1635763592399,"pid":16516,"hostname":"DESKTOP-7CKECCL","reqId":"req-4","req":{"method":"GET","url":"/google/callback?code=4%2F0AX4XfWg3Y9a6aUNaUE7raazx5I9YDRxuQfkYATW5RT6gRe_prB12Orc-DM5D21xlAM8CbQ&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+openid&authuser=0&prompt=consent","hostname":"localhost:8070","remoteAddress":"127.0.0.1","remotePort":4868},"res":{"statusCode":500},"err":{"type":"TokenError","message":"Bad Request","stack":"TokenError: Bad Request\n    at Strategy.OAuth2Strategy.parseErrorResponse (D:\oslash_backend_clone\node_modules\passport-oauth2\lib\strategy.js:373:12)\n    at Strategy.OAuth2Strategy._createOAuthError (D:\oslash_backend_clone\node_modules\passport-oauth2\lib\strategy.js:420:16)\n    at D:\oslash_backend_clone\node_modules\passport-oauth2\lib\strategy.js:177:45\n    at D:\oslash_backend_clone\node_modules\oauth\lib\oauth2.js:191:18\n    at passBackControl (D:\oslash_backend_clone\node_modules\oauth\lib\oauth2.js:132:9)\n    at IncomingMessage. (D:\oslash_backend_clone\node_modules\oauth\lib\oauth2.js:157:7)\n    at IncomingMessage.emit (events.js:327:22)\n    at IncomingMessage.EventEmitter.emit (domain.js:467:12)\n    at endReadableNT (internal/streams/readable.js:1327:12)\n
at processTicksAndRejections (internal/process/task_queues.js:80:21)","name":"TokenError","code":"invalid_grant","status":500},"msg":"Bad Request"}

Routes:
fastify.get(
    "/google",
    {
      preValidation: fastifyPassport.authenticate("google", {
        scope: ["profile", "email"],
        authInfo: false,
      }),
    },
    (req: any, res: any, next: any) => {}
  );

  // callback route for google to redirect to
fastify.get(
    "/google/callback",
    {
      preValidation: fastifyPassport.authenticate("google", {
        successRedirect: "/user/profile",
        failureRedirect: "/login",
        authInfo: false,
      }),
    },
    (req: any, res: any, next: any) => {
      res.send(req.user);
    }
  );

passport-setup:
fastifyPassport.registerUserSerializer(async (user: any, done: any) => {
  done(null, user._id);
});

fastifyPassport.registerUserDeserializer(async (id: any, done: any) => {
  models.User.findById(id).then((user: any) => {
    done(null, user);
  });
});

fastifyPassport.use(
  "google",
  new GoogleStrategy(
    {
      clientID: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      callbackURL: "/google/callback",
    },
    function (
      access_token: String,
      refresh_token: String,
      profile: any,
      done: any
    ) {
      models.User.findOne({ google_id: profile._json.sub }).then(
        (currentUser: any) => {
          if (currentUser) {
            console.log("User already Exists..!");
            done(null, currentUser);
          } else {
            models.User.create({
              google_id: profile._json.sub,
              email: profile._json.email,
              name: profile._json.name,
              profile_image: profile._json.picture,
              last_login: new Date(),
            }).then((newUser: any) => {
              done(null, newUser);
            });
          }
        }
      );
    }
  )
);


text:
Q: C shuffle 2D array Want to shuffle char *array and make elements random order
I read Shuffle array in C but for int
I try
const char *words = { "one", "two", "three", "four", "five", "six" };
for (int i=0; i<6; i++)
{
    int r = (rand() % (6 - i)) + i;

    int temp =  words[i];
    words[i] = words[r];
    words[r] = temp;
}

error though when iterate array words
please explain

A: As said in remarks you have several problems

const char *words = { "one", "two", "three", "four", "five", "six" };

is invalid because the initialization (and the rest of the code) indicates words is an array, so replace it by
const char *words[] = { "one", "two", "three", "four", "five", "six" };

    int temp =  words[i];
    words[i] = words[r];
    words[r] = temp;

words is an array of const char * so temp cannot be an int, use
const char * temp = words[i];

Out of that

*

*to use the literal 6 is dangerous, use sizeof to take into account any change on words replacing 6 by sizeof(words)/sizeof(*words)

*the right type for an index is size_t,

*to not have always the same executions use srand for instance with the current time

For instance :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
  const char *words[] = { "one", "two", "three", "four", "five", "six" };
  const size_t nelts = sizeof(words)/sizeof(*words);

  srand(time(NULL));

  for (size_t i=0; i < nelts;  ++i)
  {
    size_t r = (rand() % (nelts - i)) + i;
    const char * temp =  words[i];

    words[i] = words[r];
    words[r] = temp;
  }

  /* show */
  for (size_t i=0; i < nelts;  ++i)
    puts(words[i]);

  return 0;
}

Compilation and executions :
pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
four
one
two
five
three
six
pi@raspberrypi:/tmp $ ./a.out
one
three
two
four
five
six
pi@raspberrypi:/tmp $ ./a.out
six
five
two
four
three
one
pi@raspberrypi:/tmp $ ./a.out
three
one
five
four
six
two

A: There are multiple errors and flaws in OPs code.

*

*array of strings:

const char *words = { "one", "two", "three", "four", "five", "six" };

Not sure how the compiler reads this (if not complaining). An array of C strings should be:
const char *words[] = { "one", "two", "three", "four", "five", "six" };

*magic number

for (int i=0; i<6; i++)

6 is a magic number which is considered as bad style. It's better to give it a name. Even better: the value can be determined by compiler which improves maintainability of code:
int n = sizeof words / sizeof *words;
for (int i = 0; i < n; ++i) {

*usage of rand()
int r = (rand() % (6 - i)) + i;

rand() is a pseudo random generator with certain limitations. It shouldn't be used with % n. For certain ns (e.g. 2), this may result into a rather non-random sequence. The cppreference doc. of rand() gives a better example which I turned into a function:
int randomRange(int min, int max)
{
  for (int range = max - min;;) {
    int x = min + rand() / ((RAND_MAX + 1u) / range);
    if (x < max) return x;
  }
}

which is called
int r = randomRange(i, n);

*idiomatic swap

int temp =  words[i];

If the type of array elements to swap is const char* the temp must be as well:
    const char *temp = words[i];
    words[i] = words[j];
    words[j] = temp;

The complete sample code:
#include <stdio.h>
#include <stdlib.h>

int randomRange(int min, int max)
{
  for (int range = max - min;;) {
    int x = min + rand() / ((RAND_MAX + 1u) / range);
    if (x < max) return x;
  }
}

int main(void)
{
  /* an array of strings */
  const char *words[] = { "one", "two", "three", "four", "five", "six" };
  /* let compiler determine size */
  int n = sizeof words / sizeof *words;
  /* shuffle */
  for (int i = 0; i < n; ++i) {
    int j = randomRange(i, n);
    /* idiomatic swap */
    const char *temp = words[i];
    words[i] = words[j];
    words[j] = temp;
  }
  /* print result */
  const char *sep = "";
  for (int i = 0; i < n; ++i) {
    printf("%s%s", sep, words[i]);
    sep = ", ";
  }
  /* done */
  return 0;
}

Output:
six, three, one, two, four, five

Live Demo on coliru


text:
Q: Grok pattern for data separated by pipe I have a logfile in which the data is separated by a pipe symbol. "|". An example is below. Does anyone know how to write a GROK pattern to extract it for logstash?
2014-01-07 11:58:48.7694|LOGLEVEL|LOGSOURCE|LOGMESSAGE

A: use this filter:
it works for me. use this site to verify grok patern, https://grokdebug.herokuapp.com/
(?<date>(([0-9]+)-*)+ ([0-9]+:*)+.*)\|%{WORD:LOGLEVEL}\|%{WORD:LOGSOURCE}\|%{WORD:LOGMESSAGE}

A: You can use gsub API to change the pipe "|" to space and the use GROK to extract it.
For example:
filter {
    grok {
            match => ["message","%{DATESTAMP:time}\|%{WORD:LOGLEVEL}\|%{WORD:LOGSOURCE}\|%{WORD:LOGMESSAGE}"]
    }
}

The above configuration is worked on me with your log. Hope this can help you.

A: This worked for me
grok { match => ["message","%{DATESTAMP:time}\|%{WORD:LOGLEVEL}\|%{WORD:LOGSOURCE}\|%{WORD:LOGMESSAGE}"] }

A: The LOGMESSAGE part can contain a long content. For this reason, I recommend the following usage.
%{GREEDYDATA:LOGMESSAGE}


text:
Q: Multiplying the dirac delta distribution by a function In the theory of distributions, if $H(x)$ is the Heaviside function, we have seen that the distributional derivative of $H$ can be found as follows, for a test-function $\varphi$:
\begin{align*}
\left\langle H'(x),\varphi \right \rangle&=\left\langle H,-\varphi' \right\rangle\\
&=-\int_0^{\infty}\varphi'(x)dx\\
&=\varphi(0) \\
&=\left\langle \delta,\varphi\right\rangle \,.
\end{align*}
Now, my question is, when using a multiplication operator in $\mathcal{D}'(\mathbb{\Omega})$ for some function $f \in \mathcal{C}^\infty(\Omega)$, how do I calculate $\left\langle fH',\varphi \right\rangle = \left\langle H',f\varphi\right\rangle =\left\langle \delta,f\varphi\right\rangle $, which is also equal to $-\left\langle H,(f\varphi)' \right\rangle$? If I just write out this latter integral I end up circling around in partial integration, and I am unable to find a meaningful expression.
Am I missing something? Do I just evaluate $f(0)\varphi(0)$?

A: You don't need to integrate here, just use the definition of $\delta$:
$$\langle fH', \varphi \rangle = \langle H', f\varphi \rangle = \langle \delta, f\varphi \rangle = (f\varphi)(0) = f(0) \varphi(0).$$


text:
Q: Get unique list of links that match query I am using anglesharp to parse a webpage and to then discover links that might be the contact page.
Here is my code:
        var config = Configuration.Default.WithDefaultLoader();

        string address = "http://www.stackoverflow.com/";

        Url baseurl = new Url(address);

        var document = await BrowsingContext.New(config).OpenAsync(baseurl);

        var links = document.Links.Where(x => ((IHtmlAnchorElement)x).Host == baseurl.Host ).ToList();

        var contacts = links.Where(x => ((IHtmlAnchorElement)x).PathName.ToLower().Contains("contact")).Select(x => ((IHtmlAnchorElement)x).PathName).Distinct();

It works but I am getting duplicate PathName values in contacts.  I want to only ever take one value for each PathName but the select/distinct isn't working.
Do I have to create my own custom comparer or is there a way to alter my linq query?  I don't need any of the other data, just the host and pathname.

A: As Reza said, ToLower() is needed, and a simpler approach is to select the pathName first and then do the filtering:
var contacts = links.Select(x => ((IHtmlAnchorElement)x).PathName.ToLower())
                    .Where(pathName => pathName.Contains("contact"))
                    .Distinct();


text:
Q: Original with me
There are many ideas in this book which are, to the best of my knowledge, original with me.

A favorite technique, original with him, he called "word-count."

I do not know whether this would now be taught in the schools of Oxford, and was original with him or not.

All examples are from the internet. There is a similar discussion on WordReference.com
Since Merriam-Webster doesn't mention this type of use, I'd like to ask about it here. The meaning, as I get it, credits the item/knowledge to a certain owner/producer ("me," "him" in the example).
However, I'm curious if this structure is widely accepted or is regional. Most sources where I've seen this phrase are AmE. Is it slang or a new norm?


text:
Q: DAX measure - show values from best day I have, in PowerBI (October 2017 release) some data showing the snapshotted output of some solar panels at five-minute intervals.

I presently have a measure which calculates the total production for each day by getting a sum of the instantaneous readings for the day and dividing by 12 (because there are 12 readings per hour) and then shows the average of this daily amount over whichever period is in the current context:
Avg Daily Production (KWh) =
    AVERAGEX(SUMMARIZE('Solar Output', 'Solar Output'[Date], "Daily Production (KWh)", SUM('Solar Output'[Production (KW)]/12), [Daily Production (KWh)])

For my visualisations I'd like to show a chart which displays the average production at various times of the day compared to the production at that time for the best day, i.e. the day with the highest value for [Avg Daily Production (KWh)].
Here is my working so far:
Identify the top day by using
Best Day = TOPN(1, SUMMARIZE('Solar Output', 'Solar Output'[Date], "Daily Production (KWh)", [Avg Daily Production (KWh)]), [Daily Production (KWh)], DESC)

But this produces a row, not a scalar, and I can't quite work out how to just get this date and use it as a filter for a measure like this:
Production On Best Day (KW) =
    CALCULATE(SUM([Production (KW)]), FILTER(ALL('Solar Output'[Date]), 'Solar Output'[Date] = [Best Day]))

The chart I want would look like this, with the average production for the selected dates in green and then another series showing the production at those times on the best day pencilled in red.

A: Can't really get my head around the calculations involved but I hope I get your requirement.
So you want to plot two lines on the same chart, one always being the data from the best day as reference, and the other one the data selected from the date filter, right?
You're actually pretty closed to the solution with the info given above.
I just modified your DAX to:
Production On Best Day (KW) =
CALCULATE(
    SUM('Solar Output'[Average]),
    FILTER(
        ALL('Solar Output'[Date]),
        'Solar Output'[Date] = VALUES('Best Day'[Date])
    )
)

(Not quite sure how you compute your intermediate measures so you may need to adjust according to your measures)
Yes, TOPN() returns a table, so you can get the date value using VALUES('Best Day'[Date]) and use it for comparison.
Results:

A: Alternate approach to solve this issue is to use the MAXX() function to get a scalar value out of the the table returned by TOPN().
This works where MAX() doesn't because MAXX() accepts a table expression as its first argument (the table expression is the result of the TOPN() function) where MAX() only takes columns from existing tables.
Best Day = MAXX(TOPN(1,
                     SUMMARIZE(ALL('Solar Output'),
                               'Solar Output'[Date],
                               "Daily Production (KWh)",
                               [Avg Daily Production (KWh)]),
                     [Daily Production (KWh)],
                     DESC),
                [Date])

The benefit of this approach is that it should work in versions of DAX with no calculated table support (e.g. SSAS 2014, Excel 2013).


text:
Q: Install wxPython classic on OSX11.2 so I can run a project from source that imports wx I am trying to run a project from source that needs to import wx. I have tried more than one method.

*

*I am getting the following error:

Can't find or import /pathToMyGitHubSources/wxWidgets/build/tools/build-wxwidgets.py, exiting.

That is when I try installing from source using the following command:
/usr/bin/python /pathToMyGitHubSources/wxPython/build-wxpython.py --build_dir=../bld --osx_cocoa

I confirmed the file does not exist in the source folder:
ls /pathToMyGitHubSources/wxWidgets/build/tools/
appveyor.bat    msvs        release.bat release.sh  wxwidgets.iss

I had pulled the sources from the following:

*

*https://github.com/wxWidgets/wxPython.git

*https://github.com/wxWidgets/wxWidgets.git

*I also tried installing a downloaded package using the following command:
sudo installer -pkg /Volumes/wxPython3.0-osx-3.0.2.0-cocoa-py2.7\ 1/wxPython3.0-osx-cocoa-py2.7.pkg -target /

The package was downloaded from: http://downloads.sourceforge.net/wxpython/wxPython3.0-osx-3.0.2.0-cocoa-py2.7.dmg
This only results in an error:

The Installer could not install the software because there was no software found to install

*I installed a build using the following command:
sudo -H pip install --upgrade --trusted-host wxpython.org --pre -f http://wxpython.org/Phoenix/snapshot-builds/ wxPython_Phoenix

However, this build, having the 'Phoenix' designation is apparently not compatible with projects that were made for the 'classic' builds. The wxversion() doesn't detect the install and even after a successful 'import wx', attempting to migrate the project using the migration guide I found does not actually cover all of the differences I run into, such as

object has no attribute 'InsertColumnInfo'

Error for the wx.ListCtrl objects. For this reason, I think I need to get classic wx installed. (If I continue trying the migration method, I'll make a separate question for it. )
Having failed my attempts at these three different methods, my question: Is there a way to get wx classic installed, so that I may run the parent project from source?

A: This change was just pushed to source that restores the missing build-wxwidgets.py
Update to this version and then retry the build-wxpython.py.
After successful build, environment variables need to be set. Then wxversion fails to detect. Insert the path to wxPython* files at the beginning of the path list. Then finally able to import wx. Shown below.
export PYTHONPATH=$PYTHONPATH:'/usr/lib/python2.7/site-packages/wx'
export DYLD_LIBRARY_PATH=%DYLD_LIBRARY_PATH=:'/usr/lib/python2.7/site-packages/wx/lib'

python

import sys
import wxversion
try:
    wxversion.select(['3.0.3', '3.0'])
except wxversion.VersionError:
    print "wx version failed detection"
    sys.path.insert(0, '/usr/lib/python2.7/site-packages')

import wx
print wx.version()

Above wx is installed beginning by using method #1 in the question.
The package installer does not work with OSX 10.11 and over, so method #2 in the question doesn't work. Method #3 in the question leads to a lengthy migration process.


text:
Q: Create Google Script to send email when cell is edited This may sound like many other questions - but it's slightly different and I can't formulate an answer.
I have "Tasks" in column A, "Person Responsible" for task in column B, "Email" in column C, and Column D is blank for tracking completion.
When an edit is made to a cell in Column D( like an "X" for completed), I want send an email to the address specified in the corresponding row, with the corresponding task in the email subject/body.
Here is a link to a Google Spreadsheet to help illustrate
http://goo.gl/uFWGE

A: I can't see any reason why with a minimum of work you couldn't achieve what you want.
please have a look at this post to learn how to restrict the event source range by column and then use simply the Mailapp service like in this tuto and you'll have the pleasure to run an app that you wrote by yourself...
The next one will be even easier and so will be the one after... That process is called learning and we all have been trough this, believe me.


text:
Q: getting error unrecognized selector sent at tableview when last row  of table view is clicked i m parsing json data and populating the tableview and making some validation with the incoming json data..everthing works fine.i made the code such that when the last table view row is clicked it got to open a modal view controller.when clicked .i m getting this error [tableiew1] Unrecognised selector send at the instance...could u guys help me out below is the code.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here. Create and push another view controller.

if (indexPath.row == 5) {

    if (self.dvController6 == nil)
    {
        Vad_tycker *temp = [[Vad_tycker alloc] initWithNibName:@"Vad_tycker" bundle:[NSBundle mainBundle]];
        self.dvController6 = temp;
        [temp release];
    }

    [self presentModalViewController:self.dvController6 animated:YES];

}

   }

A: Seems like you have forgotten to provide the access for the tableView1 in Vad_tycker.
Or You should do a crosscheck whether you have assigned the correct instance in tableView delegate's and also make sure to provide the implementation for the method of delegate's in their respect target classes.

A: I think you forgot to connect the tableView Datasource and Delegate methods in the vad_tycker controller.
Also check that the instance of UITableView i.e. in your case tableView1 is also connected with the TableView. on the view.
Thanks


text:
Q: Select from term_taxnomy table using AND I have stucked with a situation, where i have to show posts on check and uncheck of the terms.
The posts having terms assigned. I have terms 'Area' and 'Cuisines' now i have to select the post which has the area 'XYZ' and cuisine 'ABC'.
The query i have tried :-
    SELECT p.ID, p.post_title
      FROM wp_posts p
 LEFT JOIN `wp_term_relationships` t
        ON p.ID = t.object_id
 LEFT JOIN `wp_term_taxonomy` tt
        ON t.term_taxonomy_id = tt.term_taxonomy_id
     WHERE tt.term_id IN (".$area.")
           OR tt.term_id IN (".$cuis.")
  GROUP BY t.object_id
    HAVING COUNT( t.term_taxonomy_id ) = 2
     LIMIT 0,7

And the Structure of the wp_term_taxonomy is shown here :-
The problem is the single table and single column and apply the AND operator between the values.
wp_term_relationship
object_id  | wp_term_taxonomy_id | term_order
==============================================
   134     |       36            |    0
______________________________________________
   135     |       36            |    0

wp_posts
    ID     |    post_title       |
==================================
    1      |       Hello world!  |
__________________________________
    2      |       Test          |

wp_term_taxnomy
  term_taxonomy_id  term_id     taxonomy    description     parent  count
        =============================================================================
          1                1            category     ------           0        2

A: Suppose, we have 3 tables:
| test1 |     | test1_to_test2 |         | test2 |
|-------+     +----------------|         +-------|
| id    |-----|  test1_id      |    +----|  id   |
              |  test2_id      |----+

Exactly the structure, that you have.
Content:
    test1
+----+-------+
| id | value |
+----+-------+
|  1 | val1  |
|  2 | val2  |
+----+-------+

    test1_to_test2
|----------+----------|
| test1_id | test2_id |
|----------+----------|
|        1 |        1 |
|        1 |        2 |
|        2 |        1 |
|----------+----------|

 test2
|----+
| id |
|----+
|  1 |
|  2 |
|----+

And we need to select values from test1 table, that have rows in test1_to_test2 with (test2_id = 1) AND (test2_id = 2). So, we want this:
+----+-------+
| id | value |
+----+-------+
|  1 | val1  |
+----+-------+

To do it we split the task into 2 subtasks:
1.Select test1_id from test1_to_test2, that has both rows present:
SELECT
    test1_id
FROM
    test1_to_test2
WHERE
    test1_to_test2.test2_id IN (1,2)
GROUP BY
    test1_id
HAVING
    COUNT(test1_id) = 2

2.Select the appropriate rows from test1, using the subquery and IN operator (it's the SQL, that we need):
SELECT
    test1.id,
    test1.`value`
FROM
    test1
WHERE
    test1.id IN
(
SELECT
    test1_id
FROM
    test1_to_test2
WHERE
    test1_to_test2.test2_id IN (1,2)
GROUP BY
    test1_id
HAVING
    COUNT(test1_id) = 2
)

We get what we need:
+----+-------+
| id | value |
+----+-------+
|  1 | val1  |
+----+-------+

Use the same approach with your tables, and you'll get the posts which have the area 'XYZ' and cuisine 'ABC'.

A: Your best bet is to do two joins, one for each term:
    SELECT p.ID, p.post_title
      FROM wp_posts p
 LEFT JOIN `wp_term_relationships` t
        ON p.ID = t.object_id
 LEFT JOIN `wp_term_taxonomy` tarea
        ON t.term_taxonomy_id = tt.term_taxonomy_id and tt.term_id IN (".$area.")
 LEFT JOIN `wp_term_taxonomy` tcuis
        ON t.term_taxonomy_id = tt.term_taxonomy_id and tt.term_id IN (".$cuis.")
     WHERE tarea.description = 'XYZ' and
           tcuis.descriptoin = 'ABC'
  GROUP BY t.object_id
     LIMIT 0,7 ;

Also, you can change the left joins to inner joins -- which the where clause does anyway.  The left joins would be useful for "or" conditions rather than "and" conditions.


text:
Q: How to redirect FileListAbsolute.txt to another folder I have an MS Build set up to build C++ projects which is configured with file path length as 260 characters. A few of my projects are having long target names which were failing with
MSB3491: Could not write lines to file Path: x64\Release\{targetname}vcxproj.FileListAbsolute.txt exceeds the OS max path limit.The fully qualified file name must be less than 260 characters.
I have redirected the output path and intermediate path a few levels up to the project folders and all the targets are generated without causing the above mentioned error except for FileListAbsolute.txt.
I am unable to redirect FileListAbsolute.txt and it is always created inside default path (projfolder\platform\configuration).
How can I redirect FileListAbsolute.txt to another folder few levels up to the project folder where other intermediate files are generated?
Edit:
Additionally, FileListAbsolute.txt is generated with 0KB size.
if we cannot move this file to any other folder, how can I block generating this file?


text:
Q: How to change the parameters of the binomial distribution used in a binomial glmer? I wish to assess how being part of a majority helps in emerging as a leader of an animal group.
Say I have 10 cases in which I assessed whether the leader came from the majority or the minority.
Leader <- c(1,1,1,1,0,1,1,1,0,1,0,0,0,0,1,0,0,0,1,0)
Case <- as.factor(c(1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10))
Majority <- as.factor(c("Maj","Maj","Maj","Maj","Maj","Maj","Maj","Maj","Maj","Maj",
        "Min","Min","Min","Min","Min","Min","Min","Min","Min","Min"))
leadMaj <- data.frame(Leader,Case,Majority)

binomial.glmer <- glmer(Leader ~ Majority + (1|Case),
                    family = binomial, data = leadMaj)
summary(binomial.glmer)

The outcome says that being from the minority drastically decreases the probability to lead the group
Generalized linear mixed model fit by maximum likelihood (Laplace Approximation) [glmerMod]
Family: binomial  ( logit )
Formula: Leader ~ Majority + (1 | Case)
Data: leadMaj

 AIC      BIC   logLik deviance df.resid
  26       29      -10       20       17

Scaled residuals:
Min     1Q Median     3Q    Max
-2.0   -0.5    0.0    0.5    2.0

Random effects:
Groups Name        Variance Std.Dev.
Case   (Intercept) 0        0
Number of obs: 20, groups:  Case, 10

Fixed effects:
        Estimate Std. Error z value Pr(>|z|)
(Intercept)   1.3863     0.7906   1.754   0.0795 .
MajorityMin  -2.7726     1.1180  -2.480   0.0131 *
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
            (Intr)
MajorityMin -0.707

However, the groups were composed of 8 individuals in the majority and 2 individuals in the minority. We can see that in 80% of the cases the majority led, which is what is expected.
So the question is: how can I include the binomial distribution with p=0.8, and not p=0.5?


text:
Q: Tab Index is Reset in UpdatePanel I'm currently having an issue where an updatepanel does an async postback and loses the tab order when the partial postback occurs.
When you run through the tabs the tab order works correctly, but then you press a button and the partial postback occures the tabindex is reset. Is there any non-javascript solution to this. If not, what would the javascript solution be?

A: You might try putting this at the end of the code that is handling your button click event:
ScriptManager.SetFocus(DirectCast(sender, Control))

This would put the focus back on your button when the page loads.

A: this is a fix for anyone using AutoPostBack="true" on controls not going to the next control in the tab order.  if you wrap each control in it's own UpdatePanel the focus will move to the next control as expected.  even w/ UpdateMode="Conditional" the controls seem to lose focus.  i hope this helps someone else.


text:
Q: python re.sub, substitute a pattern only if it appears at the beginning of a string substitute a pattern only if it appears at the beginning of a string.
for e.g. str1 = "abab abadfadsf"
I only want to remove/replace the "ab" at the beginning of str1, i.e. I want to write an regex so that I can get str2 = "ab abadfadsf" from str1 by re.sub
how do I do it?

A: You'd be better off using the builtin string methods for this simple case - a regex is useful for more complex matching, but not required for this.
str2 = str1[2:] if str1.startswith('ab') else str1

A: You can use re.sub('^ab', '', 'abab abadfadsf')
^ stands for the beginning of the string.


text:
Q: Proper Way to Test a file method with .net I'm new to .net and testing. My following code looks like this:
using System.Xml.Linq;
    public class AnimalXmlService
    {
        public Animal GetAnimalInfoFromXml(string url) {
            XElement xml_doc = GetXmlInfo(url);
            if (xml_doc == null)
            {
                return null;
            } else {
                XElement animal_info = xml_doc.Element("Animal");
                string animal_name = GetAnimalName(animal_info);
                int animal_id = GetAnimalId(animal_info);

                return new Animal(animal_id, animal_name);
            }
        }

        private XElement GetXmlInfo(string url)
        {
            try
            {
                XElement animal_xml_info = XElement.Load(url);
                return animal_xml_info;
            }
            catch
            {
                return null;
            }
        }

        private int GetAnimalName(XElement animal_info)
        {
           ....
        }

}

My question is how do I stub the GetAnimalInfoFromXml to return a file? I have the sample xml file that I will be using instead of making a request. Here's my following test. I'm also wondering if there are better ways to refactor this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;

namespace AnimalXmlService
{
    [TestFixture]
    public class AnimalXmlTest
    {

        [Test]
        public void extracts_valid_name()
        {
           //get xml file?

            animalService AnimalXmlService = new AnimalXmlService();
            name = animalService.GetAnimalName(xml_file);
            Assert.AreEqual(name, "bobby the tiger");
        }

        [Test]
        public void extracts_valid_id()
        {
           //get xml file?
           xml_file = fetch_file //is this appropriate?

            animalService AnimalXmlService = new AnimalXmlService();
            id = animalService.GetAnimalId(xml_file);
            Assert.AreEqual(name, "2");
        }
    }
}

A: In this situations you can use test doubles.
First , you should make your codes more testable ( Breaking dependency )
public class AnimalXmlService
{
    private readonly IXmlReader _xmlReader;

    public AnimalXmlService(IXmlReader xmlReader)
    {
        this._xmlReader = xmlReader;
    }

    public Animal GetAnimalInfoFromXml(string url)
    {
        XElement xml_doc = _xmlReader.Load(url);
        if (xml_doc == null)
        {
            return null;
        }
        else
        {
            XElement animal_info = xml_doc.Element("Animal");
            string animal_name = GetAnimalName(animal_info);
            int animal_id = GetAnimalId(animal_info);

            return new Animal(animal_id, animal_name);
        }
    }
}

And then you should create a stub to replace your real dependency. ( Also you can use frameworks like NSubstitute,Mock,...)
public class XmlReaderStub : IXmlReader
{
    public XElement XElement { get; set; }

    public XElement Load(string url)
    {
        return XElement;
    }
}

And finally
public class AnimalXmlTest
{
        [Test]
        public void extracts_valid_name()
        {
            var stub = new XmlReaderStub();
            stub.XElement = new XElement(); // some XElement
            animalService AnimalXmlService = new AnimalXmlService(stub);

            name = animalService.GetAnimalName();

            Assert.AreEqual(name, "bobby the tiger");
        }
}

A: You can have another method in your class like the one below which returns an XmlDocument.
 public XmlDocument GetXmlFile()
   {
      XmlDocument doc = new XmlDocument();
      doc.LoadXml("<Animal><Name>Bobby the tiger</Name></Animal>");

      return doc;
   }


text:
Q: Check continuity of functional in weak topology I have the following exercise:
Check whether the following family of seminorms is separating.
$$C[0,1]\ni f\rightarrow \sqrt{\int_0^1 |f(\frac{t}{n})|^2 dt} \in [0,\infty) \:\:\:\:\:\:\:n=1,2,3,\dots$$
If so, check continuity of functional $C[0,1]\ni f\rightarrow f(0) \in \mathbb{C}$ with respect to locally convex (weak topology) induced by this system of seminorms.
My attempt
I checked that indeed this family of seminorms is separating. But I don't have idea how can I check continuity. This functional is continuous in norm topology on $C[0,1]$. Doesn't it follow that it is then continuous in weak topology?

A: An integral of $f$ does not control pointwise behavior of $f$, because each individual point makes zero contribution to the integral. This   suggests that the functional $f\mapsto f(0)$ is not continuous. (Aside:   an integral  involving derivatives of $f$ may be able to control pointwise values of $f$, via the Fundamental Theorem of Calculus.)
A counterexample is presented by functions that behave differently in a very small neighborhood of $0$ than they do elsewhere. A natural choice is $f_k=\chi_{[0,1/k]}$... except this isn't continuous, so we'd better take $f_k=\max(0,1-kx)$ instead. This sequence converges to the zero function[1] in the    topology  induced by these  seminorms, but $f_k(0)=1\not\to0$.

[1] Take any neighborhood of $0$. For some $r>0$ and some $N$, this neighborhood contains all functions whose $n$th seminorm is less than $r$, for $n=1,\dots,N$. Check that $f_k$ satisfies this for all sufficiently large $k$.


text:
Q: ASM code in KMDF driver I added asm source to KMDF driver project:
.CODE

read_port PROC port : WORD, result_ptr : PTR BYTE

    mov dx, port
    in al, dx                       ; read port

    mov rbx, result_ptr
    mov BYTE PTR [rbx], al          ; place value at result address

ret

read_port ENDP

END

In Driver.c file I can call read_port like this:
extern void read_port(unsigned short port, unsigned char* result);

//...

unsigned char val;
read_port(0, &val);

However I can't call this function like that from additional source file, for example test.cpp. Complier gives me unresolved external.
test.cpp:
extern void read_port(unsigned short port, unsigned char* result);

//...

unsigned char val;
read_port(0, &val);         // unresolved external

What is the reason?


text:
Q: What is the ROF pin on my power supply? I laid my hands on a old power supply (Cisco ADP-29DB CC:B1/1, it came with an Cisco ISDN router many moons ago) and it has a connector with the following pinout:
\begin{array}{ccc}
\text{-12V / 100mA}&*&*&\text{-24V / 120mA}\\
\text{+12V / 100mA}&*&*&\text{-71V / 120mA}\\
\text{RTN}&*&*&\text{RTN}\\
\text{ROF}&.&*&\text{+5V / 120mA}\\
\end{array}
Most pins are clear, I guess 'RTN' is simply short for 'return' or GND. Which leaves one pin with an unclear marking:
What does ROF mean? An interesting detail is that the pin for ROF is a bit deeper down into the connector so it makes contact last of all pins, implying that is has something to do with hot-plugging the PSU.

A: ROF stands for Remote On/Off.  This pin must be grounded for the supply to work.


text:
Q: stop scroll when you click on body or move your finger on the phone I have several scrolling options on my website after clicking the button:
 $(".button").click(function () {
      $('html,body').animate({
         scrollTop: $("div").offset().top
      });
  });

How can I stop scrolling if the user clicks anywhere with the mouse or clicks a finger on the phone's screen to stop it?


text:
Q: WP_cron keeps going back to the past When I execute this command wp cron event list, this is the output:
+-------------------------------------------------------------------+---------------------+----------------------+---------------+
| hook                                                              | next_run_gmt        | next_run_relative    | recurrence    |
+-------------------------------------------------------------------+---------------------+----------------------+---------------+
| action_scheduler_run_queue                                        | 2021-04-28 08:11:04 | now                  | 1 minute      |
| jetpack_sync_cron                                                 | 2021-04-28 08:11:13 | now                  | 5 minutes     |
| jetpack_sync_full_cron                                            | 2021-04-28 08:13:19 | now                  | 5 minutes     |
| woocommerce_cancel_unpaid_orders                                  | 2021-04-28 08:14:53 | now                  | Non-repeating |
...

I can execute the cron manually, the list gets more empty, the next run date will update correctly.
But... after +- 5 minutes this list is there again, with the same date/time as in the past.
The cron itself is working, so no problem with that.
I've been searching for this problem for hours, but cannot find the cause of this.
Disabled almost all the plugins I've got, no difference.
Tried to manually delete the cron entry from wp_options => it's working again, but after a few minutes, the list with old entries is here again.
Maybe someone over here knows the magic? :-)

A: For future reference if someone else has the same problem.
Found out that the high availability of the database cluster was causing this. For some weird reason another server was sending old data back to the mysql server on which this wordpress site is connected at the moment.
The strange thing is that it was only the cron row in wp_options that was affected with this, but the important part is that the cause has been found.
The cause was not wordpress related itself, but still only affecting wordpress for some reason...


text:
Q: Java Semaphore - How to get used permits We can get remain permits though availablePermits()
how to get usedPermits() or maxPermits  at runtime (e.g. The max permits are loaded from db and the db value may be mutated after the semaphore created)?
Of course I can memorize the maximum permits in the memory but I wondered whether there is a simple way to do this

A: Unfortunately, it is not possible, if you don't keep track of the original number yourself. Alternatively, you could easily extend Semaphore to have said capability(example implementation at the bottom).
In theory(and in the Java implementation), a semaphore does not have any concept of the "original" number of permits. With the defined semantics of a semaphore, you could very well initialize it with 0 permits, and require some permits to be "released" before any could be aquired. In practice I have never come seen a semaphore used in this manner, but that is how a semaphore is defined.
From the Java Semaphore documentation:

There is no requirement that a thread that releases a permit must have acquired that permit by calling acquire(). Correct usage of a semaphore is established by programming convention in the application.

So as you can see, if we don't know the "max permits" ourselves, the way semaphores are designed, they have no way of telling us either.
If you think of a semaphore as a wrapper around an int(which is in many ways what it is), it becomes quite clear:
Imagine we have the following sequence:
int permits = x;
permits--;
permits++;
// More unknown decrements/increments
permits--;

Getting the number of permits now is easy. Telling you how many has been used is impossible without either knowing x or the sequence of operations in the meantime.

Example of extending Semaphore to have a usedPermits method.
import java.util.concurrent.*;

class UsedTrackingSemaphore extends Semaphore {
    private int originalPermits;

    public UsedTrackingSemaphore(int permits) {
        super(permits);
        originalPermits = permits;
    }

    public UsedTrackingSemaphore(int permits, boolean fair) {
        super(permits, fair);
        originalPermits = permits;
    }

    public int usedPermits() {
        return originalPermits - availablePermits();
    }
}


text:
Q: Strange interaction between Alpha and legend While plotting several ecdf curves that overlapped, I tried adjusting the alpha of the curves to improve visibility. While tinkering with the correct placement of alpha, I found the following.
library(ggplot2)
library(dplyr)

x <- data.frame(Var = rep(1:3, 10000)) %>%
  mutate(Val = rnorm(10000)*Var,
         Var = factor(Var)) %>%
  arrange(Var, Val) %>%
  group_by(Var) %>%
  mutate(ecdf = ecdf(Val)(Val))

ggplot(x, aes(x=Val)) +
  stat_ecdf(aes(color = Var), size = 1.25, alpha = .9)

This gives the lines the correct alpha, but makes the legend useless. (I'm only using alpha=.9 here to demonstrate the point that the legend colors completely disappear). The work around I've found is to add:
ggplot(x, aes(x=Val)) +
  stat_ecdf(aes(color = Var), size = 1.35, alpha = .9) +
  guides(color = guide_legend(override.aes= list(alpha = 1)))

So while I have a solution for my immediate problem, can someone explain why the first call to ggplot is messed up? Is this a bug? If it makes any difference, I believe this issue also exists when using geom_line (though a slightly different data.frame is needed).
Wierd. Here's my sessionInfo(). I've also checked to see if there are any outdated packages.
sessionInfo()
R version 3.2.1 (2015-06-18)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=Japanese_Japan.932  LC_CTYPE=Japanese_Japan.932  LC_MONETARY=Japanese_Japan.932
[4] LC_NUMERIC=C                   LC_TIME=Japanese_Japan.932

attached base packages:
[1] splines   stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] RColorBrewer_1.1-2 ggplot2_1.0.1      stringr_1.0.0      tidyr_0.2.0        dplyr_0.4.2
[6] data.table_1.9.4

loaded via a namespace (and not attached):
[1] Rcpp_0.11.6      magrittr_1.5     MASS_7.3-40      munsell_0.4.2    colorspace_1.2-6
[6] R6_2.0.1         plyr_1.8.3       tools_3.2.1      parallel_3.2.1   grid_3.2.1
[11] gtable_0.1.2     DBI_0.3.1        lazyeval_0.1.10  assertthat_0.1   digest_0.6.8
[16] reshape2_1.4.1   labeling_0.3     stringi_0.5-4    scales_0.2.5     chron_2.3-47
[21] proto_0.3-10

A: How are they different? What am I missing?
library(ggplot2)
library(dplyr)
library(gridExtra)

x <- data.frame(Var = rep(1:3, 10000)) %>%
  mutate(Val = rnorm(10000)*Var,
         Var = factor(Var)) %>%
  arrange(Var, Val) %>%
  group_by(Var) %>%
  mutate(ecdf = ecdf(Val)(Val))

ggplot(x, aes(x=Val)) +
  stat_ecdf(aes(color = Var), size = 1.25, alpha = .9) -> gg1

ggplot(x, aes(x=Val)) +
  stat_ecdf(aes(color = Var), size = 1.35, alpha = .9) +
  guides(color = guide_legend(override.aes= list(alpha = 1))) -> gg2

grid.arrange(gg1, gg2)


text:
Q: Two external monitors using macOS and Windows on a MacBook Pro 13" I am in the process of setting up my desktop space and would like some guidance on products to purchase.
I am looking to buy two external monitors and a dock that will allow me to use my macOS and Windows Boot Camp partition on MacBook Pro 13" (2019) with two USB-C ports.
I essentially want to be sure that I will be able to utilize both operating systems when I purchase the new hardware. I have encountered mixed reviews about what will work with Boot Camp. I am willing to sacrifice display quality for speed as I will be using various types of statistical software and ArcGIS.

A: You have to check with the manufacturer to ensure it works with the OS on the Bootcamp partition.
There is no Bootcamp "compatible" hardware because Bootcamp isn't an operating system, it's  functionality built into your Mac.
So, you have to check to see if the dock, displays, and any other ancillary devices are compatible with macOS and Windows 10 (for example).
That said, docks and displays rarely have specific OS drivers.  Get quality ones of each and you should be fine.

A: This kind of depends on the monitors. For example, if you need the traditional Mac displayports, you would buy a Thunderbolt 3 Dual
DisplayPort Adapter.

A: No wait, you can't use bootcamp like that.
Bootcamp is designed to allow you to change your operating system while the computer boots.
Nothing allows you to swap purely between operating systems that way. you can use software that runs Windows in OS X with hardware virtualization, a huge step up from the software virtual machines of old.
There are three good options:
Parallels, VMWare Fusion, and VirtualBox,
the last of which has the advantage of being free.


text:
Q: Systemd Zookeeper service failed I've created the following systemd service script for running Zookeeper using Ansible:
[Unit]
Description=ZooKeeper

[Service]
User=root
Type=forking
User=zookeeper
Group=zookeeper
ExecStart=/tmp/zookeeper-3.4.9/bin/zkServer.sh start
ExecStop=/tmp/zookeeper-3.4.9/bin/zkServer.sh stop

TimeoutSec=300

[Install]
WantedBy=multi-user.target

But, while trying to run the script using sudo service zookeeper start I get the following error:
Nov 15 22:00:35 sharedservicesprovider systemd[1]: Starting ZooKeeper...
-- Subject: Unit zookeeper.service has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit zookeeper.service has begun starting up.
Nov 15 22:00:35 sharedservicesprovider systemd[15287]: zookeeper.service: Failed at step USER spawning /tmp/zookeeper-3.4.9/bin/zkServer.sh: No such process
-- Subject: Process /tmp/zookeeper-3.4.9/bin/zkServer.sh could not be executed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- The process /tmp/zookeeper-3.4.9/bin/zkServer.sh could not be executed and failed.
--
-- The error number returned by this process is 3.
Nov 15 22:00:35 sharedservicesprovider systemd[1]: zookeeper.service: Control process exited, code=exited status=217
Nov 15 22:00:35 sharedservicesprovider systemd[1]: Failed to start ZooKeeper.
-- Subject: Unit zookeeper.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel

Any hint onto why I am unable to start Zookeeper properly since I'm quite new to system services?

A: Maybe so late... but use as ExecStart:
/tmp/zookeeper-3.4.9/bin/zkServer.sh start-foreground

A: [Unit]
Description=Zookeeper
After=syslog.target
[Service]
Environment=ZOO_LOG_DIR=/zookeeper/logs
SyslogIdentifier=zookeeper
TimoutStartSec=10min
Type=forking
User=zookeeper
Group=zookeeper
ExecStart=/zookeeper/bin/zkServer.sh start
ExecStop=/zookeeper/bin/zkServer.sh stop
[Install]
WantedBy=multi-user.target

ZOO_LOG_DIR is for permission require

A: this sounds like basics to check to me
first, make sure the file exists
ls -ltrah /tmp/zookeeper-3.4.9/bin/zkServer.sh

if it doesn't find where you extracted the zookeeper startup script. On my instance, it's /opt/kafka/bin/zookeeper-server-start.sh
Then verify that the user you have specified (you've specified two users, root and zookeeper. I'm assuming the last value is what's valid/desired) can access the script and has executable rights to it.
This would be done with chown and chmod commands, respectively.


text:
Q: Symfony2 Assert\Expression annotation doesn't support Constants Generally I use Constants in all of annotation based places e.g. annotations, route and assert annotations, but in Assert\Expression it throws Variable "EntityInterface" is not valid around position 26.
Is this a bug or is a special rare case ?
<?php

    /**
     * @var string
     *
     * @ORM\Column(name="id_number", type="string", length=11, nullable=true)
     * @Assert\Expression(
     *     "this.getNationality() == EntityInterface::COUNTRY_DEFAULT_VALUE and value != null",
     *     message = "form.user.validation.id_number.blank",
     *     groups = {"personal_info"}
     * )
     * @Assert\Regex(
     *      pattern="/^([\d]{11})$/",
     *      match=true,
     *      message="form.user.validation.id_number.regex",
     *      groups = {"personal_info"}
     * )
     */
    private $idNumber;

A: Try using
/**
 * @ORM\Column(name="id_number", type="string", length=11, nullable=true)
 * @Assert\Expression(
 *     "this.getNationality() == constant('EntityInterface::COUNTRY_DEFAULT_VALUE') and value != null",
 *     message = "form.user.validation.id_number.blank",
 *     groups = {"personal_info"}
 * )
 */

instead (omitted parts of your example to focus on using constant() here).
For reference, see

*

*http://symfony.com/doc/current/components/expression_language/syntax.html#working-with-functions

*http://php.net/manual/en/function.constant.php


text:
Q: Cloudformation AllowedPattern match dots and hyphens I am trying to get a Cloudformation script to enforce a valid url path which could contain version information. I am trying to match something like:
/mypath-1.2.1
I am using

"AllowedPattern": "/[/a-zA-Z0-9_\-\.]*",
"Default": "mypath-1.2.1"

I have checked the regex against an online checker and it is fine but I am getting a "Template validation error: Template format error: JSON not well-formed" on the backslashes.
It will validate ok without the backslashes but fails on the default value not matching the regex

A: AllowedPattern is a JSON string and must follow the JSON standard for strings.
Your AllowedPattern contains escape sequences like \- and \. which are invalid in JSON.
You need to escape the black slashes in the AllowedPattern to make this valid JSON;
"AllowedPattern": "/[/a-zA-Z0-9_\\-\\.]*"

The JSON specification only allows escape sequences that follow these rules;


text:
Q: What is a reasonable timeout for firebase remote config with A/B testing for a loading a screen? In the firebase docs for remote config loading strategies it recommends that if you decide to fetch and activate remote config behind a loading screen you should add a timeout to the loading screen.
Firstly I assume I can use the fetchTimeout property below to do this?
   init() {
        #if DEBUG
        let settings = RemoteConfigSettings()
        settings.minimumFetchInterval = 0
        remoteConfig.configSettings = settings
        #else
        let settings = RemoteConfigSettings()
        settings.fetchTimeout = 10
        remoteConfig.configSettings = settings
        #endif
    }

Secondly, is there any guidance on what this timeout should be? the default is 1 minute but that is clearly too long. I have set it to 10 seconds and also see there is a note that With A/B Testing, additional time is required as the user is placed into an experiment and the experimental values are applied.
As we don't control this service, it is very hard to gauge what a good timeout number is. Even 10 seconds seems fairly long for a user to wait.
Thanks


text:
Q: Selenium WebDriver driver.getWindowHandles() in FireFox Selenium WebDriver 2.53.1 using FireFox 47.0.1 with Java:
No matter what driver1.getWindowHandles() returns only one handle. In Chrome, the code below works fine and returns the correct number of handles.
Is there anyway to return multiple window handles this way using firefox?
    driver1 = new FirefoxDriver();

    // LOOP TO OPEN AS MANY TABS AS YOU WISH
    for(int i = 0; i < TAB_NUMBER; i++) {
       driver1.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
       // SLEEP FOR SPLIT SECOND TO ALLOW DRIVER TIME TO OPEN TAB
       Thread.sleep(100);
     }
    // STORE TAB HANDLES IN ARRAY LIST FOR EASY ACCESS
    ArrayList tabs1 = new ArrayList<String> (driver1.getWindowHandles());

    System.out.println(tabs1);


text:
Q: How does Spring convert Java to JSON? In my Spring Boot project, I just return a list directly. Then I can see the JSON response in Postman. I didn't do anything to convert the Java object to JSON. How does it work? Is JSON the default way to exchange data for Java?
Here is an controller example.
@GetMapping("/")
@Secured({"ROLE_ANONYMOUS", "ROLE_REGULAR"})
List<Project> allProducts() {
    return projectService.getAllProjects();
}

Here is the dependency part of my pom.xml
<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.9</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.7</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.19</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.2</version>
    </dependency>
    <dependency>
        <groupId>jakarta.xml.bind</groupId>
        <artifactId>jakarta.xml.bind-api</artifactId>
        <version>4.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jta-atomikos</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.kafka</groupId>
        <artifactId>spring-kafka</artifactId>
        <version>2.8.5</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>2.0.2</version>
    </dependency>
</dependencies>

A:
How does it work?

By default Spring will use Jackson to convert your object graph to JSON.

Is JSON the default way to exchange data for java?

No, it isn't.  Java doesn't define a default way to exchange data.

A: The DispatchServlet process calls HttpMessageConverter for serialization


text:
Q: iOS: Split up Key - Value joined by Equal sign from NSString I have following string;
    key = value = 123

I want to split up this string into two strings "key" and "value = 123". What is the best way to do this?
I was thinking of using componentsSeparatedByString by "=" and then combine last two components but for me, "key =" is fixed but right side it can be any value like "value1 = 123, value2 = 123" so I can't use this approach.
Basically if there is a good way to get key (all characters before first = sign) and after first = sign whatever remained is the value then it would be really helpful.

A: Use the NSScanner!
       NSString *key, *value;
       NSScanner *scanner = [NSScanner scannerWithString:yourstring];
       [scanner scanUpToString:@"=" intoString:&key];
       [scanner scanString:@"=" intoString:nil];
       value = [yourstring substringFromIndex:scanner.scanLocation];

       key = [key stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
       value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

String "key = value1 = 123, value2 = 456" would result in key = "key" and value = "value1 = 123, value2 = 456".

A: I'm not sure if I fully understand your question? The following code will fetch the key, regardless of what it is and then strip that from the original string to get the value.
NSString *strKeyKalue = @"key = value = 123";
NSArray *aryKeyValue = [strKeyKalue componentsSeparatedByString:@" = "];
NSString *key = [aryKeyValue objectAtIndex:0];
NSString *values = [strKeyValue substringFromIndex:[key length] + 3]; // Remember ' = '

So max_int = 17477575 would result in key = max_int and value = 17477575

A: Your explanation is pretty confusing.
If you want to separate just the key from value = 123, use commentsSeperatedByString and then
NSString *newString = [NSString stringWithFormat"@"%@ = %@", string1, string2];


text:
Q: Viewstate exception Validation of viewstate MAC failed In our log files I find the following exception. (ASP.NET, Sitecore 6.6). Any ideas why this happens?
I referred to this post. My app is not in a server farm. Also this does not happen with every postback.
7776 02:11:53 ERROR Application error.
Exception: System.Web.HttpException
Message: Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.
Source: System.Web
at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError)
at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString, Purpose purpose)
at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter2 formatter, String serializedState, Purpose purpose)
at System.Web.UI.HiddenFieldPageStatePersister.Load()
at System.Web.UI.Page.LoadPageStateFromPersistenceMedium()
at System.Web.UI.Page.LoadAllState()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

Nested Exception

Exception: System.Web.UI.ViewStateException
Message: Invalid viewstate.
Client IP: xxx.xxx.xxx.201
Port: <PORT>
Referer: <URL>
Path: /<PAGE>
User-Agent: Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11
ViewState: /wEPDwUJMzY0OTY5Mjg5D2QWAgIFEGRkFgQCAw9kFgJmD2QWAmYPZBYCAg4PZBYCZg9kFgQCAw8PFgQeFUN1cnJlbnRTZWxlY3Rpb25WYWx1ZQUkMDAwMDAwMDAtMDAwMC0wMDAwLTAwMDAtMDAwMDAwMDAwMDAwHhRDdXJyZW50U2VsZWN0aW9uVGV4dAUVQWxsIENhdGVnb3JpZXMgKDY5NTEpZBYCAgEPZBYCZg9kFgICAQ8UKwACDxYGHgRUZXh0BRVBbGwgQ2F0ZWdvcmllcyAoNjk1MSkeBF8hU0ICAh4IQ3NzQ2xhc3MFB1Rvb2xCYXJkEBYBZhYBFCsAAmRkDxYBZhYBBXdUZWxlcmlrLldlYi5VSS5SYWRDb21ib0JveEl0ZW0sIFRlbGVyaWsuV2ViLlVJLCBWZXJzaW9uPTIwMTIuMi42MDcuMzUsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49MTIxZmFlNzgxNjViYTNkNBYCAgIPFCsAAWQWAgIBDxQrAAIUKwACFCsAAg8WBB8EBQdUb29sQmFyHwMCAmQPFCsAARQrAAIPFgYfAgUVQWxsIENhdGVnb3JpZXMgKDY5NTEpHgVWYWx1ZQUkMDAwMDAwMDAtMDAwMC0wMDAwLTAwMDAtMDAwMDAwMDAwMDAwHghTZWxlY3RlZGdkZA8UKwEBZhYBBXNUZWxlcmlrLldlYi5VSS5S...

A: please check this link
Root Cause
This exception appears because Controls using DataKeyNames require Viewstate to be encrypted. When Viewstate is encrypted (Default mode, Auto, is to encrypt if controls require that, otherwise not), Page adds  field just before closing of the  tag. But this hidden field might not have been rendered to the browser with long-running pages, and if you make a postback before it does, the browser initiates postback without this field (in form post collection). End result is that if this field is omitted on postback, the page doesn't know that Viewstate is encrypted and causes the aforementioned Exception. I.E. page expects to be fully-loaded before you make a postback.
And by the way similar problem is with event validation since __EVENTVALIDATION field is also rendered on the end of the form. This is a security feature that ensures that postback actions only come from events allowed and created by the server to help prevent spoofed postbacks. This feature is implemented by having controls register valid events when they render (as in, during their actual Render() methods). The end result is that at the bottom of your rendered  tag, you'll see something like this: . When a postback occurs, ASP.NET uses the values stored in this hidden field to ensure that the button you clicked invokes a valid event. If it's not valid, you get the exception above.
The problem happens specifically when you postback before the EventValidation field has been rendered. If EventValidation is enabled (which it is, by default), but ASP.net doesn't see the hidden field when you postback, you also get the exception. If you submit a form before it has been entirely rendered, then chances are the EventValidation field has not yet been rendered, and thus ASP.NET cannot validate your click.
Workarounds
1. Set enableEventValidation to false and viewStateEncryptionMode to Never as follows:

This has the unwanted side-effect of disabling validation and encryption.  On some sites, this may be ok to do, but it isn't a best practice, especially in publicly facing sites.

A: I have similar issue in my recent project.When I tried to find some help from google, the things that most people discussed are the following
Add machine key in web.config
<system.web>
    <machineKey validationKey="..." decryptionKey="..." validation="SHA1" />
</system.web>
Set EnableViewStateMAC=False in web.config
<system.web>
         <pages enableViewStateMac="False"/>
</system.web>
But all above solution did not work for me. Whenever I try to open application with IP address it works fine but if I tried open application with domain name it showed me "Viewstate MAC failed" error. I dig down to find out what an issue and finally I found solution, this error occurs when browser does not accept cookie from server.
Godaddy provides feature for domain forwarding with masking. One of my colleague set that feature on our application domain, IE and Safari have security Level that they does not accept cookies from third parties and Advertiser, therefore both these browser generated "Viewstate MAC failed" error.
You can set Security Level to Accept all cookie in IE
Tools > Internet Options > Privacy
and Move Setting slider bottom for the Value "Accept all Cookie".
Hope this solution will help other to get out of asp.net legacy error "Viewstate MAC failed".


text:
Q: How to set AdSense Cookie after user approves cookies To implement AdSense code I have added following in between the html head tags as requested by AdSense:
<script data-ad-client="ca-pub-xxxxxxxxxxx" async
  src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

On page load adsense sets a cookie named .doubleclick.net.
I want the users to click on a button (approve cookies) before the cookie is set. How would you code that in javascript?
Since this needs to be in the head, I have no clue how to do this.
I am guessing this is not viable:
<head>
    <script>
        $('#Approve-Cookie').click(function(){
            <script data-ad-client="ca-pub-xxxxxxxxxxx" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
        });
    </script>
</head>
<body></body>

Or maybe something like this?
$('#Approve-Cookie').click(function(){
    $.ajax({
      url: "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js",
      dataType: "script",
      async: true,
      success: callback,
      scriptAttrs: { data-ad-client="ca-pub-xxxxxxxxxxx" }
    });
}

But can't get the scriptAttrs to work.

A: I believe the solution to my own problem is following:
$('#Approve-Cookie').click(function(){
    $.ajax({
      url: "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js",
      dataType: "script",
      async: true,
      scriptAttrs: { "data-ad-client": "ca-pub-xxxxxxxxxxx" }
    });
});


text:
Q: Convert quarterly data to monthly data I got the following datatable with quarterly data:
set.seed(1)
DT <- data.table(dates=c(as.Date("1983-03-31"), as.Date("1983-06-30"), as.Date("1983-09-30"),
               as.Date("1983-12-31"), as.Date("1984-03-31"), as.Date("1984-06-30"),
               as.Date("1984-09-30"), as.Date("1984-12-31"), as.Date("1985-03-31"),
               as.Date("1985-06-30"), as.Date("1985-09-30")),
       var=rnorm(11))
DT
# desired outout: (extract)
data.table(dates=c(as.Date("1983-01-31"), as.Date("1983-02-28"), as.Date("1983-03-31")),quarter=rep(as.Date("1983-03-31"),3),
               var=rep(-0.6264538,3))

I would like to create a monthly dataset out of the quarterly one, by copying the respective quarterly values 3 times for the corresponding months. The corresponding months in Date format must be created first, as they should be used later on in the analysis. Can this be done easily with some sort of join? I only found ways to do it vice-versa, i.e. from monthly into quarterly by aggregation.
Preferably by using datatable. Thanks for any hints.

A: Here's a data.table option with some lubridate functions thrown in. Perhaps there's a more direct way, but this would probably do the job, too:
library(lubridate)
DT <- DT[rep(1:.N, each = 3)]
DT[, quarter := dates]
DT[, dates := {day(dates) <- 1; dates}]
DT[, dates := {month(dates) <- month(dates) - 1:(-1); dates}, by = quarter]
DT[, dates := dates -1]

We first replicate each row three times. Then we create a copy of the dates column for the quarters. Next, we set the date to the first day of the month. Then we subtract 1, 0, -1 months from each date and finally subrtact one day to arrive at the last day of the previous month.
head(DT)
#       quarter        var      dates
# 1: 1983-03-31 -0.6264538 1983-01-31
# 2: 1983-03-31 -0.6264538 1983-02-28
# 3: 1983-03-31 -0.6264538 1983-03-31
# 4: 1983-06-30  0.1836433 1983-04-30
# 5: 1983-06-30  0.1836433 1983-05-31
# 6: 1983-06-30  0.1836433 1983-06-30

A: You can enumerate the desired dates and do a rolling join:
DT[.(seq(as.IDate("1983-02-01"), as.IDate("1985-10-01"), by="month") - 1L),
  on=.(dates), roll=-Inf]

         dates        var
 1: 1983-01-31 -0.6264538
 2: 1983-02-28 -0.6264538
 3: 1983-03-31 -0.6264538
 4: 1983-04-30  0.1836433
 5: 1983-05-31  0.1836433
 6: 1983-06-30  0.1836433
 7: 1983-07-31 -0.8356286
 8: 1983-08-31 -0.8356286
 9: 1983-09-30 -0.8356286
10: 1983-10-31  1.5952808
11: 1983-11-30  1.5952808
12: 1983-12-31  1.5952808
13: 1984-01-31  0.3295078
14: 1984-02-29  0.3295078
15: 1984-03-31  0.3295078
16: 1984-04-30 -0.8204684
17: 1984-05-31 -0.8204684
18: 1984-06-30 -0.8204684
19: 1984-07-31  0.4874291
20: 1984-08-31  0.4874291
21: 1984-09-30  0.4874291
22: 1984-10-31  0.7383247
23: 1984-11-30  0.7383247
24: 1984-12-31  0.7383247
25: 1985-01-31  0.5757814
26: 1985-02-28  0.5757814
27: 1985-03-31  0.5757814
28: 1985-04-30 -0.3053884
29: 1985-05-31 -0.3053884
30: 1985-06-30 -0.3053884
31: 1985-07-31  1.5117812
32: 1985-08-31  1.5117812
33: 1985-09-30  1.5117812
         dates        var

This rolls to the nearest later date, so if your original data has gaps, they'll need to be handled differently (eg, filling with NA first).


text:
Q: Spring Integration Doubts: CRUD operations and sharing events between components I am currently developing a simple Spring web app using Spring integration framework. I have read about the enterprise integration patterns, purpose, benefits... I have get rid out of the ServiceLayer and delegated the app workflow to the integration framework. But I have come across some design issues where I am stuck and I would appreciate some light in terms of design. Here below I ll try to explain them, thanks in advance.
1. CRUD operations with Spring Integration Framework
Lets say you have 2 endpoints connected through a direct channel, 1 endpoint receives requests and the other one processes those requests. I don't want to talk from the implementation perspective but from the design (as I have stated before) but in order to clarify it out, image that you implement the receiving endpoint as a RestController connected to a Gateway and the other endpoint as an ServiceActivator connected to a DB adapter.
Now, there are 4 basic operations the user can request, Create, Read, Update and Delete (basic CRUD). Since the receiver endpoint can only execute one method (handleMessage method), what is the correct way to multiplex the 4 operations?

*

*Adding some kind of tag to the message header? It seems ugly to me and besides the receiver endpoint will have to implement a block of if-else. It would be easier to just connect the controller to an interface and call the methods and get rid of spring integration.

*Create 4 ServiceActivator connected to the same DB? I don't like it either, imagine if you had 30 operations instead of 4.

*Any other solution I have not found yet? For example, send each operation through a different channel, so that you would have 4 channels. You can do this from the Gateway point of view but the problem is that the ServiceActivator can only have 1 inbound channel.

2. Sharing events between endpoints with Spring Integration Framework
Lets say you have a Gateway connected to a Transformer.The transformer inits a thread in which parses some data and send it to the next endpoint when finishes.
Now, the Gateway client needs to know the status of the request it sent through the channel (since the Gateway knows nothing about the Transformer or its implementation they shouldn't share anything). How can be it accomplished since the transformer only has 1 inbound channel and 1 output channel and there is no way to publish results back through a third channel? In essence, the question is, how do you share event without coupling the endpoints or breaking the integration patterns architecture?
P.D.:Please avoid no clean answers such as static shared objects, thanks.

A: M-m-m. Your concern somehow isn't clear.
When you had a ServiceLayer before, I'm pretty sure a lot of methods for particular operation didn't disturb you. So, not sure why you are so worry about message channel distinguishing for operations when you switched to Messaging architecture.
At the same time I guess that @Cotroller with GET, POST, DELETE etc @RequestMapping for its methods don't concern you again.
That is just a bit inconvenience to have extra objects in your application in face of MessageChannels in between your endpoints. But at the same time it is a bonus when you start to think about your application as a bunch of message flows, where each of them is separated my the MessageChannel and you can modify any flow not affecting any other. Plus don't forget that with the MessageChannel you simply can go to the distributed mode, when your business logic is the same, but messages are travel over the network for target services or other purposes.
So, IMO I's have @MessagingGateway to call from the @Controller and each gateway's method would be mapped to particular MessageChannel.
Thanks to annotation model you could have only one target service, but with method for each CRUD operation marked with the @ServiceActivator for particular MessageChannel:
@MessagingGateway
public interface CrudGateway {

   @Gateway(requestChannel = "getChannel")
   Object get(Object id);

   @Gateway(requestChannel = "saveChannel")
   Object save(Object object);

   @Gateway(requestChannel = "deleteChannel")
   boolean delete(Object object);

}

...

@Service
public class CrudService {

   @ServiceActivator(inputChannel = "getChannel")
   public Object get(Object id) {
       // SELECT
   }

   @ServiceActivator(inputChannel = "saveChannel")
   public Object save(Object object) {
       // INSERT or UPDATE
   }

   @ServiceActivator(inputChannel = "deleteChannel")
   public boolean delete(Object object) {
       // DELETE
   }

}

For your second question there is some answer as well.
Consider to use PublishSubscribeChannel as an output of that transformer.
On the other hand there is RecipientListRouter to distribute incoming message to several recipients - channels, of course.


text:
Q: If X is measurable in the completion of F, does there exist F-measurable Y such that X = Y a.s.? Let the underlying probability space be $(\Omega, \mathcal{A}, P)$. Suppose I have a sub-$\sigma$-field $\mathcal{F} \subset \mathcal{A}$ and a random element $X$ such that $X$ is measurable in the completion of $\mathcal{F}$ with respect to $P$.
Does there exist a random element $Y$ such that $Y$ is $\mathcal{F}$-measurable and $X = Y$ a.s.? If not in general, what are sufficient conditions for this to be the case? (I think if $X$ takes values in a separable metric space, it is true, for example.)

A: Oh, found my own answer. It's in Kallenberg's Foundations of Modern Probability, Lemma 1.25.
A sufficient condition is for $X$ to take values in a Borel space.
Then a proof can proceed by showing it for indicator functions measurable with respect to the completion, then approximation of any measurable function by simple functions that agree a.s.


text:
Q: Apache LB and huge amount of close_wait connections I use apache as a loadbalancer for servers with some java apps. On the apache host I saw huge number of close_wait state which was around 2500. Is it a problem with apache itself or with app on the other side?
RHEL 7.9
apache 2.2.15


text:
Q: How to get css and django working on live server You guys were able to help me with last issue involving Django so I thought I'd ask another that has been killing me for the past couple days!
I have a small one app project with about 6 different pages, and I can get them to show however my style.css is not "showing" on the web page, I have followed countless guides including the Django's website and I just can't seem to get this working correctly. Here are some files that I think are relevant:
public_html/mysite/nfl/templates/home.html:
{% load staticfiles %}
<!DOCTYPE HTML>
 <html lang="en">
  <head>
   <title> Draftr Home Page </title>
   <meta charset="utf-8">
   <meta name = "viewport" content="width=device-width, initial-scale=1">

<!-- Using Bootstrap 3 framework with permission from getbootstrap.com -->
        <!-- Latest compiled and minified CSS -->
        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

    <!-- Latest compiled JavaScript -->
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

    <!-- Custom Style Sheet -->
    <link href="{% static 'style.css' %}" rel="stylesheet" media="screen">

style.css is located here public_html/mysite/nfl/static AND /home/gobelogic/public_html/mysite/static(alongside admin/)
/home/gobelogic/public_html/mysite/mysite:
import os.path
import sys

PROJECT_ROOT = os.path.normpath(os.path.dirname(__file__))
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

INSTALLED_APPS = (
#other
'django.contrib.staticfiles',
'nfl'
)

TEMPLATE_DIRS =
     "nfl/templates",

)

STATICFILES_DIRS = (
    '/home/gobelogic/public_html/mysite/nfl/static',
)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static')

Ok I'm going to try and explain how I think django handles static files, please correct me where I'm wrong:
so in settings.py django is locating all static directories in my project and placing their contents in a single directory static/ next to manange.py(which is done when I run manage.py collectstatic
in the html file I tell django to load all the static files so that i can use them at the top by using {% load staticfiles %} and then i say which one in particular by using <link href="{% static 'style.css' %}" rel="stylesheet" media="screen"> by doing this, django uses the settings.py(?) to find where I put these static files and then loads up the stylesheet that way
Again I am running this on my production server so none of this is run through django built in server, idk if that matters or not
Thanks for any help
EDIT using django 1.8

A: Since you are not using Django internal server (rightly so), you need to make your production web server aware of the static file location. There is an example in Django docs for Apache (https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/modwsgi/#serving-files). Even if you are not using apache, generally you need to make sure that /static/ or whatever your STATIC_URL points to is served from the place where your STATIC_ROOT points to.