text:
Q: condense if, else JS with similar condition rules trying to find a way to condense this. wasnt sure of the best way to do it. basically if criteria is met i display an alert with a parameter that is the message. i was thinking of maybe trying it in function. this is part of a larger function react component. i was also thinking if i could find a way to condense the else if's i could use a ternary. thanks in advance for the assistance.
const handleUpdatePassword = () => {
const allFilled = !reject(passwords).length;
const passwordsMatch = newPassword === conPassword;
const isDifferent = curPassword !== newPassword;
const meetsPasswordRequirements = validatePassword();
const usesName = isUsingName();
const usesUserID = isPartOfUserID();
const isValidPassword = meetsPasswordRequirements && isDifferent;
 if (allFilled) {
  if (!isDifferent) {
    Alert.alert(difPassWord);
  } else if (!passwordsMatch) {
    Alert.alert(noMatch);
  } else if (!meetsPasswordRequirements) {
    Alert.alert(pasReqs);
  } else if (usesName || usesUserID) {
    Alert.alert(pasName);
  }
} else {
  Alert.alert(fieldNotComplete);
}
if (isValidPassword) {
  changePasswordPost(
    {
      userId,
      curPassword,
      newPassword
    },
        partyId
  );
}

};

A: You can create an array of objects for your validation rules, each containing a function which returns a boolean indicating whether that validation passes, and a string with the error message to display.
Then loop over the rules array and alert the message for the first rule that returns false. If they all return true, do the post.

A: You can split each if statement into a function, then chain them. For example
// here we make a closure to validate, and return a Promise
// condition can be a function
const validate = (condition, error) => ()=> new Promise((res, rej)=>{
   if(condition()){
       res();
   }else{
       rej(error);
   }
});

const handleUpdatePassword = () => {
   const validateFieldsComplete = validate(
        ()=>!reject(passwords).length,
        fieldNotComplete
   );
   const validateDifPassword = validate(
        ()=> curPassword !== newPassword,
        difPassWord
   );
   // ...
   validateFieldsComplete()
       .then(validateDifPassword)
       .then(...)
       .catch(Alert.alert)
}

It would be much cleaner with pipe. You can take a look at ramda. Or if you are intrested in functional way, you might consider using Monad.

A: I'd recommend DRYing up the Alert.alert part since all branches have that in common, and just come up with an expression that evaluates to the alert message. Compactness isn't always everything, but if you want it, then nested conditional operators can fit the bill. I'm also rearranging your conditions so that it can be a flat chain of if/elses:
const message
  = reject(passwords).length            ? fieldNotComplete
  : curPassword === newPassword         ? difPassWord
  : newPassword !== conPassword         ? noMatch
  : !validatePassword()                 ? pasReqs
  : (isUsingName() || isPartOfUserID()) ? pasName
                                        : null;
const isValid = !message;
if (!isValid) {
  Alert.alert(message);
}

(feel free to use any other sort of code formatting pattern; nested conditionals always look awkward no matter which pattern you use, IMO.)
Edit:
Also inlined conditionals which will short-circuit evaluation and make it even more compact.

A: I'd setup a validations object that has the tests and error messages and then loop over it. If validation fails, it'll throw the last validation error message. Using this method, you only have to maintain your tests in one place and not mess with a block of conditional statements.
const handleUpdatePassword = () => {
  const validations = {
    allFilled: {
      test() {
        return newPass && oldPass
      },
      error: 'Must fill out all fields'
    },
    correct: {
      test() {
        return curPass === oldPass
      },
      error: 'Incorrect password'
    },
    [...]
  }

  const invalid = () => {
    let flag = false
    for (let validation in validations) {
      if (!validations[validation].test()) {
        flag = validations[validation].error
      }
    }
    return flag
  }

  if (invalid()) {
    Alert.alert(invalid())
  } else {
    changePasswordPost(
      {
        userId,
        curPass,
        newPass
      },
      partyId
    )
  }
}

A: hi everyone this was the method i used for a solution
const messages = [
  {
    alertMessage: difPassWord,
    displayRule: different()
  },
  {
    alertMessage: noMatch,
    displayRule: match()
  },
  {
    alertMessage: pasReqs,
    displayRule: validatePassword()
  },
  {
    alertMessage: pasName,
    displayRule: !isUsingName() || !isPartOfUserID()
  }
];

if (allFilled) {
  const arrayLength = messages.length;
  for (let i = 0; i < arrayLength; i++) {
    if (messages[i].displayRule === false) {
      Alert.alert(messages[i].alertMessage);
    }
  }


text:
Q: PayPal guest checkout not available in certain countries I'm integrating a react native app with PayPal's REST API and all has gone quite smoothly. However, when I click through, the buyer does not get the option to complete the purchase as a guest. I'm using a v1/payments integration; The transaction works if I login or create an account, but is it possible to let buyers pay without having to login?
I have researched and done most things people say you should do, like having a business account, enable guest payments, etc.
I tried using this github as an approach to using REST API, it works fine but if it helps: https://github.com/tonynguyenit18/paypal-RN-intergration

A: This isn't a REST API issue. You are getting the expected behavior of the PayPal Checkout in general. Guest checkout is available on a case-by-case basis. Very many factors -- such as the country of the buyer, IP address, repeated payment attempts, and testing payments to one's own account in the live environment -- are used to determine guest eligibility.
When a checkout is not guest-eligible, the buyer can still enter their card details but will also need to choose a password to create an account in the process.
Again, this is just how the PayPal Checkout works in general.
By the way, the v1/payments API is deprecated. You should use 'Create Order' and 'Capture Order', documented here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a (maybe official) checklist and guide for submitting an app to the App Store? I submitted one almost 2 years ago and remember next to nothing. Just that it was very hard and that about a gazillion things had to be considered.
Now we have a universal iPhone / iPad binary.
Maybe someone can point out some resources which give a good and quick overview of what has to be checked / done?
Some things that come to mind for a useful checklist:

*

*Make sure NSZombiesEnabled is NO

*... what else?

A: https://ontestpad.com/library/201/ios-app-store-submission-checklist

A: Another important thing that hasn't been mentioned is that Xcode 4 can perform some validation to your Application before submitting it to the App Store.
After you have archived the App, you can go to Xcode's Organizer and "Validate" the App. That can save you a lot of valuable time.
Cheers.

A: Check this blog post, it was useful for me: blogpost
It contains very detailed lists for submitting apps, and also for starting a new app.
It contains such a useful points:

In the "Edit Scheme" section of Xcode, "Archive" should be set to
  "Release". Release builds must hide log statements and turn off any
  test code/test screens used for development.
NOTE: Due to compiler optimizations, release builds can sometimes
  function differently than debug builds. It is best to start testing
  release builds a few days before the release to the App Store in order
  to capture any possible issues.
  Make sure the app is communicating with the correct production servers
  (using HTTPS).
Make sure all test screens are hidden.
Make sure no sensitive data is printed to the console.
Make sure Analytics is working with the correct production account.
Make sure services such as Urban Airship are working with the correct
  production account.

Also I found other useful link  now:
APNS

Make sure that APNS certificate includes your app's BundleID.
You have created distribution APNS certificate.
Your server is using distribution APNS certificate.
Check that notifications are working on different iOS versions (pay
  attention to iOS8 where API was changed).     Versioning
Do not hardcode anywhere in sources things like isBeta=YES or
  DEBUG=YES.
Make sure that the app icon or name doesn't contain "beta" word.
Update app version and build version. Never hardcode version inside
  app (use CFBundleVersion instead).
IMPORTANT Make sure that the new release is installed over the old
  version in the correct way:
** Install app from AppStore. Create ad-hoc build and install it over the old version.
** Check that data from NSUserDefaults is read in the correct way (app doesn't crash trying to read non-existing keys).
** Check that user doesn't lose any of his info after update.


text:
Q: How to add registration information to my page in rails I want to the username to a view.
My devise model is: Player
For example:
Welcome [Username] to the website.

I am using Rails 4, Thanks.

A: In your view/layout add following:
Welcome <%= current_player.username %> to the website.


text:
Q: How to make a piece code function only once during launch? My Primary Goal: LoginActivity is the default activity to be launched. I want my homeactivity to be launched at first WITHOUT using android.manifest due to some issues I can't change or mess with it. In my homeactivity I want a button or a floating action button to lead to the LoginActivity back.
Explanation of how I attempted to do this:
I am using SendBird SDK's sample program to build my app over it. But I don't want the LoginActivity of the SendBird SDK to load at first I instead want my HomeActivity to load first so I used the following code in my LoginActivity.java onCreate.
LA#
new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        Intent startActivity = new Intent(LoginActivity.this, HomeActivity.class);
        startActivity(startActivity);
        finish();
    }
}, 0001);

In my home activity I made a floating action button to lead back to the LoginActivity using intent
Intent intent = new Intent(HomeActivity.this, LoginActivity.class);
        startActivity(intent);

Then I executed the application and as expected the HomeActivity appeared first. Then I clicked the floating action button and again HomeActivity appeared. I know the problem that this is happening because of that code (LA#) in LoginActivity.java because when the Floating Action Button leads to Login Activity that code (LA#) tells the LoginActivity to again go back to HomeActivity so it is a continuous cycle. I now want to know how can I make that piece of code (LA#) in LoginActivity work only once during launch so that from next time onwards it doesn't go back to HomeActivity and just stays at LoginActivity.
Or is there any alternate way to achieve my goal?

A: Simple solution would be to have a boolean in a sqlite database, when the app first starts up, load the initial activity, set that boolean to true if the activity succeeds, then store that in the database, every time the app loads up after that, check that value in the database and if it's true, skip over that activity; Hacky but straightforward enough to implement.


text:
Q: Can I just copy Windows from one SSD to another and use it? To upgrade my windows SSD, can I just use a linux live version and copy the whole content over to the new (and bigger) SSD?
Or are there easier ways? I fear that the boot-sector (and whatever else there could be) won't be copied and I will run into issues.

A: Assuming you leave the original drive intact until you're sure everything is working other than lost time there shouldn't be any harm in trying. You can always wipe the SSD and start over again.
You will want to make sure that you copy all of the boot sector/partition and partition structure to the new drive. This can be accomplished with software like Clonezilla but you could also just do it from a Linux live CD/USB system using the dd command to copy the entirety of the old drive bit for bit onto the new drive. This all assumes that the new drive is at least as big or bigger than the old drive. Note that after you're done if you want to use the additional space on the drive you'll have to resize/extend your NTFS partition.
Really, this is probably a good opportunity to do a fresh installation of Windows which is what I'd recommend instead. My experience is that you'll spend more time trying to make this work than if you just did a fresh install, reinstalled your applications, and copied your data back over from the old drive to the new one. Because of the way Windows activates on systems now your system should automatically activate even on a fresh installation.

A: Best way is called "Bare Metal Restore".
You do full backup to .vhdx file (which is block-oriented copy), boot from PE (Windows disk or MSDART) and then restore it.
https://blogs.technet.microsoft.com/askcore/2011/05/12/bare-metal-restore/
I did it several times to move windows to another drive. I then expanded new partition using disk manager.
When booting from PE you may face some troubles using UI restore. In this case you may open console and use wbadmin (https://technet.microsoft.com/en-us/library/dd767786.aspx)
https://technet.microsoft.com/ru-ru/library/cc742118(v=ws.11).aspx

A: No. You will need to clone it using something like Clonezilla or Macrium Reflect Free. They will also allow you to adjust the partition sizes.
From my personal experience, when only swapping the SSD, there should be no need to re-authorize the windows license.
In rare occasions, one might need to "Generalize" their install before cloning but probably not an issue when simply putting the cloned drive into the same machine.


text:
Q: error in going from one page to another using intents import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;

public class MainActivity extends Activity {

DataHandlerSignIn handler1;
ImageButton signin;
EditText etxt1,etxt2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    etxt1=(EditText) findViewById(R.id.user);
    etxt2=(EditText) findViewById(R.id.pass);
    signin=(ImageButton) findViewById(R.id.signup);

    signin.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {

            Intent ii = new Intent(MainActivity.this,SignUp.class);
            startActivity(ii);

        }

    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

}
the stack trace is
 E/AndroidRuntime(1644): FATAL EXCEPTION: main
 E/AndroidRuntime(1644): java.lang.RuntimeException: Unable to start      activity ComponentInfo{simple.smile.my_dairy/simple.smile.my_dairy.SignUp}:   java.lang.NullPointerException
 E/AndroidRuntime(1644):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
 E/AndroidRuntime(1644):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
 E/AndroidRuntime(1644):    at android.app.ActivityThread.access$600(ActivityThread.java:141)
 E/AndroidRuntime(1644):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
 E/AndroidRuntime(1644):    at android.os.Handler.dispatchMessage(Handler.java:99)
 E/AndroidRuntime(1644):    at android.os.Looper.loop(Looper.java:137)
 E/AndroidRuntime(1644):    at android.app.ActivityThread.main(ActivityThread.java:5039)
 E/AndroidRuntime(1644):    at java.lang.reflect.Method.invokeNative(Native Method)
 E/AndroidRuntime(1644):    at java.lang.reflect.Method.invoke(Method.java:511)
 E/AndroidRuntime(1644):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
 E/AndroidRuntime(1644):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
 E/AndroidRuntime(1644):    at dalvik.system.NativeStart.main(Native Method)
 E/AndroidRuntime(1644): Caused by: java.lang.NullPointerException
 E/AndroidRuntime(1644):    at simple.smile.my_dairy.SignUp.onCreate(SignUp.java:30)
 E/AndroidRuntime(1644):    at android.app.Activity.performCreate(Activity.java:5104)
 E/AndroidRuntime(1644):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
 E/AndroidRuntime(1644):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
 E/AndroidRuntime(1644):    ... 11 more

SignUp Activity code is
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class SignUp extends Activity {

ImageButton click;
DataHandlerSignIn handler;
EditText et1,et2,et3,et4,et5;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sign_up);

        et1 = (EditText) findViewById(R.id.name12);
        et2 = (EditText) findViewById(R.id.age12);
        et3 = (EditText) findViewById(R.id.date12);
        et4 = (EditText) findViewById(R.id.passed12);
        et5 = (EditText) findViewById(R.id.repassed12);

    click.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {

            String name1=et1.getText().toString();
            String age1=et2.getText().toString();
            String dob1=et3.getText().toString();
            String password1=et4.getText().toString();
            String password2=et5.getText().toString();

            if(password1.equals(password2))
            {
            handler = new DataHandlerSignIn(getBaseContext());
            handler.open();
            long id = handler.insertData(name1, age1, dob1, password1);
            Toast.makeText(getBaseContext(), "Saved",1000).show();
            handler.close();
            Intent hello = new Intent(SignUp.this,MainActivity.class);
            startActivity(hello);
            }
            else
            {
                   Toast.makeText(getBaseContext(),"passwords donot match plzz try again",3000).show();
                   et1.setText("");
                   et2.setText("");
                   et3.setText("");
                   et4.setText("");
                   et5.setText("");
            }

        }

    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_sign_up, menu);
    return true;
}

 }

I have tried going from one page to another using intents. But I am not successful. I Think I have used the correct syntax. but why did the error occur. Will anyone please tell me the error in it and how to resolve it.
Thanks in advance.

A: You never initialize your ImageButton :
click.setOnClickListener(new OnClickListener()...
// click is null, calling a method on it will cause a crash

You need to initialize ImageButton click above :
click = (ImageButton)findViewById(R.id.click);
click.setOnClickListener(new OnClickListener()...

A: Initialize your click imageButton for SignUp Activity.
click =(ImageButton) findViewById(R.id.click);

on onCreate()


text:
Q: using regular expressions in groovy I don't understand how I should use regular expressions in groovy despite it having several operators to work with it.
import java.util.regex.*

def line = "Line with 1 digits"

Pattern p = Pattern.compile("\\d+")
Matcher m = p.matcher(line)
if (m.find()) { // true
    println "found digit"
} else {
    println "not found digit"
}

if (line ==~ /\\d+/) { // false
    println "found"
} else {
    println "not found"
}

if (line =~ /\\d+/) { // false
    println "found"
} else {
    println "not found"
}

In my example in java code it found that there is a digit in the string successfully. However in groovy it was not able to do it.
What is wrong?

A: See this slashy string reference:

Slashy strings are particularly useful for defining regular expressions and patterns, as there is no need to escape backslashes.

You need to use a single backslash with \d in /\d+/ Groovy slashy strings defining a regex.
if (line =~ /\d+/) { // false
    println "found"
} else {
    println "not found"
}

The line =~ /\d+/ checks if a line contains one or more digits.
The line2 ==~ /\d+/ checks if the whole string consists of only digits.
See IDEONE demo.
Also, see some more information about using regex in Groovy at regular-expressions.info.

A: You can use find
if (line.find(/\d+/)) {
    println "found"
} else {
    println "not found"
}

A: Just as an addition if you need a Boolean, like
def myBool = line.find(/\d+/)

this returns null, if it cannot find it - and the number it matches otherwise.
Same with line =~ /\d+/ that returns a java.util.regex.Matcher.
So to get a Boolean directly you can for example extend the Regex and use matches:
def myBool = line..matches(/.*\d+.*/))


text:
Q: Neighbor discovery in contiki
Actually i dont know how to deal with neighbor_recv function. I am not receiving any packet, as was receiving in broadcast-example. All values used in this code are randomly initialized. Moreover I want to store neighbor of each node. Currently I am having 3 telosb motes.

#include "contiki.h"
#include "net/rime/rime.h"
#include "random.h"
#include "node-id.h"
#include "dev/button-sensor.h"

#include "dev/leds.h"

#include <stdio.h>

struct adv_msg {
  uint16_t val;
};

    /*------------------------------------------------------------------------    ---*/
PROCESS(neighbor_process, "Neighbor example");
AUTOSTART_PROCESSES(&neighbor_process);
/*------------------------------------------------------------------------    ---*/

static void
neighbor_recv(struct neighbor_discovery_conn *c, const linkaddr_t *from)
{
printf("message received from %d.%d: '%s'\n",
         from->u8[0], from->u8[1], (char *)packetbuf_dataptr());
}

static const struct neighbor_discovery_callbacks cb ={neighbor_recv};

static struct neighbor_discovery_conn neighbor;
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(neighbor_process, ev, data)
{
  static struct etimer et;
  clock_time_t initial=0;// randomly initialize these values
  clock_time_t min=0;
  clock_time_t max=10;

  uint16_t val=108;

  PROCESS_EXITHANDLER(neighbor_discovery_close(&neighbor));

  PROCESS_BEGIN();

  neighbor_discovery_open(&neighbor, 129,initial,min,max,&cb);

  while(1) {

    /* Delay 2-4 seconds */
    etimer_set(&et, CLOCK_SECOND * 4 + random_rand() % (CLOCK_SECOND * 4));

PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&et));

packetbuf_copyfrom("Hello", 5);
   neighbor_discovery_set_val(&neighbor,val);
   neighbor_discovery_start(&neighbor,val);
    printf("message sent\n");

 }

  PROCESS_END();
}
/*---------------------------------------------------------------------------*/


text:
Q: Avoid Printing of code when running scripts in spark shell I am trying to connect to DB from in spark shell using scripts in scala file.
when Connecting the script takes password from other location but it does print in console of spark shell.
I just want to avoid those.
Code in Scala is as below,
val config=Map("driver"->"drivername","url"->"dburl","user"->"username","password"->"741852963");

When loading this code in spark shell this prints the code in spark shell too. I want these alone part of to not print in spark console.
How can I achieve this?

A: You have several ways to achieve this:

*

*You can wrap your config definition in an object. Spark shell will just output that an object is defined

scala> object ConfigHolder {
     | val config=Map("secret"->"value")
     | }
defined object ConfigHolder

You can then simply reference your config as ConfigHolder.config instead of config

*

*You can disable/re-enable output printing in the shell with the :silent command

scala> :silent

scala> val config=Map("secret"->"value")

scala> :silent

Of course, none of these actions prevent anyone with access to the spark shell from reading your credentials, it just prevents casual onlookers from seeing them.


text:
Q: C# - Class properties are not in same order I have a requirement that,
Case 1: I have to iterate over all properties of a class and save it in a file. (Say I have to iterate and save properties values)

Case 2: Later I need create a type of class and iterate over its properties to add the saved values in the same order. (Say I have to iterate properties1
to update the saved values in same order)
But the order of properties and properties1 is different. Why?

For this purpose, I have used the concept of reflection to iterate over its properties.
Note: Screenshots are for easy understanding and not the actual code.


text:
Q: Why Firefox event.offsetX and offsetY are undefined? I just stumbled upon a bug in my software that happened only on Firefox. The reason was that the event didn't have offsetX and offsetY defined.
I managed to fix it thanks to this.
Anyways, my question is not a programming help request. I'm just curious why these properties are undefined in Firefox? What is the reason behind it?
I did look through: DOM3 UIEvent Spec., DOM3 MouseEvent Spec. and DOM2 MouseEvent Spec..
It appears that neither of the properties are mentioned there, so, I suppose that's an unofficial property introduced in other browsers?

A: Although mentioned in the W3 specification, the offsetx/offsety properties themselves are implemented inconsistently across browsers.
While supported in IE, Webkit browsers and Opera, they all function slightly different to the specifications requirements, except for IE - according to the "Calculating offsetX, offsetY" section here.
The properties aren't supported in Firefox at all - it appears to be a long-time bug that is yet to be resolved.

"I suppose that's an unofficial property introduced in other
  browsers?"

I believe it's an official property, that just hasn't been implemented in Firefox. If it was a non-official IE property, it wouldn't have been implemented in the Webkit/Opera browsers, mentioned in the W3 spec nor would Firefox actually be trying to implement it (check out the bug link above).

A: offsetX and offsetY are inconsistent in Firefox so you can do it this way
document.body.onclick = function(e) {
    e = e || window.event;

    var target = e.target || e.srcElement,
        rect = target.getBoundingClientRect(),
        offsetX = e.clientX - rect.left,
        offsetY = e.clientY - rect.top;

    console.log([offsetX, offsetY]);
};

You can find more info Here and here


text:
Q: In scala, why this implicit parameter cannot be inferred from the same scope? I'm writing a simple Apache Spark utility that automatically creates an AccumulatorV2 based on provided initial value:
  import java.lang

  type Acc[T] = AccumulatorV2[T, T]

  implicit val long1: Long => Acc[lang.Long] = _ => new LongAccumulator()LongAccumulator()

  implicit def double1: Double => Acc[lang.Double] = _ => new DoubleAccumulator()

  def accumulator[T1, T2](
                           initialValue: T1,
                           name: String
                         )(implicit
                           canBuildFrom: T1 => Acc[T2],
                           converter: T1 => T2,
                           sc: SparkContext = SparkContext.getOrCreate()
                         ): Acc[T2] = {

    val acc: Acc[T2] = canBuildFrom(initialValue)
    acc.reset()
    acc.add(initialValue)

    sc.register(acc, name)

    acc
  }

The 2 implicit parameters: canBuildFrom and converter are supposed to be provided by implicit function and compiler predefined typecast respectively. However, when I tried to call it:
Metrics.accumulator(0L, "webDriverDispatched")

I got the following error information:
Error:(102, 84) No implicit view available from Long => com.tribbloids.spookystuff.Metrics.Acc[T2].
                          webDriverDispatched: Acc[lang.Long] = Metrics.accumulator(0L, "webDriverDispatched"),
Error:(102, 84) not enough arguments for method accumulator: (implicit canBuildFrom: Long => com.tribbloids.spookystuff.Metrics.Acc[T2], implicit converter: Long => T2, implicit sc: org.apache.spark.SparkContext)com.tribbloids.spookystuff.Metrics.Acc[T2].
Unspecified value parameters canBuildFrom, converter.
                          webDriverDispatched: Acc[lang.Long] = Metrics.accumulator(0L, "webDriverDispatched"),

Why scala compiler failed to find the right implicit value? And what should I do to fix it?


text:
Q: Mongoose search on all field's values of users model i want to search in the whole users model values, if admin searches for example a number or a string if the there is a documnet with that value (or that value includes the admin input) in the users model values, mongoose should return all found documents.
how can i implement such thing?
something like this :
const adminInput = req.query.searchText
const foundDocument = await users.find({ '*': includes(adminInput) }) // very simple xD
res.send(foundDocument)

A: As @NeNad points out, this question has been asked and answered many times. Another example is this question.
I'm just chiming in about two things in particular about the phrasing of this question that caught my attention.  The first is:

if admin searches for example a number or a string if the there is a documnet with that value (or that value includes the admin input)

This type of searching can only be applied to string values. There is no concept of 3 being "in" the value of 537. There is, however, the concept of the character "3" being inside of the string "537".
The second thing somewhat overlaps with that and the includes(adminInput) from the code. The direct $text searching functionality provided in the database does not handle partial matches. You would likely need to look into alternatives such as Atlas Search or coupling Elasticsearch beside your MongoDB cluster to get the full functionality you are describing.


text:
Q: Locking another computer using sockets without interrupting the connection I am trying to set up a server that can send each client - commands.
One command is 'lock' which locks the screen of the client.
When a client gets the word "lock" it runs this code on the client:
import ctypes
ctypes.windll.user32.LockWorkStation()

This code does lock the screen however- it ends my connection with the client..
How can I make the client stay connected but still locked?
Note: The locking is not forever! it is only once, like putting the client's computer in sleep mode until he wants to unlock the screen.
Hope I was clear enough. Thanks for helping!
Server:
import socket

def main():

    sock = socket.socket()
    sock.bind(('0.0.0.0', 4582))
    print("Waiting for connections...")
    sock.listen(1)
    conn, addr = sock.accept()
    print ("New connection from: ", addr)

    while 1:
        command = input("Enter command> ")

        if command == 'shutdown':
            sock.send(b'shutdown')
        elif command == 'lock':
            sock.send(b'lock')
        else:
            print ("Unknown command")

        data = sock.recv(1024)
        print (data)

if __name__ == '__main__':
    main()

Client:
import socket
import ctypes

def main():

    sock = socket.socket()
    sock.connect(('127.0.0.1', 4582))

    while 1:

        data = sock.recv(1024)
        print (data)

        if data == 'lock':
            sock.send(b'locking')
            ctypes.windll.user32.LockWorkStation()

        sock.recv(1024)

if __name__ == '__main__':
    main()

A: I adapted the example from the Python docs to your needs.
Example for server.py:
import socket

HOST = '127.0.0.1'
PORT = 4582

with socket.socket() as s:
    print('Waiting for connection...')
    s.bind((HOST, PORT))
    s.listen(1)
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            data = input('Which command? ')
            if data in ['lock', 'shutdown']:
                conn.send(data.encode())
            else:
                print('Command unknown')

Example for client.py:
import ctypes
import socket

HOST = '127.0.0.1'
PORT = 4582

with socket.socket() as s:
    s.connect((HOST, PORT))
    while True:
        data = s.recv(1024).decode()
        if not data:
            print('Server disconnected')
            break
        print('Received command:', data)
        if data == 'shutdown':
            print('Shutting down client...')
            break
        if data == 'lock':
            print('Locking...')
            ctypes.windll.user32.LockWorkStation()


text:
Q: how to solve error CS1525: Invalid expression term ')' in unity 3d game engine using UnityEngine;
public class playermove : MonoBehaviour{
public float moveSpeed=5f;
// Update is called once per frame
void Update(){
    jump();
   Vector3 movment = new Vector3(Input.GetAxis("Horizontal"),0f ,0f);
   transform.position += movment * Time.deltaTime * moveSpeed;
}
void jump() {
    if (Input.GetButtonDown("jump"))
    gameObject.GetComponent<"RigidBody2D">();AddForce(new Vector2(0f,5f),ForceMode2D.Impulse);
}

}
i have this code i am getting error CS1525: Invalid expression term ')'
problem.

A: if (Input.GetButtonDown("jump")) {
gameObject.GetComponent<RigidBody2D>().AddForce(new Vector2(0f,5f),ForceMode2D.Impulse)
}

No need for the quote on GetComponent! And also ";" is used to end a line, use "." in your case.


text:
Q: Setting scroll height of a DIV using javascript and css I have this div which pops up when an action is triggered. When I scroll down the page, it still remains on top of page. I want to set the scroll height so it moves in relative position to the page scroll. Simply making the position : relative does not work. How can I use javascript get this? Help.
    <form name="" action="" method="POST">

<input class='form_button' type='submit' name='btnSubmit' value='Replace' onclick='return checkSearchAndReplace();'/>

</form>

this is the css
#divSearchAndReplace { width:450px; height:240px; border:1px solid #336699; background-color:#ffffff; position:absolute; left:200px; top:75px; display:none; }
#divSearchAndReplace table { width:450px; border:0px; align:center; }

A: Are you maybe looking for position: fixed in CSS?


text:
Q: How to open new Safari window on primary display I am using a monitor as my second display for my MacBook Air. I have Netflix fullscreen on my second display. Whenever I want a Safari window on my primary display, I have to go to the second display, create a new window, and drag it over to my primary display. this disrupts Netflix, as I have to click to leave full screen then put it back to fullscreen.
Is there an easier way to achieve this?

A: "active" the primary display and run this applescript
tell application "Safari"
    make new document at end of documents with properties {URL:"about:black"}
    activate
end tell


text:
Q: Не сохраняется токен в LocalStorage Есть файл Token с запросом
export default async function Token(email, password) {
  if (!res.ok) {
    throw new Error('Could not fetch');
  }
  return fetch(`/api/login?pass=${password}&user=${email}`, {
    method: 'POST',
  })
}

От него создается отдельный файл с запросом на сохранение токена в LocalStorage.
import Token from '../requests';
import saveToken from '../token';

export default function login(email, password) {
  return Token(`/api/login?pass=${password}&user=${email}`, {
      method: 'POST'
    })
    .then((res) => res.text())
    .then(saveToken)
    .catch(() => {
      alert('failed');
    });
}

Сам файл token
export default function saveToken(token) {
  localStorage.setItem('token', JSON.stringify(token));
}

На данном этапе после заполнения формы в localstorage токен полностью отсутствует (Туда вообще ничего не прилетает). Подскажите пожалуйста, в чем проблема?

A: Подозреваю, что в Token() надо передавать login и password:
export default function login(email, password) {
  return Token(email, password)
    .then((res) => res.text())
    // ... и далее по коду
}

И из объявления функции Token() стоит убрать все, что относится к res:
export default async function Token(email, password) {
  return fetch(`/api/login?pass=${password}&user=${email}`, {
    method: 'POST',
  })
}

Ну и вообще почитать про POST-запросы.


text:
Q: How do I open a file with a program via a shortcut from the cmd prompt Here's my predicament:
When I add a program's location to my PATH, I can do the following in cmd prompt to open a file in my current directory:
notepad++ open_me.txt

And this opens open_me.txt in notepad++.
However, I don't want to have to add every single program I want to run to my path.  What I want is to add a folder called C:\Users\Me\Documents\Programs to my path and just drop shortcuts to various programs into that folder and have them function the same as adding them to my path.
So I dropped a link to notepad++.exe named "np" in my folder, and what I got was this:
I have to run it with start np (instead of just np)
But more importantly, if I try start np open_me.txt, it opens notepad++.exe but looks for open_me.txt in notepad++'s directory.
How can I do this properly? (Also, I'd like to be opening notepad++.exe with the shortened name of np)

A: Sounds to me like you already know how to "do this properly" - you're just too lazy to do it.
A work-around for some commands (it'll work in your particular use case, but not much further) would be to drop batch files into a folder that is already in %PATH%.  So, instead of using a shortcut for "np" you would put the following in "np.bat":
"C:\Program Files (x86)\Notepad++\notepad++.exe" %1
Then, whenever you run np Filename.txt it should run Notepad++ and open Filename.txt.  Remember to use quotes for filenames that include spaces.


text:
Q: How to prove this action is discontinuous? Let $G$ be a group of homeomorphisms of a topological space $X$. The action of $G$ on $X$ is said to be discontinuous at a point $x \in X$ if

*

*$G_x :=$ the stabilizer of $x$, is finite.

*$x$ has an open neighbourhood $U$ such that $gU \cap U = \emptyset$ for all $g \notin G_x$
Let $H$ be the normal subgroup of $G$ generated by all those elements of $G$ that have fixed points.
I need to show that the action of $G/H$ on $X/H$ is free and discontinuous
For any $gH \in G/H$ and $[x]_H \in X/H$ I can define $gH \cdot [x]_H = [g\cdot x]_H$ where $[x]_H$ is the class of all points of $X$ in the $H$ - orbit of $x$. I have proven that this is a well defined action (independent of the choice of $x$ or $g$). Also I have proven that this action is free.
This is my attempt to prove the action is discontinuous -
Let $\pi : X \rightarrow X/H$ be the orbit map.

*

*for $[x]_H \in X/H$ the stabilizer is just $\{H\}$ which is finite.

*Let   $x\in \pi^{-1}([x]_H)$. Then there exists an open neighbourhood $U$ of $x$ in $X$ such that $gU \cap U = \emptyset$ for all $g \notin G_x$
My guess is that $\pi (U)$ is the required neighbourhood of $[x]_H$
Let $gH$ be a non identity element of $G/H$. Then I need to show that $gH \pi(U) \cap \pi (U) = \emptyset$. Suppose there is a $[y]_H$ in this intersection. Then there will be a $y_1 \in U$ such that $[y]_H = [gy_1]_H$. This will give me that $[y]_G =[y_1]_G$ as $G$ - orbits. How do I get a contradiction to $gU \cap U = \emptyset$ when $g \notin G_x$? Or more precisely where do I get a $g \notin G_x$ from? It is possible I'm missing something really simple here but I have no idea how to proceed.
Thanks!

A: The following assumes that $G$ acts discontinuously on $X$, but you assumed that at the beginning of the second point of your attempt.
First, we choose an open set $U \subseteq X$ such that $g U \cap U = \emptyset$ for all $g \notin G_x$.
So you have to prove that $gH \pi(U) \cap \pi(U) = \emptyset$. Let $x_1 \in U$, i.e. $[x_1]_H \in \pi(U)$. If $[x_1]_H \in gH \pi(U)$, then there exists an $x_2 \in U$ such that $[x_1]_H = [g(x_2)]_H$, i. e. for an $h \in H$, $x_1 = h(g(x_2))$. We define $f := h \circ g \in G$. If $f$ is in the stabiliser of $x$, then $gH$ stabilises $[x]_H$ and there is nothing to prove. Otherwise, $x_2 \in U \cap fU$, and hence $U \cap fU \neq \emptyset$, contradiction.


text:
Q: Get precison model through GridSearchCV for recall optimization Given a machine learning model  RBF SVC called 'm', I performed a gridSearchCV on gamma value, to optimize recall.
I'm looking to answer to this:
"The grid search should find the model that best optimizes for recall. How much better is the recall of this model than the precision?"
So I did the gridSearchCV:
grid_values = {'gamma': [0.001, 0.01, 0.05, 0.1, 1, 10, 100]}
grid_m_re = GridSearchCV(m, param_grid = grid_values, scoring = 'recall')
grid_m_re.fit(X_train, y_train)
y_decision_fn_scores_re = grid_m_re.decision_function(X_test)

print('Grid best parameter (max. recall): ', grid_m_re.best_params_)
print('Grid best score (recall): ', grid_m_re.best_score_)

This tell me the best model is for gamma=0.001 and it has a recall score of 1.
I'm wondering how to get the precision for this model to get the trade of of this model, cause the GridSearchCV only has attribute to get what it was optimize for.([Doc sklearn.GridSearchCV][1])

A: Not sure if there's an easier/more direct way to get this, but this approach also allows you to capture the 'best' model to play around with later:
First do you CV fit on training data:
grid_m_re = GridSearchCV(m, param_grid = grid_values, scoring = 'recall')
grid_m_re.fit(X_train, y_train)

Once you're done, you can pull out the 'best' model (as determined by your scoring criteria during CV), and then use it however you want:
m_best = grid_m_re.best_estimator_

and in your specific case:
from sklearn.metrics import precision_score

y_pred = m_best.predict(X_test)
precision_score(y_test, y_pred)

A: You can easily overfit if you don't optimize both, C and gamma at the same time.
if you plot the SVC with C on the X axis, gamma on the y axis and recall as color you get some kind of V-Shape, see here
So if you do grid search, better optimize for both, C and gamma, at the same time.
The problem is that usually you get the best results for small C-Values, and in that area the V-shape has it's pointy end: is not very big and difficult to hit.
I recently used:
make a random grid of 10 points
      every point contains C, gamma, direction, speed
cut the dataset with stratifiedShuffleSplit
fit & estimate score with cross validation

repeat:
  kill the worst two points
  the best two points spawn a kid
  move every point in its direction with just a little bit of random,
  fit & estimate score with cross validation
     (if a point notice it goes downward, turn around and half speed)
  until break criterion is hit

Worked like a charm.
I used the max distance in the feature space divided by four as initial speed,
the direction had a maximum random of pi/4
Well, the cross validation was a bit costly.
Cleptocreatively inspired by this paper.
... and another edit:
I used between 10 and 20 cycles in the loop to get the perfect points.
If your dataset is too big to do several fits, make a representative subset for the first few trainings...


text:
Q: Regex capture point surrounded by numbers I have this pretty complex Regex selection that almost works. I just seem to have a problem with understanding how non capture groups work. I've read the wiki but still can't seem to grasp how to use them properly (or this is the wrong usecase?)
\b(?:[0-9]+) ?(\.) ?(?:[0-9]+)(?! ?(uur|(u|h)))\b
If I have the following set of statements, I would like ONLY the '.' of the first 4 to be selected. ATM the Regex captures the numbers + the '.' of the first 4.
0.22
15.48
8.50
048948.00000
05:23 uur
06.35 u
15.48u
0.55u
11.00h
5.54 uur
23: 31
08 :40 uur

I've read (and tried) to use the non capture group but it doesn't seem to help much.
Anyone have an idea on how to achieve this and care to explain a bit why it works?
Also not sure if this helps but I got a link to test the Regex I made: https://regexr.com/5dc6q

A: You can use
\b[0-9]+ ?\K\.(?= ?[0-9]+(?! ?(?:uur|[uh]))\b)

See the regex demo
Regex details

*

*\b - a word boundary

*[0-9]+ ? - one or more digits and then an optional space

*\K - a match reset operator that discards all text matched so far

*\. - a dot

*(?= ?[0-9]+(?! ?(?:uur|[uh]))\b) - a location immediately followed with

*

* ? - an optional space

*[0-9]+ - one or more digits

*(?! ?(?:uur|[uh])) - not followed with an optional space, uur or u or h

*\b - word boundary


text:
Q: Linux - dd command is failing with error [no space left on device] I am currently trying to create an image of a USB key to create a backup. The USB key is 128G and the target External Hard drive has 300G available approximately.
I am using Cygwin and here is What I do so you understand :
I place myself on the External hard drive by typing : cd E: I end up under /cygdrive/e which is my HDD. The usb key is under/cygdrive/d
Here is what cat /proc/partitions gives :
$ cat /proc/partitions major minor #blocks name win-mounts

8     0 250059096 sda
8     1    266240 sda1
8     2     16384 sda2
8     3 248955904 sda3   C:\
8     4    819200 sda4
8    16 125091840 sdb
8    17 125091584 sdb1   D:\
8    32 312571224 sdc
8    33 312568641 sdc1   E:\

So here is the DD command I launch:
dd if=/dev/sdb1 | pv -s 128G | dd of=backup.usb.img bs=1M

It starts and progress well each time until it fails with the error :
dd: error writing 'backup.usb.img': No space left on device

I tried several times, and each time it fails after reading around 4,2G. My HDD has like 300G available so I don't understand...
Why is the dd command failing with a no space left whereas the target has plenty of space available ?
Thanks a lot

A: Indeed, reply from "that other guy" solved my issue.
I formatted my DD into exFat to it can be used on MacOS as well, and the DD command went fine.
Also thanks "Matzeri", because I also removed the pv in the middle.
We can use : status=progress
It just needs sys-apps/coreutils >= 8.24
Thanks !

A: Regarding what "@that other guy" mentioned with respect to splitting the file into 4G chunks so it would fit on a FAT32 disk, I had to do something like that earlier this year.
I needed to view the contents of a Mac OSX 2280 SSD, but couldn't on the non-Mac workstation I was on. The only Mac I had at my disposal was behind lock and key, i.e. no physical USB to plug in the adapter. My solution was to dd the disk image piped into ssh, sending it to the Mac, and mount it like an image file.
This should've worked:
dd if=${InputDev} bs=1M status=progress | ssh user@${DESTHOST} "dd bs=1M of=${OUTPUTFILENAME}"

The problem I ran into is that something between the two computers caused some network problems, so I would have to restart the entire clone operation. I ended up sending 10 or 100 MB at a time, then whichever chunk failed, I resent manually. I used something like this.
# For demonstration purposes, this example splits ${InputDev}, a 1 GiB file,
#   into 10 100 MiB pieces, plus an 11th piece with the remaining data.
# Note that the last couple chunks result in empty files at $DESTHOST
#   because it tries to skip past EOF on the input side.
# When chunking with ssh, it's best to use an SSH key for the transfer.

for chunk in $(seq -w 0 12)
# "-w" in seq above ensures leading zeroes to keep files in order
do
    echo "Sending chunk #${chunk} of ${InputDev}"
    dd \
        if=${InputDev} \
        bs=100M \
        skip=${chunk} \
        count=1 \
        status=progress | \
            ssh root@${DESTHOST} "dd bs=100M of=/tmp/DevSdx_chunk#_${chunk}.dd"
        echo ""
done

For your scenario, where you can plug in a USB drive on the same machine, you wouldn't need the pipe into ssh portion. You would add of=/media/MyUSB/DevSdx_chunk#_${chunk}.dd to the dd command.
After the operations are finished, you can compare the source and destination checksums to verify integrity.
# Source side
sha256sum ${InputDev}
5f9c534c0753deb7188ae645928165d16f5e7378c1257532faa1bcb17a69740d  ${InputDev}

# Destination side
# if your output files are out of lexicographical order, the checksum won't match
cat /media/MyUSB/DevSdx_chunk*.dd | sha256sum # if local
cat /tmp/DevSdx_chunk*.dd | sha256sum # using the ssh example

If the checksums match on both ends, you can reassemble the whole image on the destination side with
# Destination side
cat /media/MyUSB/DevSdx_chunk*.dd > /media/FileSystemThatAllowsLargerFiles/DevSdx.dd


text:
Q: Can't call gnome-screenshot in C I want to call the command gnome-screenshot -ac in my C program using system("gnome-screenshot -ac") or exec() but they didn't work. I'm sure that this command works well because I can use it in the terminal. The same error occurs when I tried to call a bash script I write the command in. When I use system(), it says:
(gnome-screenshot:16564): Gdk-CRITICAL **: gdk_pixbuf_get_from_surface: assertion 'width > 0 && height > 0' failed

(gnome-screenshot:16564): Gtk-CRITICAL **: gtk_window_resize: assertion 'width > 0' failed

** (gnome-screenshot:16564): CRITICAL **: Unable to capture a screenshot of any window

When calling execl("./screenshot.sh","screenshot",NULL) in C:
(gnome-screenshot:16861): Gdk-CRITICAL **: gdk_pixbuf_get_from_surface: assertion 'width > 0 && height > 0' failed

(gnome-screenshot:16861): Gtk-CRITICAL **: gtk_window_resize: assertion 'width > 0' failed

** (gnome-screenshot:16861): CRITICAL **: Unable to capture a screenshot of any window

Why it is wrong and how to fix it?
I can see the cursor after I run it in my terminal but in my C program. I just want to capture the screen and the clipboard will be accessed by users. I'm doing this with 14.04.2. I just call the functions to call the command in C but it always causes some errors above.


text:
Q: Adding drop shadow to custom UITableCellView not working So I have a custom UITableCellView that has a bunch of subviews inside of it. I'm trying to add a drop shadow to this cell -
-(void)drawRect:(CGRect)rect{
    [self.layer setShadowColor:[UIColor blackColor].CGColor];
    [self.layer setShadowOpacity:0.8];
    [self.layer setShadowRadius:3.0];
    [self.layer setShadowOffset:CGSizeMake(4.0, 4.0)];
    self.layer.masksToBounds = YES;

}

So I overrode the draw rect method to do so - but this isn't working.
How should I add a drop shadow to each cell?

A: Try this code in cellForRowAtIndexPath
cell.layer.shadowOffset = CGSizeMake(1, 0);
cell.layer.shadowColor = [[UIColor blackColor] CGColor];
cell.layer.shadowRadius = 5;
cell.layer.shadowOpacity = .25;

CGRect shadowFrame = cell.layer.bounds;
CGPathRef shadowPath = [UIBezierPath bezierPathWithRect:shadowFrame].CGPath;
cell.layer.shadowPath = shadowPath;

A: since u hav custom cell then u can add shadow like this,

   //this is in custom cell assume u hav "CustomCell" class
   //in CustomCell.m

  - (void)layoutSubviews
   {
       [super layoutSubviews];

       //add shadow properties by using layers
        self.layer.shadowOpacity = 0.8f; //self is the custom cell
        self.layer.shadowColor = [UIColor blackColor].CGColor; //set the shadow color

       // .. other layer properties and effects u want

   }

A: try this
-(void)drawRect:(CGRect)rect
{
    [[self layer] setShadowColor:[[UIColor blackColor] CGColor]];
    [[self layer] setShadowOpacity:0.8f];
    [[self layer] setShadowRadius:3.0f];
    [[self layer] setShadowOffset:CGSizeMake(4.0f, 4.0f)];
    [[self layer] setShouldRasterize:YES];
    [[self layer] setRasterizationScale:[[UIScreen mainScreen] scale]];
}


text:
Q: MySQL fails to start in XAMPP due to mysqld.exe error Everything was working fine. I've worked with xampp for about 4 years now and I've never encountered such problem. Tried to start MySQL from XAMPP and it failed. upon looking at the error log, I have deducted that one of the folders are corrupted and if so, how do I fix it?
mysql_error.log (part of it):
2020-01-19 11:56:21 0 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2020-01-19 11:56:21 0 [Note] InnoDB: Uses event mutexes
2020-01-19 11:56:21 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
2020-01-19 11:56:21 0 [Note] InnoDB: Number of pools: 1
2020-01-19 11:56:21 0 [Note] InnoDB: Using SSE2 crc32 instructions
2020-01-19 11:56:21 0 [Note] InnoDB: Initializing buffer pool, total size = 16M, instances = 1, chunk size = 16M
2020-01-19 11:56:21 0 [Note] InnoDB: Completed initialization of buffer pool
2020-01-19 11:56:21 0 [Note] InnoDB: Starting crash recovery from checkpoint LSN=38825021
2020-01-19 11:56:21 0 [Note] InnoDB: 128 out of 128 rollback segments are active.
2020-01-19 11:56:21 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
2020-01-19 11:56:21 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2020-01-19 11:56:21 0 [Note] InnoDB: Setting file 'C:\xampp\mysql\data\ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2020-01-19 11:56:21 0 [Note] InnoDB: File 'C:\xampp\mysql\data\ibtmp1' size is now 12 MB.
2020-01-19 11:56:21 0 [Note] InnoDB: Waiting for purge to start
2020-01-19 11:56:21 0 [Note] InnoDB: 10.4.6 started; log sequence number 38825030; transaction id 21030
2020-01-19 11:56:21 0 [Note] InnoDB: Loading buffer pool(s) from C:\xampp\mysql\data\ib_buffer_pool
2020-01-19 11:56:21 0 [Note] Plugin 'FEEDBACK' is disabled.
2020-01-19 11:56:21 0 [Note] Server socket created on IP: '::'.
2020-01-19 20:37:41 0 [Note] mysqld.exe: Aria engine: starting recovery
recovered pages: 0% 17%
2020-01-19 20:37:41 0 [ERROR] mysqld.exe: Index for table '.\mysql\db' is corrupt; try to repair it

***WARNING: .\mysql\db could not be opened: Error: 126
 27% 39% 52% 62% 73% 86% 96% 100% (0.0 seconds); tables to flush: 1 0 (0.0 seconds);
2020-01-19 20:37:41 0 [Note] mysqld.exe: Aria engine: recovery done
InnoDB: using atomic writes.
2020-01-19 20:37:41 0 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2020-01-19 20:37:41 0 [Note] InnoDB: Uses event mutexes
2020-01-19 20:37:41 0 [Note] InnoDB: Compressed tables use zlib 1.2.11

A: As the error says, one index is corrupt.

*

*Launch your server first in recovery mode. Add innodb_force_recovery=1 to your my.cnf.  In case your server doesn't start, you may increase this number from 1 to 6, check MySQL manual to see what the differences are (dev.mysql.com/doc/refman/5.5/en/forcing-innodb-recovery.html)

*Run mysqlcheck -c on all of the relevant tables to find out which ones had index corruption

*Use mysqlcheck --optimize from command line to rebuid the table that have corrupt indexes

Otherwise they to rebuild the table, some times a dump and import will help.  check this section of the docs with alternative ideas https://dev.mysql.com/doc/refman/8.0/en/rebuilding-tables.html


text:
Q: Atomic bool fails to protect non-atomic counter I encountered an issue with a (basic) spinlock mutex that does not seem to work as expected.
4 threads are incrementing a non-atomic counter that is protected by this mutex.
The outcome does not match with the expected result which makes the mutex seem broken.
example output:
  result: 2554230
expected: 10000000

In my environment it happens under the following conditions:

*

*flag is std::atomic<bool>, anything else such as std::atomic<int> or std::atomic_flag (with test_and_set) works fine.

*compiled on X86_64 with gcc 6.3.1 and -O3 flag
My question is, what could explain this behavior ?
#include <iostream>
#include <vector>
#include <atomic>
#include <thread>
#include <mutex>
#include <assert.h>

class my_mutex {
    std::atomic<bool> flag{false};

public:
    void lock()
    {
        while (flag.exchange(true, std::memory_order_acquire));
    }

    void unlock()
    {
        flag.store(false, std::memory_order_release);
    }
};

my_mutex mut;
static int counter = 0;

void increment(int cycles)
{
    for (int i=0; i < cycles; ++i)
    {
        std::lock_guard<my_mutex> lck(mut);

        ++counter;
    }
}

int main()
{
    std::vector<std::thread> vec;
    const int n_thr = 4;
    const int n_cycles = 2500000;

    for (int i = 0; i < n_thr; ++i)
        vec.emplace_back(increment, n_cycles);

    for(auto &t : vec)
        t.join();

    std::cout << "  result: " << counter << std::endl;
    std::cout << "expected: " << n_cycles * n_thr << std::endl;
}

edit
Per request from Voo, here is the assembly output for increment()..
$ g++ -O3 increment.cpp
$ gdb a.out
Reading symbols from a.out...done.
(gdb) disassemble increment
Dump of assembler code for function increment(int):
   0x0000000000401020 <+0>:     mov    0x20122a(%rip),%ecx        # 0x602250 <_ZL7counter>
   0x0000000000401026 <+6>:     test   %edi,%edi
   0x0000000000401028 <+8>:     mov    $0x1,%edx
   0x000000000040102d <+13>:    lea    (%rdi,%rcx,1),%esi
   0x0000000000401030 <+16>:    jle    0x401058 <increment(int)+56>
   0x0000000000401032 <+18>:    nopw   0x0(%rax,%rax,1)
   0x0000000000401038 <+24>:    mov    %edx,%eax
   0x000000000040103a <+26>:    xchg   %al,0x20120c(%rip)        # 0x60224c <mut>
   0x0000000000401040 <+32>:    test   %al,%al
   0x0000000000401042 <+34>:    jne    0x401038 <increment(int)+24>
   0x0000000000401044 <+36>:    add    $0x1,%ecx
   0x0000000000401047 <+39>:    cmp    %ecx,%esi
   0x0000000000401049 <+41>:    mov    %ecx,0x201201(%rip)        # 0x602250 <_ZL7counter>
   0x000000000040104f <+47>:    movb   $0x0,0x2011f6(%rip)        # 0x60224c <mut>
   0x0000000000401056 <+54>:    jne    0x401038 <increment(int)+24>
   0x0000000000401058 <+56>:    repz retq
End of assembler dump.

A: Your code is correct. It's a bug 80004 - [6 Regression] non-atomic load moved to before atomic load with std::memory_order_acquire


text:
Q: Not always dismissing keyboard when touching outside of textfield I have touches method but it works only when i click on some areas of the view not everywhere.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];// this will do the trick
}

how can I fix the issue?
Thanks

A: OK, try with below code & check:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    [touch locationInView:self.view];
    [self.view endEditing:YES];
}

A: Try this
- (void)viewDidLoad
{
[super viewDidLoad];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)];
[self.view addGestureRecognizer:singleTap];

// Do any additional setup after loading the view, typically from a nib.
}
- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture
{
//Get touch point
CGPoint touchPoint=[gesture locationInView:self.view];

//Hide keyBoard
[self.view endEditing:YES];
}


text:
Q: How to detect only the contour of just the filled zones in opencv I would like to be able to detect contours of the filled zones only,
I have an input image that is like this

And I would like to be able to detect only the contours of the filled zones.(the blue ones in this image)


text:
Q: Firebase realtime database add values to Recycler Long winded question. I have already this week set up a recycler view for my users in the firebase database. I want to do the same for user incidents. These are concussion tests. I basically copied my player list activities and tried to implement the same for the incidents. However they are stored differently in firebase . You can see this from the picture below.
I basically want to know is there a easy way to do this Ive tried a few things but no luck yet.
At the minute here is my code I am using. The error I get with this is "com.google.firebase.database.DatabaseException: Failed to convert value of type java.util.HashMap to String" although I think there is a few more errors.
Incident Helper Class
public class IncidentHelperClass {

    //Declare variables of the information to store in the database
    String playerId, Cervical_Spine_Activity, Glasgow_Coma_Scale_Test, Memory_Questions, Observable_Signs_Test, Red_Flags_Test, Report;

    //Empty constructor
    public IncidentHelperClass() {

    }

    //Constructor
    public IncidentHelperClass(String redFlag, String observable, String memory, String gcs, String csa, String incidentReport) {

        this.Cervical_Spine_Activity = redFlag;
        this.Observable_Signs_Test = observable;
        this.Memory_Questions = memory;
        this.Glasgow_Coma_Scale_Test = gcs;
        this.Cervical_Spine_Activity = csa;
        this.Report = incidentReport;
    }

    public String getPlayerId() {
        return playerId;
    }

    public void setPlayerId(String playerId) {
        this.playerId = playerId;
    }

    public String getCervical_Spine_Activity() {
        return Cervical_Spine_Activity;
    }

    public void setCervical_Spine_Activity(String cervical_Spine_Activity) {
        Cervical_Spine_Activity = cervical_Spine_Activity;
    }

    public String getGlasgow_Coma_Scale_Test() {
        return Glasgow_Coma_Scale_Test;
    }

    public void setGlasgow_Coma_Scale_Test(String glasgow_Coma_Scale_Test) {
        Glasgow_Coma_Scale_Test = glasgow_Coma_Scale_Test;
    }

    public String getMemory_Questions() {
        return Memory_Questions;
    }

    public void setMemory_Questions(String memory_Questions) {
        Memory_Questions = memory_Questions;
    }

    public String getObservable_Signs_Test() {
        return Observable_Signs_Test;
    }

    public void setObservable_Signs_Test(String observable_Signs_Test) {
        Observable_Signs_Test = observable_Signs_Test;
    }

    public String getRed_Flags_Test() {
        return Red_Flags_Test;
    }

    public void setRed_Flags_Test(String red_Flags_Test) {
        Red_Flags_Test = red_Flags_Test;
    }

    public String getReport() {
        return Report;
    }

    public void setReport(String report) {
        Report = report;
    }

}
Incident Adapter
public class IncidentListAdapter extends RecyclerView.Adapter<IncidentListAdapter.ViewHolder> {

    //Constants for the player name and id
    public static final String PLAYER_NAME = "playername";
    public static final String PLAYER_ID = "playerid";

    SharedPreferences sharedpreferences;

    public static final String MyPREFERENCES = "MyPrefs";
    public static final String ID = "idKey";
    //Variables
    private Context context;
    //Declare a list using the UserHelperClass
    private List<IncidentHelperClass> incidentList;

    //Constructor
    public IncidentListAdapter(Context context, List<IncidentHelperClass> incidentsList) {
        this.context = context;
        this.incidentList = incidentsList;
    }

    @NonNull
    @Override
    //If viewHolder does  not exist create one by inflating the user_details_view
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(
                LayoutInflater.from(context)
                        .inflate(R.layout.users_details_view, parent, false)
        );
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {

        //Retrieve the incident stored at the position
        final IncidentHelperClass incidents = incidentList.get(position);
        //Set the info from the UserHelperClass in the textViews
        holder.textViewRedFlag.setText(incidents.getRed_Flags_Test());
        holder.textViewObs.setText(incidents.getObservable_Signs_Test());
        holder.textViewMemory.setText(incidents.getMemory_Questions());
        holder.textViewGCS.setText(incidents.getGlasgow_Coma_Scale_Test());
        holder.textViewCSA.setText(incidents.getCervical_Spine_Activity());
        holder.textViewIncidentReport.setText(incidents.getReport());

        //Add an onClickListener to the parentView
        holder.parentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                IncidentHelperClass selectedIncident = incidentList.get(position);

                //The intent to launch the activity
                Intent intent = new Intent(context, RedFlagActivity.class);

                //Put the player id and name into the Intent from the playerList
                //  intent.putExtra(PLAYER_ID, player.getPlayerID());
                // intent.putExtra(PLAYER_NAME, player.getName());
                //Start the activity passed from the intent
                context.startActivity(intent);

            }
        });

    }

    @Override
    //Return the amount of players
    public int getItemCount() {
        return this.incidentList.size();
    }

    //ViewHolder wraps the view passed to it so RecyclerView can deal with it
    public class ViewHolder extends RecyclerView.ViewHolder {

        private TextView textViewRedFlag;
        private TextView textViewObs;
        private TextView textViewMemory;
        private TextView textViewGCS;
        private TextView textViewCSA;
        private TextView textViewIncidentReport;
        private View parentView;

        //Attach the variables to their views
        public ViewHolder(@NonNull View view) {
            super(view);
            this.parentView = view;
            this.textViewRedFlag = view.findViewById(R.id.player_view_name);
            this.textViewObs = view.findViewById(R.id.player_view_email);
            this.textViewMemory = view.findViewById(R.id.player_view_phoneNo);
            this.textViewGCS = view.findViewById(R.id.player_view_emergencyContact);
            this.textViewCSA = view.findViewById(R.id.player_view_emergencyContactPhone);
            this.textViewGCS = view.findViewById(R.id.player_view_emergencyContactPhone2);
            this.textViewIncidentReport = view.findViewById(R.id.player_view_emergencyContactPhone3);
        }
    }
}

Incident Activity
public class IncidentListView extends AppCompatActivity {

//Class to update and display information in the recycler_view

    //Define the RecyclerView
    RecyclerView listViewIncidents;

    //Define a list to store the players
    ArrayList<IncidentHelperClass> incidentsList;
    //Define the reference to the database
    DatabaseReference reference;

    //Define the PlayerList Adapter
    IncidentListAdapter adapter;

    SharedPreferences sharedpreferences;
    public static final String MyPREFERENCES = "MyPrefs";
    public static final String ID = "idKey";

    //Constants fot the player name and id
    public static final String PLAYER_NAME = "playername";
    public static final String PLAYER_ID = "playerid";

    //Tag for printing log details
    private final String TAG = getClass().getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.users_list_recycler_view);

        //Assign the listView to the appropriate view
        // listViewPlayers = findViewById(R.id.users_list_recycler_view);
        //Assign the playersList
        incidentsList = new ArrayList<>();

        //Assign the recycler view to the correct view
        listViewIncidents = findViewById(R.id.recycler_list_view);
        //Set the adapter to an instance of the PlayerListAdapter
        listViewIncidents.setAdapter(new IncidentListAdapter(this, incidentsList));
        //Instruct the layout manager to set the layout to LinearLayout
        listViewIncidents.setLayoutManager(new LinearLayoutManager(this));

        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
        sharedpreferences = getBaseContext().getSharedPreferences(MyPREFERENCES, 0);
        String id = sharedpreferences.getString(ID, "UserID");
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putString(ID, id);
        editor.commit();

        //Get a reference to the path required in the database
        reference = FirebaseDatabase.getInstance().getReference("Incidents");

        //AddValueEventListener will update the players list if any new players added
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for (DataSnapshot incidentSnapshot : snapshot.getChildren()) {
                    //Get the values defined in the UserHelperClass from the registered players in the database
                    IncidentHelperClass incident = incidentSnapshot.getValue(IncidentHelperClass.class);
                    //If a new player is created add them to the playersList
                    incidentsList.add(incident);
                }
                //What does this do??
                adapter = new IncidentListAdapter(IncidentListView.this, incidentsList);
                listViewIncidents.setAdapter(adapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                //Show Error toast to user
                Toast.makeText(IncidentListView.this, "Error Occured", Toast.LENGTH_LONG).show();
            }
        });
    }
}

Update
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
//Retrieve the incident stored at the position
final StackIncidentHelperClass incidents = incidentList.get(position);
//Set the info from the UserHelperClass in the textViews
holder.textViewRedFlag.setText((CharSequence) incidents.getRed_Flags_Test());
holder.textViewObs.setText((CharSequence) incidents.getObservable_Signs_Test());
holder.textViewMemory.setText((CharSequence) incidents.getMemory_Questions());
holder.textViewGCS.setText((CharSequence) incidents.getGlasgow_Coma_Scale_Test());
holder.textViewCSA.setText((CharSequence) incidents.getCervical_Spine_Activity());
holder.textViewIncidentReport.setText((CharSequence) incidents.getReport());

Update Database

UPDATE

A: You code crashes because of the type of these variables:
String Cervical_Spine_Activity, Glasgow_Coma_Scale_Test, Memory_Questions, Observable_Signs_Test, Red_Flags_Test;

Their type is java.util.HashMap<String, String>.
And Report variable is of another absolutelly different type. You have to declare new class (lets call it Report) with the next content:
class Report {
    public String reportDetails;
    public String reportId;
    // add getters/setters/constructors if necessary
}

Having that information you can update IncidentHelperClass class members declaration:
public class IncidentHelperClass {

    //Declare variables of the information to store in the database
    String playerId;
    HashMap<String, String> Cervical_Spine_Activity, Glasgow_Coma_Scale_Test, Memory_Questions, Observable_Signs_Test, Red_Flags_Test;
    @SerializedName("Report")
    Report report;

    //Empty constructor
    public IncidentHelperClass() {

    }

    //Constructor
    public IncidentHelperClass(HashMap<String, String> redFlag,
                               HashMap<String, String> observable,
                               HashMap<String, String> memory,
                               HashMap<String, String> gcs,
                               HashMap<String, String> csa,
                               Report incidentReport) {

        this.Cervical_Spine_Activity = redFlag;
        this.Observable_Signs_Test = observable;
        this.Memory_Questions = memory;
        this.Glasgow_Coma_Scale_Test = gcs;
        this.Cervical_Spine_Activity = csa;
        this.report = incidentReport;
    }

    public String getPlayerId() {
        return playerId;
    }

    public void setPlayerId(String playerId) {
        this.playerId = playerId;
    }

    public HashMap<String, String> getCervical_Spine_Activity() {
        return Cervical_Spine_Activity;
    }

    public void setCervical_Spine_Activity(HashMap<String, String> cervical_Spine_Activity) {
        Cervical_Spine_Activity = cervical_Spine_Activity;
    }

    public HashMap<String, String> getGlasgow_Coma_Scale_Test() {
        return Glasgow_Coma_Scale_Test;
    }

    public void setGlasgow_Coma_Scale_Test(HashMap<String, String> glasgow_Coma_Scale_Test) {
        Glasgow_Coma_Scale_Test = glasgow_Coma_Scale_Test;
    }

    public HashMap<String, String> getMemory_Questions() {
        return Memory_Questions;
    }

    public void setMemory_Questions(HashMap<String, String> memory_Questions) {
        Memory_Questions = memory_Questions;
    }

    public HashMap<String, String> getObservable_Signs_Test() {
        return Observable_Signs_Test;
    }

    public void setObservable_Signs_Test(HashMap<String, String> observable_Signs_Test) {
        Observable_Signs_Test = observable_Signs_Test;
    }

    public HashMap<String, String> getRed_Flags_Test() {
        return Red_Flags_Test;
    }

    public void setRed_Flags_Test(HashMap<String, String> red_Flags_Test) {
        Red_Flags_Test = red_Flags_Test;
    }

    public Report getReport() {
        return report;
    }

    public void setReport(Report report) {
        this.report = report;
    }
}

After these changes, you'll have to update the code that uses these classes.


text:
Q: OSGI: Service not available after Bundle update I have a Bundle P(rovider= which implements an Interface Defined in Bundle I(interface) Bundle U(ser) should use this Service. After I started the application everything works fine, all my service can be used. But when I update the Bundle P, non of its service can be resolved.
The update method looks like this:
this._bundle.stop();
this._bundle.update(new FileInputStream(updateFile));
this._bundle.start();

This is my BundleActivator for all of my Packages which also should handle ServiceRegistrations and ServiceReferences:
public abstract class BundleActivator implements org.osgi.framework.BundleActivator, BundleListener, ServiceListener
{
/**
 * Bundle Context.
 */
protected BundleContext context;

/**
 * Services which are registered by this bundle.
 */
protected HashSet<ServiceRegistration> serviceRegistrations = new HashSet<ServiceRegistration>();

/**
 * Service references used by this bundle.
 */
protected HashMap<String, ServiceReference> serviceReferences = new HashMap<String, ServiceReference>();

/**
 * Perform this method after Bundle has started.
 *
 * @param bc BundleContext.
 */
protected abstract void afterStart(BundleContext bc);

/**
 * Perform this method before Bundle is going to be stoped.
 *
 * @param bc BundleContext.
 */
protected abstract void beforeStop(BundleContext bc);

/**
 * Perform this method after Bundle has changed.
 *
 * @param be BundleEvent
 */
protected abstract void afterBundleChanged(BundleEvent be);

/**
 * Returns the bundle context for this bundle.
 *
 * @return bundle context
 */
public BundleContext getContext() {
    return this.context;
}

/**
 * Registeres a service.
 *
 * @param clazz      interface
 * @param service    service
 * @param properties properties
 *
 * @return service registration
 */
public ServiceRegistration registerService(Class clazz, Object service, Dictionary<String, ?> properties) {
    return this.registerService(clazz.getCanonicalName(), service, properties);
}

/**
 * Registeres a service.
 *
 * @param clazz      interface
 * @param service    service
 * @param properties properties
 *
 * @return service registration
 */
public ServiceRegistration registerService(String clazz, Object service, Dictionary<String, ?> properties) {
    ServiceRegistration retval = this.context.registerService(clazz, service, properties);
    System.out.println("registered service: " + retval.toString() + " for " + clazz);
    this.serviceRegistrations.add(retval);
    return retval;
}

/**
 * Returns a registered service.
 *
 * @param clazz interface
 *
 * @return service instance
 */
public Object getService(Class clazz) {
    if (clazz == null) {
        return null;
    }
    return this.getService(clazz.getCanonicalName());
}

/**
 * Returns a registered service.
 *
 * @param clazz interface
 *
 * @return service instance
 */
public Object getService(String clazz) {
    if (clazz == null) {
        return null;
    }
    System.out.println("Class: " + clazz);
    ServiceReference sr = this.context.getServiceReference(clazz);
    System.out.println("SR: " + sr);
    if (sr == null) {
        if (this.serviceReferences.containsKey(clazz)) {
            System.out.println("Unget service");
            this.context.ungetService(this.serviceReferences.get(clazz));
            this.serviceReferences.remove(clazz);
        }
        sr = this.context.getServiceReference(clazz);
        System.out.println("SR: " + sr);
        if (sr == null) {
            return null;
        }
    }

    try {
        this.context.addServiceListener(this, "(objectClass=" + clazz + ")");
    } catch (InvalidSyntaxException ex) {
        Logger.getLogger(BundleActivator.class.getName()).log(Level.SEVERE, null, ex);
    }

    this.serviceReferences.put(clazz, sr);
    return this.context.getService(sr);
}

@Override
public void start(BundleContext bc) throws Exception {
    ContextRegistry.getInstance().add(bc);

    this.context = bc;
    this.context.addBundleListener(this);
    this.afterStart(bc);
    System.out.println("Balindoo bundle activated: " + this.getClass().getPackage().getName());
}

@Override
public void stop(BundleContext bc) throws Exception {
    this.beforeStop(bc);

    for (ServiceRegistration sr : this.serviceRegistrations) {
        this.context.ungetService(sr.getReference());
        sr.unregister();
    }
    this.serviceRegistrations.clear();

    for (ServiceReference sr : this.serviceReferences.values()) {
        this.context.ungetService(sr);
    }
    this.serviceReferences.clear();

    ContextRegistry.getInstance().remove(bc);
    this.context.removeBundleListener(this);
    this.context = null;
    System.out.println("Balindoo bundle deactivated: " + this.getClass().getPackage().getName());
}

@Override
public void bundleChanged(BundleEvent be) {
    String name = be.getBundle().getSymbolicName();
    if (name.startsWith("com.vaadin")) {
        if (be.getType() == BundleEvent.STARTED && !ResourceProvider.getInstance().hasBundle(be.getBundle())) {
            ResourceProvider.getInstance().add(be.getBundle());
        } else if (be.getType() == BundleEvent.STOPPED && ResourceProvider.getInstance().hasBundle(be.getBundle())) {
            ResourceProvider.getInstance().remove(be.getBundle());
        }
    }

    for (ServiceReference sr : this.serviceReferences.values()) {
        this.context.ungetService(sr);
    }
    this.serviceReferences.clear();

    HashSet<Bundle> thisBundle = new HashSet<>();
    thisBundle.add(this.context.getBundle());
    thisBundle.add(be.getBundle());

    FrameworkWiring wiring = this.context.getBundle().adapt(FrameworkWiring.class);
    if (wiring != null) {
        System.out.println("FrameworkWiring:\n\tthis:\t" + this.context.getBundle().getSymbolicName() + "\n\tto  :\t" + be.getBundle().getSymbolicName());
        wiring.refreshBundles(thisBundle);
    }

    this.afterBundleChanged(be);
}

@Override
public void serviceChanged(ServiceEvent event) {
    switch (event.getType()) {
        case ServiceEvent.UNREGISTERING:
            System.out.println("unregister service");
            if (this.serviceReferences.containsValue(event.getServiceReference())) {
                //Remove
            }
            this.context.ungetService(event.getServiceReference());
            break;
    }
}

As you can see, i tried a lot to resolve this Problem, but nothing worked.
What am I doing wrong?
Here is the Manifest for the bundle P (org.company.example.data). The interface is located in org.company.example.data.api which is in a separate bundle.
Manifest-Version: 1.0
Bnd-LastModified: 1381157007428
Build-Jdk: 1.7.0_21
Built-By: nspecht
Bundle-Activator: org.company.example.data.impl.BundleActivator
Bundle-Description: Example Bundle org.company.example.data 1.0.0
Bundle-ManifestVersion: 2
Bundle-Name: org.company.example.data
Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Bundle-SymbolicName: org.company.org.company.example.data
Bundle-Vendor: Company Inc.
Bundle-Version: 1.0.0
Created-By: Apache Maven Bundle Plugin
Eclipse-BuddyPolicy: registered
Eclipse-RegisterBuddy: org.company.wrapper.hibernate
Export-Package: org.company.example.data.api;uses:="org.company.example.data.api.model";version="1.0.0",org.company.example.data.impl;uses:="org.company.example.data.api,org.company.utils.data.database,org.osgi.framework,org.company.example.data.api.model,org.company.utils.modulemanager.generic,org.hibernate,org.hibernate.criterion";version="1.0.0",org.company.example.data;version="1.0.0",org.company.example.data.api.impl;uses:="org.osgi.framework,org.company.utils.modulemanager.generic";version="1.0.0",org.company.example.data.api.model;uses:="org.company.utils.data.api";version="1.0.0",org.company.example.data.i18n;version="1.0.0"
Import-Package: org.company.utils.data.api;version="[1.0,2)",org.company.utils.data.database;version="[1.0,2)",org.company.utils.modulemanager.generic;version="[1.0,2)",org.hibernate;version="4.2,5)",org.hibernate.criterion;version="4.2,5)",org.osgi.framework;version="[1.6,2)"
Tool: Bnd-1.50.0

The Manifest for the Interface bundle:
Manifest-Version: 1.0
Bnd-LastModified: 1381156992131
Build-Jdk: 1.7.0_21
Built-By: nspecht
Bundle-Activator: org.company.example.data.api.impl.BundleActivator
Bundle-Description: Example Bundle org.company.example.data.api 1.0.0
Bundle-ManifestVersion: 2
Bundle-Name: org.company.example.data.api
Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Bundle-SymbolicName: org.company.org.company.example.data.api
Bundle-Vendor: Company Inc.
Bundle-Version: 1.0.0
Created-By: Apache Maven Bundle Plugin
Eclipse-BuddyPolicy: registered
Export-Package: org.company.example.data.api;uses:="org.company.example.data.api.model";version="1.0.0",org.company.example.data.api.impl;uses:="org.osgi.framework,org.company.utils.modulemanager.generic";version="1.0.0",org.company.example.data.api.model;uses:="org.company.utils.data.api";version="1.0.0"
Import-Package: org.company.utils.data.api;version="[1.0,2)",org.company.utils.modulemanager.generic;version="[1.0,2)",org.osgi.framework;version="[1.6,2)"
Tool: Bnd-1.50.0

At least the interface for the Bundle U:
Manifest-Version: 1.0
Bnd-LastModified: 1381157008373
Build-Jdk: 1.7.0_21
Built-By: nspecht
Bundle-Activator: org.company.example.webui.impl.BundleActivator
Bundle-Description: Example Bundle org.company.example.webui 1.0.0
Bundle-ManifestVersion: 2
Bundle-Name: org.company.example.webui
Bundle-RequiredExecutionEnvironment: JavaSE-1.7
Bundle-SymbolicName: org.company.org.company.example.webui
Bundle-Vendor: Company Inc.
Bundle-Version: 1.0.0
Created-By: Apache Maven Bundle Plugin
Eclipse-BuddyPolicy: registered
Export-Package: org.company.example.webui.impl;uses:="org.company.utils.webui,org.company.example.data.api,org.company.example.webui.menu,org.osgi.framework,org.company.utils.webui.menu,org.company.example.webui.view,org.company.utils.modulemanager.generic,org.company.utils.modulemanager.exception";version="1.0.0",org.company.example.webui.menu;uses:="org.company.utils.webui,org.company.utils.webui.generics,org.company.utils.modulemanager.translation,org.company.example.webui.view,org.company.utils.webui.menu";version="1.0.0",org.company.example.webui.i18n;version="1.0.0",org.company.example.webui.view;uses:="org.company.example.data.api,com.vaadin.server,org.company.utils.modulemanager.translation,org.company.example.data.api.model,com.vaadin.ui,org.company.example.webui.impl,com.vaadin.event,org.company.utils.webui.exception,com.vaadin.data,com.vaadin.data.util,com.vaadin.navigator,org.company.utils.modulemanager.exception";version="1.0.0"
Import-Package: com.vaadin.data;version="[7.1,8)",com.vaadin.data.util;version="[7.1,8)",com.vaadin.event;version="[7.1,8)",com.vaadin.navigator;version="[7.1,8)",com.vaadin.server;version="[7.1,8)",com.vaadin.ui;version="[7.1,8)",org.company.example.data.api;version="[1.0,2)",org.company.example.data.api.model;version="[1.0,2)",org.company.utils.modulemanager.exception;version="[1.0,2)",org.company.utils.modulemanager.generic;version="[1.0,2)",org.company.utils.modulemanager.translation;version="[1.0,2)",org.company.utils.webui;version="[1.0,2)",org.company.utils.webui.exception;version="[1.0,2)",org.company.utils.webui.generics;version="[1.0,2)",org.company.utils.webui.menu;version="[1.0,2)",org.osgi.framework;version="[1.6,2)"
Tool: Bnd-1.50.0

A: Check who is exporting the package containing the service interface I. Both P and U must be wired to the same package. In order to ensure U can use the service object, the framework verifies that U is wired to the same package as P.
It appears that after updating P, the new P' is wired to a different revision of the package than U. So when P' registers the service, it comes from a different revision of the package.
This can occur if the package is contained in P and exported by P without having P also import the same package. A service provider should both export and import the service interface package. See http://blog.osgi.org/2007/04/importance-of-exporting-nd-importing.html

A: you most likely need to "refresh" your consuming bundles (U) also, since usually the consuming bundle keeps a reference to the original bundle P and therefore it won't see your new Services. So you need to bring your bundle U back into the "resolving" state. At the GOGO shell you usually just issue the refresh command.


text:
Q: and then it redirects to /adfs/oauth2/authorize/wia? I am doing the authz code grant flow on ADFSv3.
When I do AcquireToken, the usual html web browser authentication prompt is initiated, but for some reason it redirects to the following endpoint /adfs/oauth2/authorize/wia? showing the windows integrated login box.
Question:
is this some sort of ntml/sso thing ADFS provides here?
is it possible to get rid of the initial html web browser and instead directly show the windows login box, it looks kind of like a split personality with 2 authentication prompts (1 disabled, 1 enabled).

A: Is the client computer from which you're doing the AcquireToken flow domain-joined? It's likely not. It looks like it is attempting windows integrated authentication (Kerberos) and falling back to NTLM (Windows credential collection dialog you're seeing).
You can configure the authentication methods offered by ADFS using the ADFS Global Authentication policy (i.e. Set/Get-AdfsGlobalAuthenticationPolicy PowerShell cmdlets) or via the Authentication Policies node in the MMC snap-in. Ensure that you have 'Forms Authentication' enabled for both intranet and extranet locations in the global authentication policy in order to use web-based credential collection experience. You can also choose to turn off Windows Integrated Authentication in the global authentication policy, if you'd like.
If both forms authentication and WIA are enabled for the intranet location, ADFS will prefer to use WIA if the client's user agent/browser is WIA-capable. You can see a list of WIA-capable user agents via the Get-AdfsProperties cmdlets (look for the WIACapableUserAgents setting). Typically browsers like IE are capable of WIA. For user agents that are not on this list, ADFS will automatically fall back to using forms authentication.


text:
Q: OpenGL Vertex shader transformation and output I have a simple vertex shader
#version 330 core

uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform mat4 modelMatrix;

in vec3 in_Position;

out vec3 pass_Color;

void main(void)
{
    //gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(in_Position, 1.0);
    gl_Position = vec4(in_Position, 1.0);
    pass_Color = vec3(1,1,1);
}

In my client code i have
    glm::vec4 vec1(-1,-1,0,1);//first
    glm::vec4 vec2(0,1,0,1);//second
    glm::vec4 vec3(1,-1,0,1);//third
    glm::mat4 m = projectionMatrix * viewMatrix * modelMatrix;

    //translate on client side
    vec1 = m * vec1;
    vec2 = m * vec2;
    vec3 = m * vec3;

    //first vertex
    vertices[0] = vec1.x;
    vertices[1] = vec1.y;
    vertices[2] = vec1.z;
    //second
    vertices[3] = vec2.x;
    vertices[4] = vec2.y;
    vertices[5] = vec2.z;
    //third
    vertices[6] = vec3.x;
    vertices[7] = vec3.y;
    vertices[8] = vec3.z;

Now my question if i use no matrix multiplication in the shader and none in client code this will render me a nice triangle which strectch the whole screen, so i take it the vertex shader maps cordinates its given to the screen in a cordinate system with x=-1..1 and y=-1..1
If i do the matrix multiplication in the shader everything works nice. But if i comment out the code in the shader like shown and do it on the client i get odd results. Shouldnt it yield the same result?
Have i gotten it wrong thinking the output of the vertex shader gl_Position is 2D cordinates despite being a vec4?
Thanks for any help. I really like to understand what exactly the output of the vertex shader is in terms of vertex position.

A: The problem is in your shader as it accepts only 3 components of position. It is OK to set the forth coordinate to 1 (like you do it) if the coordinate is not in projection space yet.
When you are doing the transformation in client space, the results are correct 4-component homogeneous vectors. You just need to use them as is in your vertex shader:
in vec4 in_Position.
...
gl_Position = in_Position.


text:
Q: How can I show the upper and right axes in a bokeh plot? I would like to always show the upper x-axis and right y-axis in my bokeh plots.
Is there a command to simply add these axes to the diagram?

A: If you mean how to show top and right axis line, simply add outline_line_color='black' inside bokeh's plot.figure().


text:
Q: Return XML from Web Api Controller How to specify return xml from web api controller?In one browser data opens as XML,in other as JSON.
Edit
Here is my action:
    [HttpGet]
    public IEnumerable<MagazineMeta> GetLastUploadPdfMeta(int count)
    {
       List<MagazineMeta> metas = _metaRepository
                 .GetAll()
                 .OrderBy(e => e.TimeAdd)
                 .Take(count)
                 .ToList();

       return metas;
    }

A: Add these 2 lines to the end of Application_Start in Global.asax.cs:
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new System.Net.Http.Formatting.XmlMediaTypeFormatter());

EDIT:
As @YishaiGalatzer pointed out, this is rather quick & dirty workaround to achieve what was originally asked in question. To get desired response format include appropriate Accept header  in request (in context of this question, "application/xml")

A: To make response serialize you need one more line
GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;

A: And for others who want to enforce json instead, call this :
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());


text:
Q: Как определить элемент в рулетке У меня есть готовая рулетка, она крутится и при остановке на элементе его рамки горят зелёным. Мне надо узнать, что это за элемент.

  <button class="button">Кнопка</button>

A: Подход в целом неверный. Надо не от сгенерированных пикселей отталкиваться и искать, что это за картинка, а сделать так:

*

*в data атрибут картинок вписать числа 1,2,3, и т.д. В общем пронумеровать.

*Создать массив с числами от 1 до количества кортинок (например 5)

*Сделать рандом именно на числа из массива

*Соотнести число из массива и картинку...и только тогда эту картинку отображать и выделять.


text:
Q: How do I copy only one file (the newest one) from a directory using a shell script on Mac OS X? I'm looking to periodically run a script which copies only the most recently edited file over from one directory, over to another one. How do I do this with a shell script on OSX?

A: The easiest way would be to do this directly through cron. For example, to copy the file once a week, create a crontab like this:
@weekly cp "$(ls -t /path/to/source | head -1)" /path/to/target

DETAILS:
The -t flag of ls means sort by time, so by printing only the first file (head -1) I know I am getting the newest. Running ls -t /path/to/source | head -1 will return the newest file in the directory /path/to/source so cp "$(ls -t /path/to/source | head -1)" /path/to/target will copy the newest file from source to target. The quotes around the expression are needed in order to deal with file names that contain spaces.
Wikipedia explains that

Cron is the time-based job scheduler in Unix-like computer operating systems. Cron enables users to schedule jobs (commands or shell scripts) to run periodically at certain times or dates. It is commonly used to automate system maintenance or administration.
[...]
Cron is driven by a crontab (cron table) file, a configuration file that specifies shell commands to run periodically on a given schedule.

To create a new crontab, open a terminal and run
crontab -e

This will launch your default editor ($EDITOR) and present you with a text file. Paste the line above into that file, save and exit and that's it, your crontab has been created.
The format of crontabs is (taken from here):
*     *     *     *     *  command to be executed
-     -     -     -     -
|     |     |     |     |
|     |     |     |     +----- day of week (0 - 6) (Sunday=0)
|     |     |     +------- month (1 - 12)
|     |     +--------- day of month (1 - 31)
|     +----------- hour (0 - 23)
+------------- min (0 - 59)

So, for example, to run cp /foo /bar at 14:35 on October 12th you would write:
35    14   12      11    cp /foo /bar

The cron daemon also understands some shorthand commands such as:
       string          meaning
       ------          -------
       @reboot         Run once, at startup.
       @yearly         Run once a year, "0 0 1 1 *".
       @annually       (same as @yearly)
       @monthly        Run once a month, "0 0 1 * *".
       @weekly         Run once a week, "0 0 * * 0".
       @daily          Run once a day, "0 0 * * *".
       @midnight       (same as @daily)
       @hourly         Run once an hour, "0 * * * *".

So, the crontab I gave above means run the cp command once a week at midnight on Sunday morning.


text: Q: Cross Domain Scripting I am currently hosting my client side files (.html, .js) on Apache port 80. However, i want to call Jetty server port 8080 where my server side files are being hosted on. Due to the nature of my project (web-chat), the information will be required to be passed back to port 80. What is the best way to get this done? I have researched on cross-domain scripting but it failed to work.