text:
Q: Add a comma after two words in pandas I have the following texts in a df column:
La Palma
La Palma Nueva
La Palma, Nueva Concepcion
El Estor
El Estor Nuevo
Nuevo Leon
San Jose
La Paz Colombia
Mexico Distrito Federal
El Estor, Nuevo Lugar

What I need is to add a comma at the end of each row but the condition that it is only two words.  I found a partial solution:
df['Column3'] = df['Column3'].apply(lambda x: str(x)+',')

(solution found in stackoverflow)

A: Given:
                        words
0                    La Palma
1              La Palma Nueva
2  La Palma, Nueva Concepcion
3                    El Estor
4              El Estor Nuevo
5                  Nuevo Leon
6                    San Jose
7             La Paz Colombia
8     Mexico Distrito Federal
9       El Estor, Nuevo Lugar

Doing:
df.words = df.words.apply(lambda x: x+',' if len(x.split(' ')) == 2 else x)
print(df)

Outputs:
                        words
0                   La Palma,
1              La Palma Nueva
2  La Palma, Nueva Concepcion
3                   El Estor,
4              El Estor Nuevo
5                 Nuevo Leon,
6                   San Jose,
7             La Paz Colombia
8     Mexico Distrito Federal
9       El Estor, Nuevo Lugar


text:
Q: High precision millisecond timer in matlab I'm trying to implement a high-precision, millisecond-timescale timer in matlab. Every T seconds, I want to query a camera linked to matlab, and if there is an image in the memory, I want to pull it out. The actual connection to the camera is straightforward - but a problem arises because images are coming in every ~60ms, and need to all be pulled off before another image enters the camera buffer. This essentially means that I need to be checking the camera buffer at least every ~30ms, and ideally every ~5ms.
While MATLAB's built in timer function ostensibly allows millisecond timing, it suffers from poor precision. While in >95% of executions the built in MATLAB timer will indeed pause for ~5ms between runs, in ~5% of cases it hovers around ~30ms, and in ~1% of cases it takes >100ms between executions, which unacceptably kills the performance. I should clarify in MATLAB's defense that simultaneously there are two other timers running (both with 1 s periods), as well as a number of figure windows open, so even though my machine is beefy (16-core, 64GB RAM), there is certainly a lot to be doing all at once. I have tried using timers based on .NET timers (System.Timers.Timer(period)) as well as with the Java sleep function (java.lang.Thread.sleep(period)), both of which should theoretically be more precise, and while both are better than the MATLAB timer (at the cost of being more unwieldy), none are able to consistently achieve <60ms execution delay across thousands of iterations.
Maybe I'm asking for something which is not implementable - but I hope that there is some way to implement a high-precision timer in MATLAB which will continue executing at a ms time-scale even when there are other figures/timers/commands being executed semi-simultaneously. I should maybe clarify that when running just a timer with no other timers/figures open I am able to consistently achieve <60ms execution (and really, consistent <10ms execution for a 5ms timer period). This is possible even when all those timers/figures are open in a different instance of MATLAB, so it seems the problem is to somehow separate the timer from the rest of MATLAB. Any advice or guidance would be appreciated in this regard.

A: Depending on what exactly you are doing, the timing system of Psychtoolbox may help you.
Specifically, check out the WaitSecs function and its documentation. It is supposed to be more precise than timer, and the documentation contains some tips about achieving high precision timing in general.
Also related is the GetSecs function.
It might however happen that switching to WaitSecs will not help you. In that case you can be quite sure that your machine is just too loaded to do what you are trying to do.

redpajama_set_name: RedPajamaStackExchange


text:
Q: can boost::managed_shared_memory handle vector correctly? Here is the official example to use vector in shared memory between processes:
http://www.boost.org/doc/libs/1_55_0/doc/html/interprocess/quick_guide.html#interprocess.quick_guide.qg_interprocess_container
However I still have some concern:

*

*what if the vector need to reallocate new memory(e.g. after several push_back)?

*what if the vector keep increasing and finally consume all the initialized memory?

*what's the performance penalty by comparing with the original STL vector?

A: *

*It does so via the custom ShmemAllocator. That's how allocators work: you swap out the standard heap-allocator that calls new for Boost's one that allocates from the shared memory segment.

*Same behaviour as running out of memory with the standard allocator: an exception will be thrown (not std::bad_alloc though: it's apparently boost::interprocess::bad_alloc instead).

*You'll want to benchmark the Boost's allocator's allocation speed, and compare it with that of std::allocator, which is the default. The vector itself does not really matter.

A: There are 2 separate entities here

*

*Vector

*Allocator

When you create vector as
vector <int> v1;

It is actually
vector<int, allocator<int>> v1;

We don't provide any memory allocator because its the defult allocator.
Now in the case of Boost.Interprocess communication, the vector is created as
typedef vector<int, ShmemAllocator> MyVector

Where the memory allocator is changed to Shared Memory Allocator from Default Allocator.
So, the functionality of vector is independent of which memory allocator one uses.
Regarding the questions, the availability of memory and speed of the allocation depends upon allocators and not on vectors, as long as allocators manage to get some memory, vectors will continue to perform.


text:
Q: Variational Principle for an Elliptic equation I wish to find the functional whose minimisation yields the follwoing equation on the vector function u
$(\lambda + \mu) \nabla (\nabla \cdot u) + \mu \nabla^{2} u = 0$,
the Navier equation of linear elasticity.
I know that this equation has a vaiational principle from physical reasons, but struggle to find it. The term containing the laplacian is easier to handle, I can not even prove simmetry of the weak form for the first one: how to integrate by parts (grad div u) v to obtain a term symmetric in u e v?
Many thanks

A: By a corollary of the divergence theorem:
$$\int_\Omega \nabla(\nabla\cdot u)\cdot v = - \int_\Omega \nabla\cdot u\,\nabla\cdot v + \int_{\partial\Omega}(\nabla\cdot g)v\cdot n.$$


text:
Q: How to keep beacon in pairing mode until it comes out of range for android? I am developing an application to communicate with beacon. It display all the names of beacons, I have to pair & connect to beacon on onclick event.I need to keep beacon in connecting mode until it goes out of range. But in my case it disconnects after certain amount of time.Please tell me how to keep beacon in pairing mode until it comes out of range.
Below is my code for pairing beacon to android app.
 private void pairDevice(BluetoothDevice device) {
    try {
        Method method = device.getClass().getMethod("createBond", (Class[]) null);
        method.invoke(device, (Object[]) null);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

A: It is common for Android Bluetooth LE connections to disconnect before you are finished communicating, so you must build logic into your app to handle these disconnect events and retry the connection as needed.
If you Bluetooth LE beacon is exiting connectable mode before you can do this, then you must somehow extend the time it is in this mode.  How you do this is (if it is possible at all) is manufacturer-specific, so you'll have to consult your beacon manufacturer's documentation on how you put the beacon into configurable mode.


text:
Q: How to pass networkImageView to another fragment? bitmap or URI long story short, ive got fragmnet (catalog) which holds cardview, that fills from json file that stream from my server.
on card click, im poping DialogFragment, that asks the user to fill how many items he want from this specific "product", after i get the quantity, my dilemma starts...
How to pass the image itself to the dialog and from the dialog to the fragment (userCart),
 I want to display the image again in listview in  userCartFragment.
I know passing view isn't a solution, but i read that maybe with uri its is possible, and so with the bitmap convertion to array.
Which way you guys think would be better, or maybe you have any better solution for this.
Any advise/snippet  would be appreciated!
Thank you!

A: Use Uri to pass images.
Otherwise, if the image size is too large it might create some memory issues. Also, there is a size limit (1 MB) in passing extras between activities or fragments.
Check this link

A: Better Solution: Load image with URI
The reason:Simple&Uncomplicated,
If you use Glide, you just code like this
Glide.with(this).load("YOUR URL").into(imageView);
It's just one step. Make's your URL to be public static so variable can access in all class.
If you use bitmap conversion at least you need 3-4 step so you can load image to another fragment.


text:
Q: Is there a way to get rid of the Runaway Promise warning when using react-query I am using react-query useQuery as follows:
const { isLoading, error, data } = useQuery('repoData', () => {
        return fetch('https://api.github.com/repos/tannerlinsley/react-query').then(res =>
            res.json()
        )
    }
)

It generates the following warning:
Warning: a promise was created in a handler at webpack-internal:///./node_modules/react-query/es/core/retryer.js:68:50 but was not returned from it.
Is there anyway to remove it.
I am using Typescript


text:
Q: Grouping different amounts together in MongoDB If I have a set of objects each with the same description, but with different amounts.
{

    {
    "_id": "101",
    "description": "DD from my employer1",
    "amount": 1000.33
    },
    {
    "_id": "102",
    "description": "DD from my employer1",
    "amount": 1000.34
    },
    {
    "_id": "103",
    "description": "DD from my employer1",
    "amount": 1000.35
    },
    {
    "_id": "104",
    "description": "DD from employer1",
    "amount": 5000.00
    },
    {
    "_id": "105",
    "description": "DD from my employer2",
    "amount": 2000.33
    },
    {
    "_id": "106",
    "description": "DD from my employer2",
    "amount": 2000.33
    },
    {
    "_id": "107",
    "description": "DD from my employer2",
    "amount": 2000.33
    }

}

Below, I am able to group them using the description:
{

    {
        "$group": {
            "_id": {
                "description": "$description"
            },
            "count": {
                "$sum": 1
            },
            "_id": {
                "$addToSet": "$_id"
            }
        }
    },
    {
        "$match": {
            "count": {
                "$gte": 3
            }
        }
    }

}

Is there a way to include all the amounts in the group (_ids: 101, 102, and 103 plus 105,106,107) even if they have a small difference, but exclude the bonus amount, which in the sample above is _id 104?
I don't believe it could be done in a group stage, but is there something that could be done at a later stage that could group _ids 101, 102 and 103 together and exclude _id 104.  Basically, I want MongoDB to ignore the small differences in 101, 102, 103 and group them together since the are paychecks coming from the same employer.
I have been working with $stdDevPop, but can't get a solid formula down.
I am looking for a simple array output of just the _ids.
{
  "result": [
      "101",
      "102",
      "103",
      "105",
      "106",
      "107"
  ]
}

A: db.yourDBNameHere.aggregate( [
  { $match: { "amount" : { $lt : 5000 } } },
  { $project: { _id: 1 } },
])

that will grab the ID only of every transaction less than 5000$.

A: You can do this by doing some math on the "amount" to round it down to the nearest 1000 and use that as the grouping _id:
db.collection.aggregate([
  { "$group": {
      "_id": {
        "$subtract": [
           { "$trunc": "$amount" },
           { "$mod": [
             { "$trunc": "$amount" },
             1000
           ]}
         ]
      },
      "results": { "$push": "$_id" }
  }},
  { "$redact": {
    "$cond": {
      "if": { "$gt": [ { "$size": "$results" }, 1 ] },
      "then": "$$KEEP",
      "else": "$$PRUNE"
    }
  }},
  { "$unwind": "$results" },
  { "$group": {
    "_id": null,
    "results": { "$push": "$results" }
  }}
])

If your MongoDB is older than 3.2 then you would just need to use a long form with $mod of what $trunc is doing. And if your MongoDB is older than 2.6 then rather than $redact you would $match. So in the longer form this is:
db.collection.aggregate([
  { "$group": {
      "_id": {
        "$subtract": [
           { "$subtract": [
             "$amount",
             { "$mod": [ "$amount", 1 ] }
           ]},
           { "$mod": [
             { "$subtract": [
               "$amount",
               { "$mod": [ "$amount", 1 ] }
             ]},
             1000
           ]}
         ]
      },
      "results": { "$push": "$_id" },
      "count": { "$sum": 1 }
  }},
  { "$match": { "count": { "$gt": 1 } } },
  { "$unwind": "$results" },
  { "$group": {
    "_id": null,
    "results": { "$push": "$results" }
  }}
])

Either way the output is just the _id values whose amounts grouped to the boundaries with a count more than once.
{ "_id" : null, "results" : [ "105", "106", "107", "101", "102", "103" ] }

You could either add a $sort in there or live with sorting the result array in client code.


text:
Q: Recursively enumerable language of Turing machines If you have the language $L_{h}=\{M_{i} | (\exists z \in \sum ^{*}) M_{i}\text{ halts  on  some  input } z\}$
where $M_{i}$ are Turing machines, is $L_{h}$ recursively enumerable?
I'm fairly certain it is, but I'm having issues proving that to be the case.
The way I understand RE languages is that they CAN be infinite, which this language most certainly is, but I have no idea where to go from there.
Thanks in advance.

A: Hint:

*

*First, is the language of all Turing machines enumerable?

*Consider a language $L_i = \{M_i \mid M_i \text{ halts on some input }\}$. Its size is at most $1$, how to "enumerate it"?

*Run in parallel $L_i$ for all Turing machines, and if some of $L_i$ finishes, output its unique element.

I hope this helps $\ddot\smile$


text:
Q: NestJS validate POST body when it's other than object type I need to validate a list of emails (array of strings) that are passed via POST. Using something like validation pipes and class-validator would be awesome (however in the official docs I only found examples of objects validation through DTOs and validation of primitive types but for GET requests).
Here is how my method looks like in the controller:
@Post()
async submit(@Body() emails: string[]) {
}

A: If it's just being passed directly like that, then there's not much you can do besides implement a custom pipe. If you are able to change the payload structure I would suggest it to something like
export class PostDTO {
  @IsEmail({ each: true })
  emails: string[]
}

And use
@Post()
async submit(@Body() { emails }: PostDTO) {}

so that Nest's ValidationPipe can read the metadata of the post.


text:
Q: extjs treenode add radio group as node property I'd like this effect.

I wouldn't like Take a nap show as a non-leaf node with 10 minutes and 20 minutes show as leaf child nodes of Take a nap node.
I try with code
    children: [{
        text: 'Take a nap <input type="radio" checked/>10 minutes<input type="radio"/>20 minutes',
        leaf: true,
    },{......}]

It can show as my expection. But can not work since the radio button can't be clicked.
And I don't like implement with menu like this:
    var menu1 = new Ext.menu.Menu({
        items: [
        '<b class="menu-title">Choose Time</b>',
        {
            text: '10 minutes',
            checked: true,
            group: 'time'
        }, {
            text: '20 minutes',
            checked: false,
            group: 'time'
        }]
    });

    children: [{
        text: 'Go jogging',
        leaf: true,

        listeners: {
            'click': function(node,event) {

                x = event.browserEvent.clientX;
                y = event.browserEvent.clientY;
                menu1.showAt([x, y]);
            }
        }
    }

Can extjs do this?
Demo In jsfiddle, for convenience.


text:
Q: Select similar phrases in Microsoft Word I need to select and highlight many sentences in which Microsoft Word in which the start word and the end word of the sentence/phrase is the same, but the content in between is different.
How can I achieve this using the find function in word? I want to automate doing this as it should be possible, only thing is I don't know how to achieve this. It would take a very long time for me to manually highlight so many phrases

A: Try using regular expressions.
Microsoft has a tutorial here:


text:
Q: Angular Promise not resolved I have a subscribe function in my class which subscribes to a state of a checkbox toggle:
public subscribe(): void{
   ...
// Subscribe to toggle subject state
    this.subscription = this.isSet$
      .pipe(
        // Skip initial toggle state
        skip(1),
        // Update persisted FCM enabled state
        tap(isSet => {
          localStorage.setItem(PushService.localStorageKey, String(isSet));
        }),
        // Switch between function calls based on the toggle state
        switchMap(isSet => (isSet ?
          this.requestToken()
            .then(() => {
              console.log('RESOLVED REQUEST');
              this.cbDisabled = false;
            }) :
          this.deleteToken()
            .then(() => {
              console.log('RESOLVED DELETE');
              this.cbDisabled = false;
            }))))
      .subscribe();
}

The 2 Promises in the switchMap look like that:
REQUEST
private requestToken(): Promise<any> {

    console.log('REQUEST TOKEN FROM FIREBASE');

    return this.afMessaging.requestToken.pipe(
      mergeMap(deviceToken =>
        this.http.post<void>(
          formatEndpointUrl(environment.endpoints.communicationservice.web_push.register_device),
          {deviceToken}
        )
      )
    ).toPromise();
  }

DELETE
private deleteToken(): Promise<void> {

    console.log('DELETE TOKEN CALLED');

    return this.afMessaging.getToken.pipe(
      tap((deviceToken) => {
        this.afMessaging.deleteToken(deviceToken);
        console.log('DELETING TOKEN IN FIREBASE');
      }),
      mergeMap(deviceToken =>
        this.http.delete<void>(
          formatEndpointUrl(environment.endpoints.communicationservice.web_push.delete_device, {deviceToken})
        ).toPromise().then(() => {
           console.log('DELETING TOKEN IN BACKEND');
        })
      )).toPromise();
  }

When I toggle the Switch to OFF, it deletes the Token, the log looks like this:
DELETE TOKEN CALLED
DELETING TOKEN IN FIREBASE
DELETING TOKEN IN BACKEND
RESOLVED DELETE

However, when I toggle the Switch to ON, I get this:
REQUEST TOKEN FROM FIREBASE

and that is it, the Promise never gets resolved. What am I missing?


text:
Q: What is the difference between Selenium's mouseMove() and an actual mouse movement? Let's say I have element A and an element B. I've fired up Selenium or PhantomJS, which also has the capability to move the mouse via coordinate sets.
I locate the shape of element A (a link) and element B (a submit button). I draw a bezier curve or transform a pre-recorded human mouse movement to go from element A to element B.
My intuition is that mouseMove() simply "teleports" the cursor to that coordinate set. How is this different than actually using a mouse?
If I track users' mouse movements on my site, will I be able to tell, assuming they use sophisticated movement curves, that they are using an automation tool?

A: From my experience if you track the mouse from JS and a bot simply uses selenium to move the mouse pointer without a "sophisticated movement curves" the answer is yes.
But,
if the 'bot' is specifically designed to create a "sophisticated movement curves" or for example "replay a recorded movement data set", i think you cannot. (Similar question also with negative answer).
So,
You can just devise an "heuristic solution" but not a perfect one. If it is what you want i can try to give you some ideas. Otherwise, if you can follow other paths i would advise you some sort of selenium detection or captcha.


text:
Q: Have three 3 numbers to work with. None match = 0, 2 match = 10, if all match = 20 This is my code, it's not returning 10 when only two out of the three numbers match.
def green_ticket_value(a, b, c):
  if a != b or b != c or a != c:
    return 0
  elif a == b and a != c or b == c and b != a or a == c and a!= b:
    return 0
  else: a == b == c
  return 20

A: First of all, the second "return 0" should be "return 10".
Second of all, (this may or may not have an impact), you might need parentheses in the elif line.
def green_ticket_value(a, b, c):
    if a != b or b != c or a != c:
        return 0
    elif (a == b and a != c) or (b == c and b != a) or (a == c and a!= b):
        return 10 # NOT 0
    else: a == b == c
        return 20

A: The problem is with the first if statement logic. You are using or instead of and which is why you never compare the second statement.
assuming a=1 b=2 and c=2
in your current code it is true that a !=b therefore is a valid statement and it returns 0
It should be:
def green_ticket_value(a, b, c):
    if a != b and b != c and a != c:
    #rest of code

you can also use a different method which is to use counter and return the most common value
from collections import Counter

def green_ticket_value(*args):
    green = Counter(args)
    values = {1:0,2:10,3:20}
    return values[green.most_common(1)[0][1]]

A: Think about it this way. If
a != b or b != c or a != c

is false, then
a == b and b == c and a == c

DeMorgan's Laws explain why this is the case. Remember that
~(A \/ B) <-> ~A /\ ~B
~(A /\ B) <-> ~A \/ ~B

Where <-> basically means "equivalent to each other", ~ means "not," \/ means "or", and /\ means "and."
To go through this code:
def green_ticket_value(a, b, c):
    if a != b or b != c or a != c:
       return 0
    # It can *never* be the case that a != c or a != b at this point
    elif a == b and a != c or b == c and b != a or a == c and a!= b:
      return 0 // Should this be "return 10"?
   # What did you mean to do here?
   else: a == b == c
       return 20

It's a little unclear whether you meant
a == b and a != c or b == c and b != a or a == c and a!= b

to mean
(a == b and a != c) or (b == c and b != a) or (a == c and a!= b)

which will always be false (a == c and a == b, which means that all of these conditions are false), or the following:
a == b and (a != c or b == c) and (b != a or a == c) and a!= b

which is also always false (in fact, it's self-refuting because it contains a == b && a != b) or if you meant some other variant. I'd strongly recommend using parenthases here to make it more clear what you're trying to do.
Also, for the last part:
(b == c and b != a) or (a == c and a != b)

a != b and b != a mean the exact same thing, so the above statement means the same thing as
a != b and (a == c or b == c)


text:
Q: Xamarin.Android: Service stopps working when screen off (Doze / App Standby mode) I have to implement a service were I transmit GPS (Lat/Lon) every 120 sec. to my REST backend.
I have the problem that the service seems to stop working when the screen is turned off.

*

*Attempt with a StartedService and a BroadcastReceiver

*Attempt with an IntentService and a WakefulBroadcastReceiver

The 1. Attempt works for example on a SAMSUNG Galaxy X COVER but not on a HUAWEI P9 Lite. Dispite the fact that I turned Power Saving mode (Power Apps) in HUAWEI phone off. So my app keeps running when screen is turned off. After e.g 10 Minutes I turned screen on on the HUAWEI phone and saw in runing services that the service is running (elapsed seconds) so I could verify that the service is not shut down.
The 2. Attempt works on no phone when screen is turned off.
Both attempts are working properly when screen is turned on (no sleep).
Note: For brevity I stripped out the code of not relevant methods (fetch/transfer gps data).
Here is the code for 1. Attempt:
Service
[Service]
public class GpsTrackerService : Service
{
    private static readonly string LogTag = "X:TruckerApp-" + typeof(GpsTrackerService).Name;
    private static readonly int NOTIFICATION_ID = 10000;
    private MobileServiceClient _mobileServiceClient;

    public TelephonyManager GetTelefonyManager()
    {
        return (Android.Telephony.TelephonyManager) GetSystemService(TelephonyService);
    }

    public bool IsRunningAsService { get; set; }

    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        Log.Debug(LogTag, "GpsTrackerService.OnStartCommand :: Service started. Timer instantiated.");
        GpsTrackerServiceUtils.SendGenericMessageToApplicationInsights("Gps-Info", LogTag, _mobileServiceClient, this, "GpsTrackerService.OnStartCommand :: Service started.Timer instantiated.");

        Task.Run(async () =>
        {
            try
            {
                await DoWork();
                await Task.Delay(TimeSpan.FromMinutes(2));
            }
            catch (Exception e)
            {
                Log.Debug(LogTag, $"GpsTrackerService.HandleTimerCallback :: (OUTER try-catch) Exception:{e.Message} Type:{e.GetType().Name}, Stacktrack:{e.StackTrace}");
                if (e.InnerException != null)
                {
                    Log.Debug(LogTag, $"GpsTrackerService.HandleTimerCallback :: (OUTER try-catch) Exception:{e.InnerException.Message} Type:{e.InnerException.GetType().Name}, Stacktrack:{e.InnerException.StackTrace}");
                }
                GpsTrackerServiceUtils.SendExceptionToApplicationInsights(e, LogTag, _mobileServiceClient, this);
            }
            finally
            {
                // Restart Service
                Intent broadcastIntent = new Intent(action: GpsConstants.GpsRestart);
                SendBroadcast(broadcastIntent);
            }

        });

        return StartCommandResult.Sticky;
    }

      public override IBinder OnBind(Intent intent)
    {
        // This is a started service, not a bound service, so we just return null.
        return null;
    }
}

BroadcastReceiver
[BroadcastReceiver(Enabled = true, Exported = true, Name = GpsConstants.GpsBroadcastReceiver, Label = "RestartServiceWhenStopped")]
[IntentFilter(new[] {GpsConstants.GpsRestart})]
public class GpsTrackerServiceBroadcastReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        try
        {
            MetricsManagerHelper.Instance.SendGenericMessageToApplicationInsights("Gps-Info", "OnReceive :: Gps Service broadcast message received. Restarting GPS Service...");
            context.StartService(new Intent(context, typeof(GpsTrackerService)));
         }
        catch (Exception e)
        {
            MetricsManagerHelper.Instance.SendExceptionToApplicationInsights(e);
        }
    }
}

Register Broadcastreceiver in MainActivity.OnCreate
 GpsTrackerServiceBroadcastReceiver = new GpsTrackerServiceBroadcastReceiver();
 RegisterReceiver(GpsTrackerServiceBroadcastReceiver, new IntentFilter(GpsConstants.GpsBroadcastReceiver));

2.Attempt
Service
[Service]
public class GpsTrackerIntentService : IntentService
{
    private static readonly string LogTag = "X:TruckerApp-" + typeof(GpsTrackerIntentService).Name;
    private static readonly int NOTIFICATION_ID = 10000;
    private MobileServiceClient _mobileServiceClient;

    public TelephonyManager GetTelefonyManager()
    {
        return (TelephonyManager) GetSystemService(TelephonyService);
    }

    protected override async void OnHandleIntent(Intent intent)
    {
        try
        {
            // perform task
            await Bootstrap();

            GpsTrackerServiceUtils.SendGenericMessageToApplicationInsightsWakeLock("Gps-Info", LogTag, _mobileServiceClient, this, "GpsTrackerService.OnHandleIntent :: Invoked.");

            await DoWork();
            await Task.Delay(TimeSpan.FromMinutes(2));
        }
        catch (Exception e)
        {
            Log.Debug(LogTag, $"GpsTrackerService.OnCreate :: Exception:{e.Message} Type:{e.GetType().Name}");
            GpsTrackerServiceUtils.SendExceptionToApplicationInsightsWakeLock(e, LogTag, _mobileServiceClient, this);
        }
        finally
        {
            WakefulBroadcastReceiver.CompleteWakefulIntent(intent);
            SendBroadcast(new Intent(this, typeof(GpsTrackerServceWakefulReceiver)));
            //var wakefulReceiverIntent = new Intent(this, typeof(GpsTrackerServceWakefulReceiver));
            //var pending = PendingIntent.GetBroadcast(this, 0, wakefulReceiverIntent, PendingIntentFlags.UpdateCurrent);
            //AlarmManager manager = (AlarmManager)GetSystemService(AlarmService);
            //manager.SetRepeating(AlarmType.RtcWakeup, SystemClock.ElapsedRealtime(), 120 * 1000, pending);
        }
    }

    public async Task DoWork()
    {
        // long running code ...
        Log.Debug(LogTag, "GpsTrackerService.HandleTimerCallback :: Invoked.");
        GpsTrackerServiceUtils.SendGenericMessageToApplicationInsightsWakeLock("Gps-Info", LogTag, _mobileServiceClient, this, "GpsTrackerService.HandleTimerCallback :: Invoked.");

    }
}

WakefulReceiver
[BroadcastReceiver]
public class GpsTrackerServceWakefulReceiver : WakefulBroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        var serviceIntent = new Intent(context, typeof(GpsTrackerIntentService));
        StartWakefulService(context, serviceIntent);
    }
}

AndroidManifest.xml
added WAKE_LOCK permission
  <uses-permission android:name="android.permission.WAKE_LOCK"/>
  <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>

I got really desperate now. Hope someone can help me.
Thanks
Eric


text:
Q: Updating attribute based on time - Rails I building a rewards system for a coffee shop. Basically a customer can sign up for a year subscription. Right now when they sign up the active attribute is toggled to true. I'm trying to write a method that will toggle the attribute to false after a year passes. I have a method right now that I want to use but I don't know where to use it at? I also have a failing test. I'll show my current code for clarity.
Controller:
  def create
    @subscriber = Subscriber.new(subscriber_params)
    if @subscriber.save
      @subscriber.touch(:subscription_date)
      @subscriber.update(active: true)
      SubscriberMailer.welcome_subscriber(@subscriber).deliver_now
      flash[:notice] = "Subscriber Has Been Successfully Created"
      redirect_to new_subscriber_path(:subscriber)
    else
      render "new"
    end
  end

Model method I want to use:
    def not_active(subscriber)
    if subscription_date < 1.year.ago
      self.update(active: false)
    end
  end

Failing Test:
  it "sets active to false after a year" do
    subscriber = create(:subscriber)
    subscriber.update(active: true)

    Time.now + 366.days

    expect(subscriber.active).to eq(false)
  end

So hopefully this idea is clear. I just want to update to active: false if the user was created over a year ago.

A: You must run the not_active method in order for the method to have an effect. The method has no way of knowing what the date is today and updating a subscriber unless it is actually run. I agree with matt that you would likely run this method in a sidekiq job daily on on all of your subscribers who subscribed a year or longer ago and are active (You can write a scope for this). This way you can call the not_active method and set each subscriber's active appropriately, or write it as a Subscriber class method and apply it to the results of your scope. In the case of testing the not_active method itself all you need to do is call it and test the result. Its also not clear to me why the not_active method takes a subscriber as an arg, it seems like it would make more sense to just call it from a subscriber instance. Is this not whats already happening? I would personally call this method something like deactivate!, as its making changes. not_active kind of sounds like it would return a boolean or an inactive subscriber. I would also recommend using update! instead of update in not_active. update! will raise an error if the update fails. Adding to time.now does actually change the time. You can use rspec mocks to fake the current time if you need to. In any case here is what your not_active test might look like:
it "sets active to false after a year" do
    subscriber = Subscriber.create(subscription_date: (1.year.ago - 1.day), active: true)

    #changed not_active to deactivate, called from instance instead of passing in subscriber
    subscriber.deactivate!

    expect(subscriber.active?).to eq(false)
end

You can also write a test for the other case
it "does not deactivate a recent subscriber" do
    subscriber = Subscriber.create(subscription_date: Date.today, active: true)

    subscriber.deactivate!

    expect(subscriber.active?).to eq(true)
end

A: A simple solution to this would be to use cron. There is a rubygem to interface with cron, called whenever. The setup is simple and well documented.
With cron setup on your server, you would create some kind of class method that would iterate through Subscribers, calling the not_active method.
Btw, if the not_active method is defined within your Subscriber model, you won't need to pass subscriber as an argument, as self will be implicitly set to the subscriber.
The code would end up looking something like:
in subscriber.rb
def self.set_subscribers_to_inactive
  find_each(active: false) do |subscriber|
    subscriber.inactive!
  end
end

def inactive!
  update(active: false) if subscription_date < 1.year.ago
end

in schedule.rb
every 1.day do
  runner "Subscriber.set_subscribers_to_inactive"
end

As mentioned, your test is not actually calling the not_active method.
it "sets active to false after a year" do
  last_year = DateTime.current - 366.days
  subscriber = create(:subscriber, active: true, subscription_date: last_year)
  subscriber.inactive!

  expect(subscriber.active).to eq false
end

A: Take a look at cron and whenever gem which works on top of cron. You just need to write a super simple script which will extract data from DB and update it.
Another way to solve your problem is not to update anything. You only need *_expires_at column and check if its value less than current date.
It is pretty agile method, because by using activation_expires_at column you are able to implement #active? method and .active scope to select only users with active subscriptions.


text:
Q: Difficulty implementing a linked list in C++ I am trying to implement a linked-list in C++. Currently, I have the following code:
using namespace std;

struct CarPart
{
    int partNumber;
    char partName[40];
    double unitPrice;

    CarPart* Next;
};

class ListOfParts
{
private:
    int size;
    CarPart* Head;
public:
    ListOfParts():size(0), Head(NULL)
    {
    }

    int Count()
    {
        return size;
    }
};

Here the problem is, ideally, I should keep the Stuct CarPart within my Class. But I do not want to. At the same time, I don't want this to be acccessble anywhere from outside.
Can I have a some way, without creating a structure within the Class? Instead creating a new Class CarPart which could be accessible from only class ListOfPart?s

A: Well, as a first suggestion, have you considered using std::list? It would save you the trouble of implementing your own linked list semantics. Unless you're writing a linked list for the learning experience (which can be valuable), I suggest using:
struct CarPart
{

    int partNumber;
    std::string partName;
    double unitPrice;
};

std::list<CarPart> ListOfParts;

You'll also notice I'm using std::string for text, which I suggest you use (unless you have a very good reason not to).
To the question at hand: you could declare the constructor for CarPart private, and then declare ListOfParts as a friend class, that's one way. But consider this: what do you gain by disallowing the construction of a car part external to the list of parts? I can't see that you gain anything. In fact, by using friends you introduce unnecessary complexity into the structure of your code - as using the dreaded 'friend' keyword usually does. Anyway, if you did want to use the friend class method, you would write:
class ListOfParts;
struct CarPart
{
    friend class ListOfParts;

    int partNumber;
    char partName[40];
    double unitPrice;
    CarPart* Next;

private:

    CarPart()
    {
        // Do nothing.
    }
};

Which would mean only ListOfparts could call the default constructor for the list CarPart. Let me make this very clear: this is an abhorrent solution because it breaks rules of encapsulation. But, like mutable, friends have a use (and this isn't it).

A: What you're asking is contradictory.  Either you want CarPart to be accessible from outside (in which case you declare it as a separate class or as a public member) or you don't want it accessible (in which case you declare it as a private member).
Consider making your class a little more generic:  instead of having it be a linked list of CarParts, make it a class template that makes a linked list of Nodes that each has a T.   If you are allowed to, you should be using std::list anyway, but you could write your own if you had to/really wanted to.
Also, classes and structs are basically the same thing; the only difference is that class members and inheritance are by default private, and struct members and inheritance are by default public. (The keywords are not always interchangeable, though.)

A: You can move your CarPart struct to a separate header and include this header only in the ListOfParts implementation part (yes, you need to separate definitions from implementations).
And don't forget a forward declaration
struct CarPart

before defining
class ListOfParts


text:
Q: I have a datatable in Javascript and (almost) everything works fine, but i don't know how to refer to a value in the same row...any ideas? Basically, I have a button in every row in the third column, and when the user clicks on the button, I would like to call a function with parameters (they are from the table row). I saw that someone use row.errorType (for example), but that's gave me 'undefined' value :( Any ideas?
            columns: [
                {
                    "data": "errorType",
                    "render": function (data) {
                        return data;
                    }
                },
                {
                    "data": "errorDescription",
                    "render": function (data) {
                        return data;
                    }
                },
                {
                    "data": "entityId",
                    "render": function (data, row) {
                        return `<button class="newError" onclick="openModal(${row.errorType}, ${row.errorDescription}, ${data})"><i class="icon ticket errorTableIcon"></i></button>`;
                    }
                }
            ],

A: You are using the DataTables columns.render option, but you are not supplying the expected parameters.
You are using:
"render": function (data, row) { ... }

You should be using:
"render": function (data, type, row, meta) { ... }

So, what you are referring to as row is actually type. Change your parameters as shown above to pick up the row data object correctly - and then you should be able to use variables such as row.errorType in your string builder.

You still need to ensure that variables which resolve to strings are themselves enclosed in quotes, so your string template may need to be adjusted.
For example, you may need "${row.errorDescription}" instead of ${row.errorDescription}.


text:
Q: how to add multiple columns in listbox? I want to create a listbox in gwt , which will contain two columns- say, name and sirname.These both columns should be visible. When I will select an item from listbox ,  I should be able to get both these values. Also, is it possible to add column name in listbox which will remain unclickable?
I have tried this-
ListBox allRecs=new ListBox();
allRecs.addItem(name,sirname);

but here, sirname remains invisible.
Thanks

A: You can't do that with a plain ListBox which is wrapper for something like this:
select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

Plain GWT does not offer this out of the box.
But you can create a textfield and a button (the button will show a popup with a table).
There you can define as many columns as you like, make any rows you want unclickable etc.


text:
Q: GPS module not showing useful information using Arduino I have connected the GPS module with Arduino board, however, when I open the serial monitor, it shows a lot of empty fields and zeros. Is the GPS module faulty?
It shows this :
$GPGSA,A,1,,,,,,,,,,,,,,,*1E
$GPRMC,000053.799,V,,,,,0.00,0.00,060180,,,N*43
$GPVTG,0.00,T,,M,0.00,N,0.00,K,N*32
$GPGGA,000054.799,,,,,0,0,,,M,,M,,*4E
$GPGSA,A,1,,,,,,,,,,,,,,,*1E
$GPRMC,000054.799,V,,,,,0.00,0.00,060180,,,N*44
$GPVTG,0.00,T,,M,0.00,N,0.00,K,N*32
$GPGGA,000055.799,,,,,0,0,,,M,,M,,*4F
$GPGSA,A,1,,,,,,,,,,,,,,,*1E

A: All this means is that your GPS doesn't have a fix yet.
A cold start on a GPS can take several minutes (like, up to 7 or so) to get its initial fix.  Make sure the antenna is out in the open with a clear view of the sky.
Also, obviously, if your GPS unit has an external antenna, make sure it's connected properly.  Those small coaxial connectors break easily!


text:
Q: How to create a WPF Window without a border that can be resized? Is there a way in WPF where I can remove the main window's border, yet allow that window to be resized (without grip)?
I realized there's a way to do this scenario by setting resize mode to CanResizeWithGrip. However, I want to be able to do it with the resize mode set to CanResize.
I tried setting the following:
ResizeMode="CanResize"
WindowStyle="None"
AllowsTransparency="True"

However, by setting AllowsTransparency, it removes the ability to resize without the grip. Any ideas how I can pull this off?
I also should note that I can't set AllowsTransparency to true anyway, because I am using a winformshost control in my window, which is not shown when AllowsTransparency  is true.

A: I know this is an old question, but I just wanted to put up a working sample for newcomers.
Xaml Window:
<Window x:Class="CustomWindowDemo.DemoCustomWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:CustomWindowDemo"
        mc:Ignorable="d"
        Title="DemoCustomWindow" Height="300" Width="300" Background="{x:Null}" AllowsTransparency="True" WindowStyle="None">
    <Window.Resources>
        <Style x:Key="BorderThumb" TargetType="Thumb">
            <Setter Property="SnapsToDevicePixels" Value="true" />
            <Setter Property="OverridesDefaultStyle" Value="true" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Thumb">
                        <Rectangle MinWidth="4" MinHeight="4" StrokeThickness="0">
                            <Rectangle.Fill>
                                <SolidColorBrush Color="{DynamicResource {x:Static SystemColors.HighlightColorKey}}" Opacity="0.05"/>
                            </Rectangle.Fill>
                        </Rectangle>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Border BorderBrush="#55FFFFFF" BorderThickness="1" CornerRadius="5">
        <Grid>
            <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition/>
                    <ColumnDefinition Width="Auto"/>
                </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition/>
                    <RowDefinition Height="Auto"/>
                </Grid.RowDefinitions>
            <Border MouseMove="Header_MouseMove" DockPanel.Dock="Top" Height="32"  Grid.Row="1" Grid.Column="1">
                    <Border.Background>
                        <LinearGradientBrush StartPoint="0,0" EndPoint="0,3">
                            <GradientStop Color="#3BB2EA" Offset="0" />
                            <GradientStop Color="#EFF7FA" Offset="0.3" />
                        </LinearGradientBrush>
                    </Border.Background>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition/>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="Auto"/>
                            <ColumnDefinition Width="Auto"/>
                        </Grid.ColumnDefinitions>
                        <TextBlock VerticalAlignment="Center" HorizontalAlignment="Left" Margin="10,0,0,0" Text="{Binding Path=Title, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}"/>
                        <Button x:Name="btn_Minimize" Background="{x:Null}" BorderBrush="{x:Null}" Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" BorderThickness="0" Click="btn_Minimize_Click" Grid.Column="1">
                            <Image Source="Resources/Ahmadhania-Spherical-Minimize.ico"/>
                        </Button>
                        <Button x:Name="btn_Maximize" Background="{x:Null}" BorderBrush="{x:Null}" Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" BorderThickness="0" Grid.Column="2" Click="btn_Maximize_Click">
                            <Image Source="Resources/1412181205_61002.ico"/>
                        </Button>
                        <Button x:Name="btn_Close" Background="{x:Null}" BorderBrush="{x:Null}" Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" BorderThickness="0" Grid.Column="3" Click="btn_Close_Click">
                            <Image Source="Resources/Ahmadhania-Spherical-Close(1).ico"/>
                        </Button>
                    </Grid>
                </Border>
            <Thumb x:Name="ThumbBottom" DragDelta="ThumbBottom_DragDelta" HorizontalAlignment="Stretch" Cursor="SizeNS" Grid.Column="0" Background="{x:Null}"  Margin="3,0" Grid.ColumnSpan="3" Grid.Row="3" Style="{Binding Mode=OneWay, Source={StaticResource BorderThumb}}"/>
            <Thumb x:Name="ThumbTop" DragDelta="ThumbTop_DragDelta" HorizontalAlignment="Stretch" Cursor="SizeNS" Grid.Column="0" Background="{x:Null}"  Margin="3,0" Grid.ColumnSpan="3" Height="4" Style="{Binding Mode=OneWay, Source={StaticResource BorderThumb}}"/>
            <Thumb x:Name="ThumbBottomRightCorner" DragDelta="ThumbBottomRightCorner_DragDelta" HorizontalAlignment="Right" Cursor="SizeNWSE" Grid.Row="3" Grid.Column="3" Background="{x:Null}" Style="{Binding Mode=OneWay, Source={StaticResource BorderThumb}}"/>
            <Thumb x:Name="ThumbTopRightCorner" DragDelta="ThumbTopRightCorner_DragDelta" HorizontalAlignment="Right" Cursor="SizeNESW" Grid.Row="0" Grid.Column="2" Background="{x:Null}" Style="{Binding Mode=OneWay, Source={StaticResource BorderThumb}}"/>
            <Thumb x:Name="ThumbTopLeftCorner" DragDelta="ThumbTopLeftCorner_DragDelta" HorizontalAlignment="Left" Cursor="SizeNWSE" Grid.Row="0" Grid.Column="0" Background="{x:Null}" Style="{Binding Mode=OneWay, Source={StaticResource BorderThumb}}" />
            <Thumb x:Name="ThumbBottomLeftCorner" DragDelta="ThumbBottomLeftCorner_DragDelta" HorizontalAlignment="Left" Cursor="SizeNESW" Grid.Row="3" Grid.Column="0" Background="{x:Null}" Style="{Binding Mode=OneWay, Source={StaticResource BorderThumb}}" />
            <Thumb x:Name="ThumbRight" DragDelta="ThumbRight_DragDelta" Cursor="SizeWE" Grid.Column="2" Grid.RowSpan="4" Background="{x:Null}"  Margin="0,3" Style="{Binding Mode=OneWay, Source={StaticResource BorderThumb}}"/>
            <Thumb x:Name="ThumbLeft" DragDelta="ThumbLeft_DragDelta" Cursor="SizeWE" Grid.Column="0" Grid.RowSpan="4" HorizontalContentAlignment="Right" Background="{x:Null}" Margin="0,3" Style="{Binding Mode=OneWay, Source={StaticResource BorderThumb}}"/>
            <Grid x:Name="Grid_Content" Background="#EFF7FA" Grid.Row="2" Grid.Column="1">

            </Grid>
        </Grid>
    </Border>
</Window>

C# code behind:
using System.Windows.Interop;
using winforms = System.Windows.Forms;

namespace CustomWindowDemo
{
    /// <summary>
    /// Interaction logic for DemoCustomWindow.xaml
    /// </summary>
    public partial class DemoCustomWindow : Window
    {
        bool Maximized = false;
        int NormalWidth = 0;
        int NormalHeight = 0;
        int NormalX = 0;
        int NormalY = 0;

        public DemoCustomWindow()
        {
            InitializeComponent();
        }

        #region Header & Resize
        void Header_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (e.LeftButton == System.Windows.Input.MouseButtonState.Pressed)
                this.DragMove();
        }

        void ThumbBottomRightCorner_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
        {
            if (this.Width + e.HorizontalChange > 10)
                this.Width += e.HorizontalChange;
            if (this.Height + e.VerticalChange > 10)
                this.Height += e.VerticalChange;
        }
        void ThumbTopRightCorner_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
        {
            if (this.Width + e.HorizontalChange > 10)
                this.Width += e.HorizontalChange;
            if (this.Top + e.VerticalChange > 10)
            {
                this.Top += e.VerticalChange;
                this.Height -= e.VerticalChange;
            }
        }
        void ThumbTopLeftCorner_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
        {
            if (this.Left + e.HorizontalChange > 10)
            {
                this.Left += e.HorizontalChange;
                this.Width -= e.HorizontalChange;
            }
            if (this.Top + e.VerticalChange > 10)
            {
                this.Top += e.VerticalChange;
                this.Height -= e.VerticalChange;
            }
        }
        void ThumbBottomLeftCorner_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
        {
            if (this.Left + e.HorizontalChange > 10)
            {
                this.Left += e.HorizontalChange;
                this.Width -= e.HorizontalChange;
            }
            if (this.Height + e.VerticalChange > 10)
                this.Height += e.VerticalChange;
        }
        void ThumbRight_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
        {
            if (this.Width + e.HorizontalChange > 10)
                this.Width += e.HorizontalChange;
        }
        void ThumbLeft_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
        {
            if (this.Left + e.HorizontalChange > 10)
            {
                this.Left += e.HorizontalChange;
                this.Width -= e.HorizontalChange;
            }
        }
        void ThumbBottom_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
        {
            if (this.Height + e.VerticalChange > 10)
                this.Height += e.VerticalChange;
        }
        void ThumbTop_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
        {
            if (this.Top + e.VerticalChange > 10)
            {
                this.Top += e.VerticalChange;
                this.Height -= e.VerticalChange;
            }
        }

        void btn_Minimize_Click(object sender, RoutedEventArgs e)
        {
            WindowState = WindowState.Minimized;
        }
        void btn_Maximize_Click(object sender, RoutedEventArgs e)
        {
            if (Maximized == true)
            {
                this.Width = NormalWidth;
                this.Height = NormalHeight;
                this.Left = NormalX;
                this.Top = NormalY;
                Maximized = false;
                Thumbs();
            }
            else
            {
                NormalX = (int)this.Left;
                NormalY = (int)this.Top;
                NormalHeight = (int)this.Height;
                NormalWidth = (int)this.Width;
                this.Left = winforms.Screen.FromHandle(new WindowInteropHelper(this).Handle).WorkingArea.Left;
                this.Top = winforms.Screen.FromHandle(new WindowInteropHelper(this).Handle).WorkingArea.Top;
                this.Width = winforms.Screen.FromHandle(new WindowInteropHelper(this).Handle).WorkingArea.Width;
                this.Height = winforms.Screen.FromHandle(new WindowInteropHelper(this).Handle).WorkingArea.Height;
                Maximized = true;
                Thumbs();
            }
        }
        void btn_Close_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }
        void Thumbs()
        {
            if (Maximized == true)
            {
                ThumbBottom.Visibility = Visibility.Collapsed;
                ThumbLeft.Visibility = Visibility.Collapsed;
                ThumbTop.Visibility = Visibility.Collapsed;
                ThumbRight.Visibility = Visibility.Collapsed;
                ThumbTopLeftCorner.Visibility = Visibility.Collapsed;
                ThumbTopRightCorner.Visibility = Visibility.Collapsed;
                ThumbBottomLeftCorner.Visibility = Visibility.Collapsed;
                ThumbBottomRightCorner.Visibility = Visibility.Collapsed;
            }
            else
            {
                ThumbBottom.Visibility = Visibility.Visible;
                ThumbLeft.Visibility = Visibility.Visible;
                ThumbTop.Visibility = Visibility.Visible;
                ThumbRight.Visibility = Visibility.Visible;
                ThumbTopLeftCorner.Visibility = Visibility.Visible;
                ThumbTopRightCorner.Visibility = Visibility.Visible;
                ThumbBottomLeftCorner.Visibility = Visibility.Visible;
                ThumbBottomRightCorner.Visibility = Visibility.Visible;
            }
        }
        #endregion
    }
}

A: This can happen if ResizeBorderThickness is set to 0.
It can be set to a positive value in XAML like this:
<WindowChrome>
    <WindowChrome.ResizeBorderThickness>
        <Thickness>1</Thickness>
    </WindowChrome.ResizeBorderThickness>
</WindowChrome>

A: You can use the WPF customizable window library, available here: http://wpfwindow.codeplex.com/
Then, when using the library's window type, you can set the same properties as you listed above
<CustomWindow:EssentialWindow x:Class="CustomWindowDemo.DemoEssentialWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:CustomWindow="clr-namespace:CustomWindow;assembly=CustomWindow"
    AllowsTransparency="True" ResizeMode="CanResize" WindowStyle="None" Title="EssentialWindow"
    Height="300" Width="250">

A: The user needs something to interact with to resize the window.  If you don't like the default border or grip, you'll need to add some other control with a click and drag behavior that resizes the window.  Perhaps a line on each edge of the window?

A: The simplest, but maybe too simple is
this.MouseLeftButtonDown += delegate { this.DragMove(); };


text:
Q: Why is choice returning errorlevels oddly? choice /c 123456789 >NUL
if errorlevel = 9 if %ui9%==9 set "ui9=X" & set /a moves = %moves% + 1 & goto :medmodulebot
if errorlevel = 8 if %ui8%==8 set "ui8=X" & set /a moves = %moves% + 1 & goto :medmodulebot
if errorlevel = 7 if %ui7%==7 set "ui7=X" & set /a moves = %moves% + 1 & goto :medmodulebot
if errorlevel = 6 if %ui6%==6 set "ui6=X" & set /a moves = %moves% + 1 & goto :medmodulebot
if errorlevel = 5 if %ui5%==5 set "ui5=X" & set /a moves = %moves% + 1 & goto :medmodulebot
if errorlevel = 4 if %ui4%==4 set "ui4=X" & set /a moves = %moves% + 1 & goto :medmodulebot
if errorlevel = 3 if %ui3%==3 set "ui3=X" & set /a moves = %moves% + 1 & goto :medmodulebot
if errorlevel = 2 if %ui2%==2 set "ui2=X" & set /a moves = %moves% + 1 & goto :medmodulebot
if errorlevel = 1 if %ui1%==1 set "ui1=X" & set /a moves = %moves% + 1 & goto :medmodulebot
cls
echo That spot's already taken
ping localhost -n 3 >NUL
goto medmoduleuser

I'm making a tic-tac-toe bot. When entering a digit such as 9, then entering it again in the next turn, it will trigger the if errorlevel = 8 if %ui8%==8 set "ui8=X" & set /a moves = %moves% + 1 & goto :medmodulebot instead of just going through the code until it hits the bottom... It seems that choice is returning errorlevels oddly? What do I do to prevent this?

A: In addition to the comments, errorlevel testing could be avoided completely. By converting the choice value into the literal value with a for / F loop metavariable

@echo off & Setlocal ENABLEdelayedexpansion
Rem // script body
For /F "Delims=" %%C in ('Choice /N /C:123456789') do (
    if !ui%%C!==%%C (
        set "ui%%C=X"
        set /a moves+=1
        goto :medmodulebot
    )
)
cls
echo That spot's already taken
ping localhost -n 3 >NUL
goto medmoduleuser


text:
Q: java.lang.IllegalStateException: Failed to read Class-Path attribute from manifest of jar error using Selenium through Maven in Spring Boot I have been running in to various issues while trying to configure selenium webdriver to test my spring boot application. Every time I put the selenium dependency in to my pom.xml it seems to corrupt my m2 repository, or that is what I think.
This is the dependency:
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>3.141.59</version>
</dependency>

This is the error message:
Exception in thread "main" java.lang.IllegalStateException: Failed to read Class-Path attribute from manifest of jar file:/C:/Users/Usuario/.m2/repository/commons-codec/commons-codec/1.11/commons-codec-1.11.jar
at org.springframework.boot.devtools.restart.ChangeableUrls.getUrlsFromClassPathOfJarManifestIfPossible(ChangeableUrls.java:132)
at org.springframework.boot.devtools.restart.ChangeableUrls.fromClassLoader(ChangeableUrls.java:98)
at org.springframework.boot.devtools.restart.DefaultRestartInitializer.getUrls(DefaultRestartInitializer.java:92)
at org.springframework.boot.devtools.restart.DefaultRestartInitializer.getInitialUrls(DefaultRestartInitializer.java:56)
at org.springframework.boot.devtools.restart.Restarter.<init>(Restarter.java:142)
at org.springframework.boot.devtools.restart.Restarter.initialize(Restarter.java:556)
at org.springframework.boot.devtools.restart.RestartApplicationListener.onApplicationStartingEvent(RestartApplicationListener.java:76)
at org.springframework.boot.devtools.restart.RestartApplicationListener.onApplicationEvent(RestartApplicationListener.java:50)
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:127)
at org.springframework.boot.context.event.EventPublishingRunListener.starting(EventPublishingRunListener.java:69)
at org.springframework.boot.SpringApplicationRunListeners.starting(SpringApplicationRunListeners.java:48)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:302)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248)
at pe.backend.BackendApplication.main(BackendApplication.java:10)

I have tried cleaning my m2 repository various times and adding different versions of the dependency, but It doesn't seem to solve it. I have also tried using clean install, but it shows a build error if I have put the selenium dependency.

A: This error message...
Exception in thread "main" java.lang.IllegalStateException: Failed to read Class-Path attribute from manifest of jar file:/C:/Users/Usuario/.m2/repository/commons-codec/commons-codec/1.11/commons-codec-1.11.jar

...implies that one of the jars in your maven cache corrupted.
In your case, it seems the the following file got corrupted:
file:/C:/Users/Usuario/.m2/repository/commons-codec/commons-codec/1.11/commons-codec-1.11.jar

Solution
You need to remove the specific jar from your maven cache and re-build your application.
As you have already tried cleaning the m2 repository various times through clean install but the error persists you may need to hard delete this particular jar and rebuild your application.

Outro
You can find a relevant discussion in:

*

*Devtools startup exception


text:
Q: Chart.js Stacked Bar Chart with Groups I have used Chart.js to draw a Stacked Bar Chart with Groups.
I want customization in it.
I want to show one bar as a completed bar and another one as Not Completed bar
As shown in the below.
Blue, Red, Yellow are the different applications. The bar shows no of task completed and not completed count against each application.

Questions
1) How can I wrap the text Not Completed as it is overlapping on another bar ?
2) On hover the the tooptip also overlaps on another bar please find the below image for the ref

Code written by me is as below
    <!doctype html>

    Stacked Bar Chart with Groups

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<script src="../../utils.js"></script>
<style>
canvas {
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
}
</style>

<script>
    var barChartData = {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
        datasets: [{
            label: 'Member Agreement Tracker',
            backgroundColor: window.chartColors.red,
            stack: 'Stack 0',
            data: [
                66,
                93,
                31,
                76,
                39,
                75,
                36
            ]
        }, {
            label: 'Employee On Boarding',
            backgroundColor: window.chartColors.blue,
            stack: 'Stack 0',
            data: [
                76,
                203,
                41,
                86,
                49,
                85,
                46
            ]
        }, {
            label: 'Vendor Payment',
            backgroundColor: window.chartColors.yellow,
            stack: 'Stack 0',
            data: [
                76,
                103,
                41,
                86,
                49,
                85,
                46
            ]
        }, {
            label: 'Employee On Boarding',
            backgroundColor: window.chartColors.blue,
            stack: 'Stack 1',
            data: [
                56,
                56,
                83,
                21,
                66,
                29,
                65
            ]
        }]

    };
    window.onload = function() {
        var ctx = document.getElementById('canvas').getContext('2d');
        window.myBar = new Chart(ctx, {
            type: 'bar',
            data: barChartData,
            options: {
                title: {
                    display: true,
                    text: 'Wisdom Application My To Do'
                },
                legend: {
                    display: false
                },
                tooltips: {
                    enabled: true,
                    custom: function (tooltipModel) {

                    }
                },
                animation: {
                  duration: 1000,
                  currentStep:1,
                  onComplete: function() {
                    var chartInstance = this.chart,
                    ctx = chartInstance.ctx;
                    ctx.textAlign = 'center';
                    ctx.textBaseline = 'bottom';
                    var stackGroup = [];
                    var stackIndex = [];
                    for (index = 0; index < this.data.datasets.length; index++) {
                        var stackName = this.data.datasets[index].stack;
                        var stack = { Name : stackName, stackIndex : index}
                        var result = stackGroup.filter(obj => {
                          return obj.Name === stackName
                        });
                        if(result.length>0){
                            var sliceCount = stackGroup.findIndex(x => x.Name==stackName);
                            stackGroup.splice(sliceCount, true);
                            stackIndex.splice(sliceCount, true);
                            stackGroup.push(stack);
                            stackIndex.push(stack.stackIndex);
                        }
                        else{
                            stackGroup.push(stack);
                            stackIndex.push(stack.stackIndex);
                        }
                    }
                    this.data.datasets.forEach(function(dataset, i) {
                      var meta = chartInstance.controller.getDatasetMeta(i);
                      meta.data.forEach(function(bar, index) {
                        var data = dataset.data[index];
                        var result = stackGroup.filter(obj => {
                          return obj.stackIndex === i
                        });
                        if(result.length>0){
                            if(result[0].Name=="Stack 0"){
                                ctx.fillText("Completed", bar._model.x, bar._model.y - 5);
                            }
                            if(result[0].Name=="Stack 1"){
                                var str = "Not<br/>Completed";
                                var html = $.parseHTML(str);
                                ctx.fillText("NotCompleted", bar._model.x, bar._model.y - 5);
                            }
                        }
                        //if($.inArray(i, stackIndex) !== -1){
                            //ctx.fillText(data, bar._model.x, bar._model.y - 5);
                        //}
                      });
                    });
                  }
                },
                responsive: true,
                scales: {
                    xAxes: [{
                        stacked: true
                    }],
                    yAxes: [{
                        stacked: true,
                         scaleLabel: {
                            display: true,
                            labelString: 'Task Count'
                          }
                    }]
                }
            }
        });
    };

    document.getElementById('randomizeData').addEventListener('click', function() {
        barChartData.datasets.forEach(function(dataset) {
            dataset.data = dataset.data.map(function() {
                return randomScalingFactor();
            });
        });
        window.myBar.update();
    });
</script>


text:
Q: check if bson array include string id I would like to know if an array of bsons include a string id, something like this:
[186] pry(main)> changed = [BSON::ObjectId('5ae9972ea8abbc3c5484cd5e')]
=> [BSON::ObjectId('5ae9972ea8abbc3c5484cd5e')]
[187] pry(main)> changed
=> [BSON::ObjectId('5ae9972ea8abbc3c5484cd5e')]
[188] pry(main)> manager_to_remove = "5ae9972ea8abbc3c5484cd5e"
=> "5ae9972ea8abbc3c5484cd5e"
[189] pry(main)> manager_to_remove
=> "5ae9972ea8abbc3c5484cd5e"
[190] pry(main)> changed.include?(manager_to_remove).inspect
=> "false"

I'm always getting false.
Thank you!

A: Converting manager_to_remove to BSON::ObjectId works:
require 'bson'
changed = [BSON::ObjectId('5ae9972ea8abbc3c5484cd5e')]
manager_to_remove = BSON::ObjectId("5ae9972ea8abbc3c5484cd5e")
changed.include?(manager_to_remove).inspect # => "true"


text:
Q: Look for a particular constraint in mysql One of my friend created a table in mySQl, how can I check whether he applied  a particular constraint on a column name or not.
In my case, I want to verify whether he applied a CHECK constraint on the column CHG_HOUR or not? The query DESC JOB does not help me with the 'CHECK' constraint.
mysql> desc JOB;
+--------------+---------------+------+-----+---------+-------+
| Field        | Type          | Null | Key | Default | Extra |
+--------------+---------------+------+-----+---------+-------+
| JOB_CODE     | char(3)       | NO   | PRI | NULL    |       |
| JOB_CLASS    | char(30)      | YES  |     | NA      |       |
| CHG_HOUR     | decimal(12,2) | YES  |     | NULL    |       |
| OVERTIME_CHG | int(11)       | NO   |     | NULL    |       |
+--------------+---------------+------+-----+---------+-------+
4 rows in set (0.00 sec)

A: Short answer: he didn't.
MySQL doesn't support check constraints until 8.0.16 which, at the time of writing, does not seen to be even released.


text:
Q: Can you extend Google Identity Toolkit to include facebook/twitter/etc? I decided to look into using Google Identity Toolkit. I knew I liked the UI, and the idea of using a "federated" login system. I'm now having my doubts, as while my site works well with gmail/ymail/hotmail etc, it doesn't seem to support any of the social platforms.
Essentially, I just need an email address from people to be registered with the site, so I thought GITKit was the perfect solution.
Should I have gone down a custom route (like stackoverflow?), or have I missed some of the GITKit documentation?
Any help would be much appreciated.

A: I did do a fair amount of googling prior to posting that question. However, I have come accross some answers. Rather than delete my post - I guess I should share the information. If others thought the information was clear, please delete this thread!
Firstly, there is a page identifying how to add custom IDP's: https://sites.google.com/site/gitooldocs/customidps
There is also a sample site (http://www.openidsamplestore.com/localmapping/) which uses facebook.

How does the advanced demo work for identity providers who are not
E-mail providers, such as social networks?
The hardest part about
designing the advanced site was to find a way to handle all the
edge-cases that can happen with these types of identity providers.
Google previously published a summary of best-practices for
account-linking that describes why these types of identity providers
are so much harder to support.  However this demo provides a user
self-service mechanism for all the tricky cases to avoid the costs
that a website might otherwise occur if those users contact a customer
support representative.

Finally, a best practices run-down is available here:
https://sites.google.com/site/oauthgoog/UXFedLogin/loginlogic
EDIT 1 :

If that identity provider asserts email addresses that it does not
host, we suggest you also implement additional account linking logic.
A future version of GITKit will add support for these type of
identity providers, such as social networks, which will avoid the need
to implement that logic

Perhaps GITKit is the future after-all... Would be nice to have an idea of the time-frame in which this support will be added though...
EDIT 2 :
Direct from the horses mouth (Eric Sachs @ Google - Source Link):

That feature is not expected to be generally available in 2011.  We
are shooting for Q1 2012

A: Looks like someone got it working back in Dec 2011 but there is still an outstanding issue with mapping the id returned to an email address. It was probably resolved:
https://groups.google.com/forum/#!searchin/google-identity-toolkit/facebook/google-identity-toolkit/2218yW4zXw8/28X7btJEh_sJ
Here is the documentation for the sample store including brief info on basic, mobile and advanced mode (using facebook):
https://sites.google.com/site/oauthgoog/Home/openidsamplesite
An out-of-the-box IDP for facebook and twitter has not yet been released.


text:
Q: Android using Fragment instead of activity for a library I am using this library MaterialSearchView in my app for implementing Gmail like search view. The library has provided the implementation details using an Activity. I tried the code inside a fragment, making the necessary changes.
To implement it we do something like this from an activity:
MaterialSearchView searchView = (MaterialSearchView) findViewById(R.id.search_view);

But, I am using a fragment instead so what I do is:
searchView = (MaterialSearchView) getActivity().findViewById(R.id.search_view);

Everything works fine except the VoiceSearch. The library implements voice search using the following code:
private void onVoiceClicked() {
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak an item name or number");    // user hint
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);    // setting recognition model, optimized for short phrases – search queries
    intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);    // quantity of results we want to receive
    if (mContext instanceof Activity) {
        ((Activity) mContext).startActivityForResult(intent, REQUEST_VOICE);
    }

How can I make this work? mContext in the above code is set inside the constructor as:
public MaterialSearchView(Context context) {
    this(context, null);
}

How can I make it work from a fragment? Code for the library

A: mContext might not be an Activity.
Try using this logic (copied from MediaRouteButton.getActivity()) to get the Activity.
Activity getActivity() {
    Context context = getContext();
    while (context instanceof ContextWrapper) {
        if (context instanceof Activity) {
            return (Activity)context;
        }
        context = ((ContextWrapper)context).getBaseContext();
    }
    return null;
}


text:
Q: Magento Email not included header and footer I use community magento 1.9.1.0
All emails sent from the store without the included header and footer, instead, is the code the same as in the template:
{{template config_path="design/email/header"}}
{{inlinecss file="email-inline.css"}}

I checked the file header.html and footer.html in the directory:
app/locale/en_US/template/email/html
and are there.
where should I look for error?

A: I recommend you do an update via shell ./mage upgrade-all or via magento connect.
I had magento 1.9.0.1 with the same problem. I upgraded via shell to 1.9.1.0 and the email header/footer issue was fixed!
You should now see an options for Email Header Template, Email Footer Template and Non-inline CSS File(s) under Design > Transactional Emails.


text:
Q: PyGObject GtkFileChooserDialog default button When I create a GtkFileChooserDialog in Glade and then connect that to a Python class using Gtk.Builder, how do I tell it which is the default button?
Currently, my 'Open' button is the stock gtk-open button and when it's clicked, run() returns 0.  But double-clicking on a file or selecting a file and pressing Enter doesn't do anything.  As far as I can see, this is because the dialog doesn't know what the default button is in Glade, possibly because the 'Open' button isn't using one of GTK_RESPONSE_ACCEPT, GTK_RESPONSE_OK, GTK_RESPONSE_YES or GTK_RESPONSE_APPLY as its response code; but how do I set the response code to one of these when the button is created through Glade?
I'm using Gtk 3, Python 3 and PyGObject (ie gi.repository).
Edit: Here is the relevant bit of the Glade file:

  <object class="GtkFileChooserDialog" id="file_chooser">
    <property name="can_focus">False</property>
    <property name="modal">True</property>
    <property name="type_hint">dialog</property>
    <property name="select_multiple">True</property>
    <child internal-child="vbox">
      <object class="GtkBox">
        <property name="can_focus">False</property>
        <property name="orientation">vertical</property>
        <property name="spacing">2</property>
        <child internal-child="action_area">
          <object class="GtkButtonBox">
            <property name="can_focus">False</property>
            <property name="layout_style">end</property>
            <child>
              <object class="GtkButton" id="button1">
                <property name="label">gtk-cancel</property>
                <property name="visible">True</property>
                <property name="can_focus">True</property>
                <property name="receives_default">True</property>
                <property name="use_stock">True</property>
              </object>
              <packing>
                <property name="expand">True</property>
                <property name="fill">True</property>
                <property name="position">0</property>
              </packing>
            </child>
            <child>
              <object class="GtkButton" id="button2">
                <property name="label">gtk-open</property>
                <property name="visible">True</property>
                <property name="can_focus">True</property>
                <property name="receives_default">True</property>
                <property name="use_stock">True</property>
              </object>
              <packing>
                <property name="expand">True</property>
                <property name="fill">True</property>
                <property name="position">1</property>
              </packing>
            </child>
          </object>
          <packing>
            <property name="expand">False</property>
            <property name="fill">False</property>
            <property name="position">0</property>
          </packing>
        </child>
        <child>
          <placeholder/>
        </child>
      </object>
    </child>
    <action-widgets>
      <action-widget response="-1">button1</action-widget>
      <action-widget response="-5">button2</action-widget>
    </action-widgets>
  </object>

A: You can set the response id to a button in Glade. (General>Response ID) The response types are here.
GTK_RESPONSE_NONE    is -1
GTK_RESPONSE_REJECT  is -2
GTK_RESPONSE_ACCEPT  is -3
... so on until ...
GTK_RESPONSE_HELP    is -11

A: Try
dialog.set_default_response(Gtk.ResponseType.YES)

Can't tell for sure how to change response code on Glade, but it shouldn't matter to you if you just write the handler for your`s Gtk.ResponseType.YES code
EDIT:
If you were not using glade things like that are wired already
dialog = builder.get_object("file_chooser")
dialog.connect('file-activated', self.file_selected)

def file_selected(self, dialog):
    dialog.emit('response', Gtk.ResponseType.OK)

It is important to resume operations after You run() your dialog so emit this signal and do nothing more


text:
Q: How to ignore a route in zuul? I have a spring application, in which I use zuul for routing. My routing configuration is like this:
zuul:
  routes:
    core:
      path: /core/**
      url: http://localhost:3002
    ui:
      path: /**
      url: http://localhost:3003

Now I defined a rest controller in my app, and it should serve the captcah service beside its routing. So I used ignored-services: /captcha/** and even ignored-patterns: /captcha/**
But it don't work and requests for captcah are routed to the ui path.
My using zuul version is: org.springframework.cloud:spring-cloud-starter-zuul:1.0.3.RELEASE

A: its ignoredPatterns instead of ignored-pattern
zuul:
    ignoredPatterns:
        - ...........
routes:
core:
  path: /core/**
  url: http://localhost:3002
ui:
  path: /**
  url: http://localhost:3003


text:
Q: AndEngine how to make a sprite not jump if jump method is called So I have this method that when i touch the screen my sprite will jump. Now the problem is when I continuously touch the screen the sprite will jump again and again. What I want to do is if it jumps, the jump method cannot be called unless my sprite hits the ground.
Here is the code.

public class PhyiscsActivity extends BaseGameActivity implements IAccelerometerListener, IOnSceneTouchListener{

private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
private Camera mCamera;
private BitmapTextureAtlas mBitmapTextureAtlas;
private TiledTextureRegion mTextureRegion;
private Scene mScene;
private FixtureDef mFixtureDef = PhysicsFactory.createFixtureDef(1,-10f, 0.5f);
private PhysicsWorld mPhysicsWorld;
private Body body;
private AnimatedSprite facebox;
private FixtureDef wallfixture = PhysicsFactory.createFixtureDef(-1,0.5f, 0.5f);
@Override
public Engine onLoadEngine() {
    // TODO Auto-generated method stub
    this.mCamera = new Camera(0,0,CAMERA_WIDTH, CAMERA_HEIGHT);
    final EngineOptions mEngineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT),this.mCamera);
    mEngineOptions.getTouchOptions().setRunOnUpdateThread(true);
    return new Engine(mEngineOptions);
}

@Override
public void onLoadResources() {
    // TODO Auto-generated method stub
    this.mBitmapTextureAtlas = new BitmapTextureAtlas(128,128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
    this.mTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(mBitmapTextureAtlas, this, "gfx/face_box_tiled.png", 0, 0, 2, 1);
    this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas);
}

@Override
public Scene onLoadScene() {
    // TODO Auto-generated method stub
    this.mEngine.registerUpdateHandler(new FPSLogger());
    this.mScene = new Scene();
    this.mScene.setBackground(new ColorBackground(1,1,1));
    this.mPhysicsWorld = new PhysicsWorld(new Vector2(0,SensorManager.GRAVITY_EARTH),false);

    // This is the walls
    final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2);
    final Shape ground = new Rectangle(0,CAMERA_HEIGHT - 2,CAMERA_WIDTH,2);
    final Shape left = new Rectangle(0,0,2,CAMERA_HEIGHT);
    final Shape right = new Rectangle(CAMERA_WIDTH -2, 0,2,CAMERA_HEIGHT);
    PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallfixture);
    PhysicsFactory.createBoxBody(this.mPhysicsWorld,  roof, BodyType.StaticBody, wallfixture);
    PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallfixture);
    PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallfixture);

    // This is the Sprite
    facebox = new AnimatedSprite(30,(CAMERA_HEIGHT - 2) -  this.mTextureRegion.getHeight()  ,this.mTextureRegion);
    body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, facebox, BodyType.DynamicBody, mFixtureDef);
    this.mScene.attachChild(facebox);

    this.mScene.registerUpdateHandler(this.mPhysicsWorld);
    this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(facebox,body,true,true));
    this.mScene.setOnSceneTouchListener(this);
    return this.mScene;

}

@Override
public void onLoadComplete() {
    // TODO Auto-generated method stub

}

//Accelerometer
@Override
public void onAccelerometerChanged(AccelerometerData pAccelerometerData) {
    // TODO Auto-generated method stub
    final Vector2 gravity = Vector2Pool.obtain(pAccelerometerData.getX()* 3, 10);
    this.mPhysicsWorld.setGravity(gravity);
    Vector2Pool.recycle(gravity);
}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    this.enableAccelerometerSensor(this);
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    this.disableAccelerometerSensor();
}

//This is where i make the sprite jump
@Override
public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
    pSceneTouchEvent.isActionDown();{
        this.jump(facebox);
    }
    return false;

}
public void jump(AnimatedSprite sprite){
    boolean jumping = false;
    if(!jumping ){
        body.setLinearVelocity(new Vector2(body.getLinearVelocity().x,-8f));
        }
    }

public void jump(AnimatedSprite sprite){
    if(!jumping){
       body.setLinearVelocity(new Vector2(body.getLinearVelocity().x,-10));
       jumping = true;
    }

    }

@Override
public void beginContact(Contact contact) {
    // TODO Auto-generated method stub
    jumping = true;
}

@Override
public void endContact(Contact contact) {
    // TODO Auto-generated method stub
jumping = false;
}

I don't know why the beginContact and endContact isn't initialzing. are there things that i should do to initialize this? example like updating a handler? contactlistener?

A: You need to have a method wich tell you if your player is jumping or not.
public void jump(AnimatedSprite sprite){

    if( isJumping(sprite)){
        body.setLinearVelocity(new Vector2(body.getLinearVelocity().x,-8f));
        }

In this method you should put the way to compute if the player is jumping. Like if he is touching a wall (if player's body (x,y) is in a wall (rectangle))
Ok you are using box2d to make physics =)
You have to create a ContactListener, you have to implement this class and the function ou want to add.
http://code.google.com/p/andenginephysicsbox2dextension/source/browse/src/com/badlogic/gdx/physics/box2d/ContactListener.java?r=1605f6e82f710ef9ebbe07632d6b055239d3b520
public void beginContact (Contact contact);
public void endContact (Contact contact);

The contact object will countain your objects (Fixture) that are touching. You just have to check and set jumping to false when the body is touching and true when you call jump and you  can jump, set jumping to true;
Ok?
@Override
public void beginContact(Contact contact) {
    // TODO Auto-generated method stub
    jumping = true;
}

@Override
public void endContact(Contact contact) {
    // TODO Auto-generated method stub
jumping = false;
}

This is false.. I would think of it like that only:
@Override
public void beginContact(Contact contact) {
    jumping = false; //you touched ground so you aren't jumping anymore
}

@Override
public void endContact(Contact contact) {
jumping = true; //you leave ground so you're jumping
}

and one jump method (not two):
   public void jump(AnimatedSprite sprite){
        if(!jumping ){
            jumping = true;
            body.setLinearVelocity(new Vector2(body.getLinearVelocity().x,-8f));
            }
        }

You see?;


text:
Q: Override templates in Django-LFS I'm a n00b in django, I have done the polls tutorial and not too much more. I want to set up an online shop with Lightning Fast Shop (LFS), which does pretty much anything I need. I know it would be desirable to have a better django base...
One of the first steps I want to do, is to customize a little bit the templates. Here is an explanation about how to do it:
http://play.pixelblaster.ro/blog/archive/2009/09/17/customizing-django-lfs-lightning-fast-shop-for-the-non-django-developer
The FLS frameworks is properly installed: I can open the site, define products, add products to the cart, etc.
I have configured the settings.TEMPLATE_DIRS so that it points to a inner folder into my project. It seems I got it right, because when I drop there a template base.html, I get the following error:
NoReverseMatch at /
'url' requires a non-empty first argument. The syntax changed in Django 1.5, see the docs.

... a lot of information...

Error during template rendering

In template c:\development\......\lfs-installer\lfs_project\theme\templates\lfs\base.html, error at line 47
'url' requires a non-empty first argument. The syntax changed in Django 1.5, see the docs.
37
38
39          {% endcompress %}
40
41
42
43

44

45                  {% block header %}
46

47
48
51
52

53

54                          {% if user.is_authenticated %}
55                              {% if user.first_name %}
56                                  {{ user.first_name }} {{user.last_name}}
57                              {% else %}

I have tried to copy the whole templates from the flstheme package, but it still does not work.
There are good explanation on this topic for pure django, but it FLS is an extra complexity layer and I cant get it right. Thanks a lot in advance.
EDIT This is a freeze of my virtualenv:
Django==1.6.5
Pillow==1.7.5
South==0.7.3
django-appconf==0.6
django-compressor==1.1.1
django-countries==1.5
django-lfs==0.7.8
django-lfstheme==0.7.4
django-pagination==1.0.7
django-paypal==0.1.2
django-piston==0.2.3
django-portlets==1.1.1
django-postal==0.92
django-reviews==0.2.1
django-tagging==0.3.1
lfs-contact==1.0
lfs-order-numbers==1.0b1
six==1.7.3

A: As the traceback states, the url tag in line 47 should look like this
{% url 'lfs.core.views.shop_view' %}

This has been changed in Django 1.5.
Make also sure that you are using Django 1.3.* with LFS 0.7.*. If you do this, the above error shouldn't rise up at all.
LFS 0.9 (which is in alpha state at the moment) is using Django 1.6.*, though.


text:
Q: Email address validation in System.Net.Mail I am sending email with System.Net.Mail via .Net. When email address contains dot like john.smith@company.com, in my computer it works with Visual Studio Development Server, but in the production which runs .Net 4.0.30319 integrated mode it throws format exception. Any comments why it can be?
I used following code:
ConstructorInfo ctor = typeof(MailAddress).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(string), typeof(string), typeof(string) }, null);

MailMessage mm = new MailMessage();
string[] arrMailTo = To.Split('@');
mm.To.Add ((MailAddress)ctor.Invoke(new object[] { To, arrMailTo[0], arrMailTo[1] }));


text:
Q: fireEvent doesn't click button on React component I'm writing tests for a React component. It's a timer that starts counting down when you press a button, then stops when you press the same button. I have a test case that tries to press the pause button, wait a second, then press the pause button again, checking the timer to make sure that a second has elapsed:
Timer.test.js
render(<Timer />)
const pauseButton = screen.getByText('pause')
const timerOutput = screen.getAllByRole('heading')[1]

describe('Timer', () => {
  test('Timer starts counting down when unpaused', done => {
    function fetchTime(callback) {
      fireEvent.click(pauseButton)
      setTimeout(
        fireEvent.click(pauseButton),
        1250
      )
      return callback(timerOutput)
    }

    function callback(data) {
      try {
        expect(data).toHaveTextContent('24:59')
        done()
      } catch(error) {
        done(error)
      }
    }

    fetchTime(callback)
  })
})

The problem is, the test doesn't seem to be hitting click on pauseButton the way I want it to. Jest tells me in the terminal when I run my test that timerOutput turns out to be '25:00' rather than '24:59', and it seems as if the component failed the test. But this is a problem with the test, not the component; when I run the app in my browser and press the button myself, it works the way it should. How do I get this test to work properly, and hit the buttons the way I want it to?

A: It's difficult to have an accurate answer with few information about the component itself.
First I would recommend use async arrow function inside test() whenever you need to handle async calls so you don't rely in callback hell.
Besides that, I would try to use jest.useFakeTimers() so you can advance the setTimeout timer in order to test properly. It seems that your second fireEvent.click never gets fired since the test checks it synchronously.
And I just noticed you requested the timerOutput at first but didn't request it after the click events.
I would suggest something like:
test('Timer starts counting down when unpaused', async () => {
      jest.useFakeTimers();
      fireEvent.click(pauseButton)
      setTimeout(
        () => {fireEvent.click(pauseButton)},
        1250
      )
      jest.runPendingTimers(); // This would run the above function

        expect(screen.getAllByRole('heading')[1]).toHaveTextContent('24:59')
    }
  })

Indeed, the expect statement would be better from a user perspective assertion, like:
expect(screen.getByText("24:59")).toBeVisible();

Since you don't matter about the HTML elements that contains that text content


text:
Q: Search an hmap for a value If I have a redis hmap that looks like the following:
client.hset('test', 'one', 'aaa');
client.hset('test', 'two', 'bbb');
client.hset('test', 'three', 'ccc');
client.hset('test', 'four', 'ddd');

and I want to find if the map has a value like ccc whats the best way to do that?
I can call something like
 client.hgetall('test', function(err, obj){
     for(id in obj){
         if(obj[id] == 'ccc'){
             return id;
         }
     }
  });

But this seems very inefficient, is there a search or find method in redis that would produce nicer solution?

A: There's no built-in way to search by value. If you want to do it more efficient, you have to build an inverted index from value to key, e.g. inverted-test. Each time when you update the test hash, also update the inverted index.
HSET test one aaa
HSET inverted-test aaa one

NOTE
If in your original hash, multiple keys might have the same value. You might need to implement the inverted index with a LIST.
HSET test one aaa
LPUSH inverted-test:aaa one
HSET test two aaa
LPUSH inverted-test:aaa two

A: You could use the filter method like this:
client.hgetall('test', (err, obj) => {
    // in here we create an array of the object obj properties
    const keys = Object.keys(obj);
    // and now we iterate that array with the filter method
    const wantedValues = keys.filter(key => obj[key] === 'ccc');
    // wantedValues is now a array with the keys of the object obj that have the value ccc
});


text:
Q: How to use: PartCover .NET 4 with NUnit 2.5.6 Say I have Test assembly (NUnit compliant) App.Test.dll and a library to be tested App.dll.
How do I get the code coverage analysis using PartCover and NUint?

A: I concur. In my experiments (see blog post here: http://www.csharpcity.com/using-partcover-and-nunit-for-code-coverage/) I set up a project with an NUnit-complaint "AutomatedTest" project (which referenced NUnit's framework DLL and outputted a DLL full of test classes), and ran that through PartCover.

A: The easiest way is to set up an NUnit test project (which runs App.Test.dll), then from PartCover call the NUnit console runner and pass the project name as a parameter.  I have a blog post about it if you want to check that out.
(I haven't tried with .Net 4 or the latest versions of NUnit/PartCover but I'm assuming it's still the same).

A: It took me a while to figure out how get the source code markings. I had to put a /noshadow flag in the "Working Arguments". /noshadow prevents NUnit to make shadow copies of the files and will allow PartCover to load source files in the browser.
Then just click "Views->View Coverage Detail" after the run.


text:
Q: how to run stored procedure from groovy that returns multiple resultsets I couldnt find any good example of doing this online.
Can someone please show how to run a stored procedure (that returns multiple resultsets) from groovy?
Basically I am just trying to determine how many resultsets the stored procedure returns..

A: I have written a helper which allows me to work with stored procedures that return a single ResultSet in a way that is similar to working with queries with groovy.sql.Sql. This could easily be adapted to process multiple ResultSets (I assume each would need it's own closure).
Usage:
Sql sql = Sql.newInstance(dataSource)
SqlHelper helper = new SqlHelper(sql);
helper.eachSprocRow('EXEC sp_my_sproc ?, ?, ?', ['a', 'b', 'c']) { row ->
    println "foo=${row.foo}, bar=${row.bar}, baz=${row.baz}"
}

Code:
class SqlHelper {
    private Sql sql;

    SqlHelper(Sql sql) {
        this.sql = sql;
    }

    public void eachSprocRow(String query, List parameters, Closure closure) {
        sql.cacheConnection { Connection con ->
            CallableStatement proc = con.prepareCall(query)
            try {
                parameters.eachWithIndex { param, i ->
                    proc.setObject(i+1, param)
                }

                boolean result = proc.execute()
                boolean found = false
                while (!found) {
                    if (result) {
                        ResultSet rs = proc.getResultSet()
                        ResultSetMetaData md = rs.getMetaData()
                        int columnCount = md.getColumnCount()
                        while (rs.next()) {
                            // use case insensitive map
                            Map row = new TreeMap(String.CASE_INSENSITIVE_ORDER)
                            for (int i = 0; i < columnCount; ++ i) {
                                row[md.getColumnName(i+1)] = rs.getObject(i+1)
                            }
                            closure.call(row)
                        }
                        found = true;
                    } else if (proc.getUpdateCount() < 0) {
                        throw new RuntimeException("Sproc ${query} did not return a result set")
                    }
                    result = proc.getMoreResults()
                }
            } finally {
                proc.close()
            }
        }
    }
}

A: All Java classes are usable from Groovy. If Groovy does not give you a way to do it, then you can do it Java-way using JDBC callable statements.

A: I just stumbled across what could possibly be a solution to your problem, if an example was what you were after, have a look at the reply to this thread