text:
Q: Appending a unique id to simple_form generated radio button inputs and a matching value to the associated label I have the following object:
# Table name: interests
#
#  id         :integer          not null, primary key
#  client_id  :integer
#  condition  :string(255)
belongs_to :client

I use the following form to create new objects:
= simple_form_for interest do |f|
  = f.error_notification

  .form-inputs
    = f.hidden_field :client_id, value: interest.client_id
    = f.input :condition, as: :radio_buttons, collection: ['Used', 'New'], boolean_style: :inline

  .form-actions
    = f.button :submit

I render this form multiple times on the same page and am having an issue with the IDs of each radio button input matching an ID of the same input in every form on the page.
This is what is rendered multiple times on the page:

  Condition

    <input class="radio_buttons optional" id="interest_condition_used" name="interest[condition]" type="radio" value="Used">
      Used
    </input>

    <input class="radio_buttons optional" id="interest_condition_new" name="interest[condition]" type="radio" value="New">
      New
    </input>

My attempted solution:
Every form has access to a unique id through interest.client_id.  I intend on changing the id on the input and the for on the following label to something using that id to ensure every version is unique:
= f.input :condition, as: :radio_buttons, collection: ['Used', 'New'],
    boolean_style: :inline,
    input_html: { id: 'interest_condition' + interest.client_id.to_s},
    label_html: {for: 'interest_condition' + interest.client_id.to_s}

But this does two things wrong:

*

*I lose the dynamic id that is typically generated by the collection, each id/for is literally interest_condition#{interest.client_id} rather than interest_condition_new#{interest.client_id} and interest_condition_used#{interest.client_id}.

*And assigning the label_html for value with label_html: {for: 'interest_condition' + interest.client_id.to_s} assigns the for value for the parent label for the collection of radio buttons rather than the label that comes after the radio button itself (this is enabled with boolean_style: :inline)

Example of code generated by above code:

    Condition

    <input class="radio_buttons optional" id="interest_condition7" name="interest[condition]" type="radio" value="Used">

      Used

    <input class="radio_buttons optional" id="interest_condition7" name="interest[condition]" type="radio" value="New">

      New

How would I append a value custom to each specific form rendered on the page to the id and form attributes of my radio buttons?

A: I have come across a case where I needed unique IDs for each radio option in a collection of radio buttons.
Rather than creating a custom input and overriding Simple Form's CollectionRadioButtonInput or creating a custom wrapper using the Wrapper API, I used the namespace option.
= f.input_field :my_field, as: :radio_buttons, namespace: "unique_prefix_to_be_prepended_to_id", boolean_style: :inline

The namespace will be prepended to the automatically generated ID that SimpleForm generates based on your models and fields names. For example, let's say I have the following form for a User.
= simple_form_for @user do |f|
   = f.input_field :my_field, as: :radio_buttons, namespace: "unique"

The HTML <input> tag for the 'Yes' radio button option will automatically have an id of unique_user_my_field_true. The 'No' radio button option will have an id of unique_user_my_field_false. Of course, this is assuming you are only using a yes/no T/F scenario for radio buttons.

A: I think you're looking for an association here.  Try this:
f.association :client, label_method: :condition

and see if that appends _#{id} to each of your input#ids
provided you can do this:
Interest.first.client.condition

and get the expected value, I think the above should work

A: As (what I hope is) a temporary fix, I let the page load then I update all of the input id attributes and label for attributes using coffeescript:
$ ->
  $('.ids-updated-by-js').each (index) ->
    $(this).find('span').each ->
      span = $(this)
      id = span.find('input').attr('id')
      span.find('input').attr('id', id + index)
      span.find('label').attr('for', id + index)
      console.log 'Updated radio button with id: ' + index + ' ' + id
    return

Javascript version of the code above:
$(function() {
  return $('.ids-updated-by-js').each(function(index) {
    $(this).find('span').each(function() {
      var id, span;
      span = $(this);
      id = span.find('input').attr('id');
      span.find('input').attr('id', id + index);
      span.find('label').attr('for', id + index);
      return console.log('Updated radio button with id: ' + index + ' ' + id);
    });
  });
});

This is not ideal, but it does create the desired effect (as long as the project doesn't have to support noscript users).


text:
Q: In Objective C, what is the syntax for creating a method with unlimited parameters like NSLog? I need to write an Objective-C method whose input is an array of strings and whose output is that list of strings concatenated, but only those which are not nil.
Any ideas if this function is already somewhere in the foundation?
If it's not already done, how can I write a method which has an unlimited number of NSString parameters?  For instance, like the params keyword in C# which will essentially convert the params list into an array.
thanks

A: You need ... (ellipsis):
- yourMessage:arg1, ...;

Here's official Apple information on the subject.
Here I am copying their sample:
#import <Cocoa/Cocoa.h>

@interface NSMutableArray (variadicMethodExample)

- (void) appendObjects:(id) firstObject, ...;  // This method takes a nil-terminated list of objects.

@end

@implementation NSMutableArray (variadicMethodExample)

- (void) appendObjects:(id) firstObject, ...
{
id eachObject;
va_list argumentList;
if (firstObject)                      // The first argument isn't part of the varargs list,
  {                                   // so we'll handle it separately.
  [self addObject: firstObject];
  va_start(argumentList, firstObject);          // Start scanning for arguments after firstObject.
  while (eachObject = va_arg(argumentList, id)) // As many times as we can get an argument of type "id"
    [self addObject: eachObject];               // that isn't nil, add it to self's contents.
  va_end(argumentList);
  }
}

@end

A: Variable arguments in Objective-C methods

A: Your answer might just be in this nice post.
http://cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adicionando libs no android com eclipse normalmente eu pego o jar e coloco dentro da pasta lib do meu projeto, mas ja vi gente que faz a mesma coisa e adiciona pelo "Java Build Path/Add JARs...", tem diferença de só colocar na pasta?

A: Quando você adiciona uma biblioteca pelo Java Build Path/Add JARs, o projeto irá importar para o seu projeto uma referência(o caminho aonde está a biblioteca) da biblioteca, por exemplo digamos adiciona uma biblioteca que está na sua área de trabalho(C:\Users\Usuario\Desktop), então o eclipse irá referenciar essa biblioteca caso você posteriormente venha remove ou mover essa biblioteca da sua área de trabalho o ecplise não irá executar o seu projeto, pois falta a biblioteca.
Já você colocando diretamente na pasta lib, o projeto irá conter a biblioteca sem uma referencia a outro local diferente que não seja a pasta lib, diferentemente do caso descrito anteriormente.Caso você utilize essa biblioteca em alguma parte do seu código e posteriormente venha deletar ou mover essa biblioteca resultará num erro de compilação.


text:
Q: Using Theano shared variables with PyMC3 My observable data is very big and its likelihood function is quite complex so I load all the observable data in the GPU and then use a theano function to get their likelihood depending on the parameters that I'm trying to estimate.
def create_function(data_values):
    X = theano.shared(np.asarray(data_values,
                dtype=theano.config.floatX),
                 borrow=borrow)
    def logp(B,sigma_r,sigma_u):
        P = complexTheanoFunction(X)
        return T.sum(T.log(P))
    return logp

with mc.Model() as model:
    data_values = load_data()
    logp = create_function(data_values)

    sigma_r = mc.Uniform('sigma_r',0,1,testval=0.5,dtype='float32')
    sigma_u = mc.Uniform('sigma_u',0,1,testval=0.5,dtype='float32')
    B = mc.Uniform('B',0,1,testval=np.array([0.5,0.5,.5,.5],dtype=np.float32),shape=4,dtype='float32')

    get_logp = theano.function(
        inputs = [B,sigma_r,sigma_u],
        outputs = logp,
    )

    obs = mc.DensityDist('observations',get_logp)
    start = mc.find_MAP()
    step = mc.NUTS(state=start)

    trace = mc.sample(5000,step,start=start)
    mc.traceplot(trace, )

I don't know if this is the right approach or not. I am getting the error:
  obs = mc.DensityDist('observations',get_logp)
  File "/usr/local/lib/python2.7/dist-packages/pymc3/distributions/distribution.py", line 19, in __new__
    return model.Var(name, dist, data)
  File "/usr/local/lib/python2.7/dist-packages/pymc3/model.py", line 143, in Var
    var = FreeRV(name=name, distribution=dist, model=self)
  File "/usr/local/lib/python2.7/dist-packages/pymc3/model.py", line 322, in __init__
    self.logp_elemwiset = distribution.logp(self)
  File "/usr/local/lib/python2.7/dist-packages/theano/compile/function_module.py", line 517, in __call__
    allow_downcast=s.allow_downcast)
  File "/usr/local/lib/python2.7/dist-packages/theano/tensor/type.py", line 77, in filter
    'Expected an array-like object, but found a Variable: '
TypeError: ('Bad input argument to theano function with name "/home/joao/Dropbox/physological/Juggler/SaliencyExp/mc3tryExp.py:64"  at index 0(0-based)', 'Expected an array-like object, but found a Variable: maybe you are trying to call a function on a (possibly shared) variable instead of a numeric array?')

----------//-----------
I tried to make a simple example using the example given by John Salvatier:
P.S. This model doesn't make any sense.. I am just trying to figure it out how does Theano work with pymc3
with mc.Model() as model:
    data_values = np.random.rand(200,3)
    X = theano.shared(np.asarray(data_values,
        dtype=theano.config.floatX),
         borrow=True)

    B = mc.Uniform('B',0,1,testval=np.array([.5,.5,.5],dtype=np.float32),shape=3,dtype='float32')

    def logp(x,B):
        P = x.dot(B)
        P = P/T.sum(P)
        return T.sum(T.log(P))

    obs = mc.DensityDist('observations',logp, observed=X)
    start = mc.find_MAP()
    step = mc.NUTS(state=start)

And I get this error:
Traceback (most recent call last):
  File "/home/joao/test.py.py", line 27, in <module>
    obs = mc.DensityDist('observations',logp, observed=X)
  File "/usr/local/lib/python2.7/dist-packages/pymc3/distributions/distribution.py", line 19, in __new__
    return model.Var(name, dist, data)
  File "/usr/local/lib/python2.7/dist-packages/pymc3/model.py", line 146, in Var
    var = ObservedRV(name=name, data=data, distribution=dist, model=self)
  File "/usr/local/lib/python2.7/dist-packages/pymc3/model.py", line 348, in __init__
    args = [t.constant(args[0], name=name)]
  File "/usr/local/lib/python2.7/dist-packages/theano/tensor/basic.py", line 416, in constant
    dtype=dtype)
  File "/usr/local/lib/python2.7/dist-packages/theano/tensor/basic.py", line 411, in constant_or_value
    raise TypeError("Could not convert %s to TensorType" % x, type(x))
TypeError: ('Could not convert <CudaNdarrayType(float32, matrix)> to TensorType', <class 'theano.sandbox.cuda.var.CudaNdarraySharedVariable'>)

A: The error you're getting is because you're compiling the logp function into get_logp and then passing it to DensityDist which actually expects a function that returns a theano variable, not a compiled theano function.
I think you want something like:
with mc.Model() as model:
    data_values = load_data()
    X = theano.shared(np.asarray(data_values,
        dtype=theano.config.floatX),
         borrow=borrow)

    sigma_r = mc.Uniform('sigma_r',0,1,testval=0.5,dtype='float32')
    sigma_u = mc.Uniform('sigma_u',0,1,testval=0.5,dtype='float32')
    B = mc.Uniform('B',0,1,testval=np.array([0.5,0.5,.5,.5],dtype=np.float32),shape=4,dtype='float32')

    def logp(x):
        #need to pass B sigma r/u to the function
        P = complexTheanoFunction(x, B, sigma_r, sigma_u)
        return T.sum(T.log(P))

    obs = mc.DensityDist('observations',logp, observed=X)
    start = mc.find_MAP()
    step = mc.NUTS(state=start)


text:
Q: "be driven by something"
Spending on cosmetic surgery in UK  has risen by more than a third,
  driven by the rising number of businesspeople who are going under the
  knife to help them climb the career ladder.

What does the "driven by" in this sentence mean?

A: In this case, driven what is driving or causing the rising spend in cosmetic surgery.

Housing prices are rising, driven by lower interest rates.
lower interest rates (financing) is causing people to buy houses

A:
Driven

Providing the power to keep a machine working, or to make something happen.
For example:

*

*The new ships, propelled by gas turbines, require less maintenance
  than older, steam-driven ones.

*The fact remains that there are some public services that cannot be
  entirely market-driven (= controlled by economic forces).

Source : Driven


text:
Q: Netezza import from external file error: Unsupported external table reference, unable to derive shape I'm working to create a new table from an external file in Netezza, but am getting the following error:
Unsupported external table reference, unable to derive shape
I get the same error whether trying to create a new table or insert into an existing table. Here is the sql I'm using:
            select * from external 'FILEPATH.txt' using (delim '|');

A: you need to define the column format in your query. then the query will fire
SYSTEM.ADMIN(ADMIN)=> select * from external '/tmp/testfile.txt' (v1 int, v2 int) using (delim '|');
 V1 | V2
----+----
  3 |  4
  3 |  6
(2 rows)

note that when inserting into an existing table you don't need to specify the types
SYSTEM.ADMIN(ADMIN)=> create table test (v1 int, v2 int);
CREATE TABLE
SYSTEM.ADMIN(ADMIN)=> insert into test select * from external '/tmp/testfile.txt' using (delim '|');
INSERT 0 2


text:
Q: Socket.io + TypeScript: Socket.io not listening for new connections I've a basic express application which. I'm new to socket.io, so i was reading the docs on how to intergrate it with typescript and express server. Here is what i have for now:
server.ts
import express from "express";
import { Server, Socket } from "socket.io";
import { createServer, Server as S } from "http";
import router from "./routes";
// ----
const app: express.Application = express();
app.use(router);
const PORT: any = 3001 || process.env.PORT;
const server: S = createServer(app);
const io = new Server(server, {});

io.on("connection", (socket: Socket) => {
  console.log("we have a new connection");
  console.log(socket.id);
});
//
server.listen(PORT, () => {
  console.log(`The server is running on port: ${PORT}`);
});

routes/index.ts
import { Request, Response, Router } from "express";

const router: Router = Router();

router.get("/", (_req: Request, res: Response) => {
  res.status(200).json({
    name: "backend",
    language: "typescript",
    message: "hello world!",
  });
});

export default router;

What i understand is that when i visit the port 3001. I should see a message on the server console telling me that i have a new connection. Unfortunately there's nothing that is being loged on the console. What maybe possibly my mistake?
If i visit http://localhost:3001/, I'm getting the following response
{
"name": "backend",
"language": "typescript",
"message": "hello world!"
}

This is because of the get(/) route in the routes/index.ts file, but no socket.io connection fired after i visited that route.

A: The websocket is not running on the http protocol but on the websocket protocol. So the URL will be ws://localhost:3001/. But socket.io redirects automatically to ws://localhost:3001/socket.io when using the client API. The client API is pretty easy to use in my opinion.
You could start with the get-started from socket.io for an easy example; https://socket.io/get-started/chat. This will cover the basics of the server and client which you could then apply to your app.


text:
Q: Android 6.0 closing app after requesting permissions causes permissions to be asked for 3 times each I ran into a strange bug (I think) when trying to update my app to use Android 6.0 permissions. My code is as follows:
public void requestPerms2()
    boolean gratedPermissions = false;
    PackageManager pm = this.getPackageManager();

    int hasPerm1 = PackageManager.PERMISSION_GRANTED; //Assume granted on low level
    if(android.os.Build.VERSION.SDK_INT > 15) {
        hasPerm1 = pm.checkPermission(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                this.getPackageName());
    }
    int hasPerm2 = pm.checkPermission(
            Manifest.permission.RECORD_AUDIO,
            this.getPackageName());

    if(hasPerm1 != PackageManager.PERMISSION_GRANTED){
        String [] neededPerms = {some.path.here.Manifest.permission.READ_EXTERNAL_STORAGE};
        ActivityCompat.requestPermissions(this, neededPerms , 1);
        gratedPermissions = true;
    }

    if(hasPerm2 != PackageManager.PERMISSION_GRANTED){
        String [] neededPerms = {some.path.here.Manifest.permission.RECORD_AUDIO};
        ActivityCompat.requestPermissions(this, neededPerms , 1);
        grantedPermissions = true;
    }
    if(grantedPermissions)
        System.exit(0);
}

This is inside a method called from onCreate, and is definitely called only one time (I have some debug statements I took out). However, it will prompt the user for permissions 3 times each. I've tried varying the requested permissions, and it always asks 3 times each. If I comment out the System.exit(0), it works perfectly and asks the user one time per permission.
I ideally want to close the app after getting permissions and forcing a relaunch, since the permissions won't apply until after an app restart. Is there any way to do this without asking the user to allow permissions 3 times each?

A: I would just put this as a comment but Im not reputable enough yet :(
Android will automatically restart your app and call onCreate if the permission you are requesting requires a restart. You can then use the callback:
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults){
    if(requestCode == 101)
    {
        if( (grantResults[0] == PackageManager.PERMISSION_DENIED) || (grantResults[1] == PackageManager.PERMISSION_DENIED) ) {
            Toast.makeText(getApplicationContext(),"Unable to get permissions for ...",Toast.LENGTH_LONG).show();
        }
    }
}

then check whether the appropriate permission has been granted.
This would negate the need to exit the app altogether.


text:
Q: Why LinqPad return The name 'ModelName' does not exist in the current context error? I have a Asp.net MVC - C# project and want to use LINQPad to test some Entity Framework statements of it before use them in the project.
The project has different class libraries such as

*

*DAL (include the ApplicationDbContext class)

*Domain Classes (models)

A) I added an EF Connection to the DAL in LINQPad and it loaded all of the entities in the left tree in its window successfully. [See the bellow image]

B) Also i added the some required references from LINQPad Query to the following DLLs:

*

*DAL dll

*Domain Classes dll

*Microsoft.AspNet.Identity.Core.dll

*EntityFramework.dll

But »
When i right click on an entity in the left tree and select each option, it show this error:

The name '[Conceptual_Model_Name]' does not exist in the current context

Why?
How can i resolve this problem?

Edit 1:
In the OnModelCreating method of ApplicationDbContext class i call the following method to add entities to the DbContext dynamically.
    public void LoadEntities(Assembly asm, DbModelBuilder modelBuilder, string nameSpace)
    {
        var entityTypes = asm.GetTypes()
            .Where(type => type.BaseType != null &&
                           type.Namespace == nameSpace &&
                           type.BaseType == null)
            .ToList();

        var entityMethod = typeof(DbModelBuilder).GetMethod("Entity");
        entityTypes.ForEach(type => entityMethod.MakeGenericMethod(type).Invoke(modelBuilder, new object[] { }));
    }

I call it with this line of code:
LoadEntities(typeof(AppUser).GetTypeInfo().Assembly, modelBuilder, "DomainClasses.Entities");

Is it possible the reason be related to this dynamic loading of models?

A: I solved it myself !
The suspicion that i wrote about it in the question, was correct. As I wrote in the question i add the entities to the DbContext as dynamically but now i changed it to the static way like this:
// Add this property to the ApplicationDbContext class

public virtual DbSet<Consumption> Consumptions { get; set; }

Now when i use Consumptions property in LINQPad it works...


text:
Q: Android - SMS Broadcast receiver I have been trying to get this program to work but so far having no luck. I cannot find where I am doing wrong. I'm not sure if there's something wrong with the code, or debugging.
I'm trying to be notified if a new SMS arrives.
Here is my program:
package Technicaljar.SMSBroadcastReceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

public class SMSBroadcastReceiver extends BroadcastReceiver {

        private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
        private static final String TAG = "SMSBroadcastReceiver";

        @Override
        public void onReceive(Context context, Intent intent) {
             Log.i(TAG, "Intent recieved: " + intent.getAction());

                if (intent.getAction() == SMS_RECEIVED) {
                    Bundle bundle = intent.getExtras();
                    if (bundle != null) {
                        Object[] pdus = (Object[])bundle.get("pdus");
                        final SmsMessage[] messages = new SmsMessage[pdus.length];
                        for (int i = 0; i < pdus.length; i++) {
                            messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                        }
                        if (messages.length > -1) {
                            Log.i(TAG, "Message recieved: " + messages[0].getMessageBody());
                        }
                    }
                }
           }
    }

And the manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="Technicaljar.SMSBroadcastReceiver"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true" >
        <receiver android:name=".SMSBroadcastReceiver">
            <intent-filter>
                <action android:name="android.provider.telephony.SMS_RECEIVED"></action>
            </intent-filter>
        </receiver>

    </application>
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
</manifest>

I am sending SMS through Telnet, and I cannot see any Intent received messages in the logcat. Here is my logcat from the time of installation.
D/AndroidRuntime(  478):
D/AndroidRuntime(  478): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
D/AndroidRuntime(  478): CheckJNI is ON
D/AndroidRuntime(  478): --- registering native functions ---
D/AndroidRuntime(  478): Shutting down VM
D/dalvikvm(  478): Debugger has detached; object registry had 1 entries
I/AndroidRuntime(  478): NOTE: attach of thread 'Binder Thread #3' failed
D/Mms:app (  220): getSmsNewMessageNotificationInfo: count=14, first addr=12345, thread_id=4
D/dalvikvm(  151): GC_EXPLICIT freed 391 objects / 22552 bytes in 65ms
D/dalvikvm(  220): GC_EXPLICIT freed 926 objects / 44840 bytes in 73ms

So the SMS seems to be received by the emulator, but looks like the no intents are firing.
What am I doing wrong here? After installing, do I have to somehow 'start' this receiver?
Because when I install, I get
 [2010-11-07 21:24:41 - SMSBroadcastReceiver] No Launcher activity found!
[2010-11-07 21:24:41 - SMSBroadcastReceiver] The launch will only sync the application package on the device!

So I'm wondering if something's wrong here.

A: android.provider.Telephony.SMS_RECEIVED has a capital T, and yours in the manifest does not.
Please bear in mind that this Intent action is not documented.

A: Also note that the Hangouts application will currently block my BroadcastReceiver from receiving SMS messages. I had to disable SMS functionality in the Hangouts application (Settings->SMS->Turn on SMS), before my SMS BroadcastReceived started getting fired.
Edit: It appears as though some applications will abortBroadcast() on the intent which will prevent other applications from receiving the intent. The solution is to increase the android:priority attribute in the intent-filter tag:
<receiver android:name="com.company.application.SMSBroadcastReceiver" >
  <intent-filter android:priority="500">
    <action android:name="android.provider.Telephony.SMS_RECEIVED" />
  </intent-filter>
</receiver>

See more details here: Enabling SMS support in Hangouts 2.0 breaks the BroadcastReceiver of SMS_RECEIVED in my app

A: intent.getAction().equals(SMS_RECEIVED)
I have tried it out successfully.

A: Stumbled across this today. For anyone coding an SMS receiver nowadays, use this code instead of the deprecated in OP:
SmsMessage[] msgs = Telephony.Sms.Intents.getMessagesFromIntent(intent);
SmsMessage smsMessage = msgs[0];

A: Your broadcast receiver must specify android:exported="true" to receive broadcasts created outside your own application. My broadcast receiver is defined in the manifest as follows:
<receiver
    android:name=".IncomingSmsBroadcastReceiver"
    android:enabled="true"
    android:exported="true" >
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

As noted below, exported="true" is the default, so you can omit this line. I've left it in so that the discussion comments make sense.

A: I tried your code and found it wasn't working.
I had to change
if (intent.getAction() == SMS_RECEIVED) {

to
if (intent.getAction().equals(SMS_RECEIVED)) {

Now it's working. It's just an issue with java checking equality.

A: For android 19+ you can get it in Telephony.Sms.Intents.SMS_RECEIVED_ACTION). There are more in the Intents class that 're worth looking
at

A: I've encountered such issue recently. Though code was correct, I didn't turn on permissions in app settings. So, all permissions hasn't been set by default on emulators, so you should do it yourself.

A: android.provider.telephony.SMS_RECEIVED is not correct because Telephony is a class and it should be capital as in android.provider.Telephony.SMS_RECEIVED


text:
Q: How do you change border line color of wx.StaticBox?
As you can see from the above pic, the border line of wx.StaticBox is always grey on windows, is it possible to change it? I've searched quite a bit, but there doesn't seem to be any properties/attributes for the border line color, so how do you do it?
Thanks a lot

A: This question had discussed in wxPython google group. "wx doesn't provide that level of control over the borders of widgets." Robin Dunn. You can try to create new class inherit it from wx.StaticBox and implement OnPaint method

A: This is how you would do it

pnl = wx.Panel()
bx1 = wx.StaticBox(pnl, label='Wave 1', pos=(5, 10), size=(300, 500))
bx1.SetBackgroundColour((0, 0, 0))


text:
Q: Executing typescript class in same file I have one typescript file which I have added as required in another .ts file. I need to take the url from browser and need to do some manipulation and export it.
The class section does not seems to be executing. Seems i am missing a piece of code somewhere. Do not know what?
import { Router } from '@angular/router';

export let someVariable="SomeValue"
export class RouteComponent {
  constructor(private router: Router) {
    this.router.events.subscribe(path => {
      someVariable = path.url
    });
  }
  decideRoute(){

    // Want to do something with someVariable here
    console.log(someVariable)
  }
  ngOnInit(){
  }
}


text:
Q: How to expand the number of subuids for a linux namespace After running something like this:
$ unshare -rUm
$ mkdir opt
$ mount --bind opt /opt
$ touch /opt/test
$ chown 1000:1000 /opt/test

I'm receiving this:
chown: changing ownership of '/opt/test': Invalid argument

As I can see, I only have 1 subuid that I can use.
$ cat /proc/self/uid_map
         0       1000          1

How can I add more than that?
I already have this in my subuid/subgid files:
$ cat /etc/subuid
cloud-user:100000:65537


text:
Q: In-app delete Firebase record Hoping for help on a small issue:
I am trying to delete singular records that are stored in my Firebase database through my Android application.
At present, when clicking the delete button, all items are deleted, as opposed to the single record that I have clicked on.
For completeness, I have also included my updateMaintenance method, which works perfectly.  As you will see in the updateMaintenance method, I have used user-based authentication in mAuth.getCurrentUser() - I want to have this for my deleteMaintenance method also.
I'm sure this is just a case of adding a small bit of code, but not too sure where to start.  Thanks in advance!
private void deleteMaintenance(String maintenanceId) {
    DatabaseReference drMaintenance = FirebaseDatabase.getInstance().getReference("maintenance").child(maintenanceId);

    FirebaseUser user = mAuth.getCurrentUser();
    String uid = user.getUid();

    databaseMaintenance.child(uid).removeValue();

    Toast.makeText(this, "Maintenance record has been deleted", Toast.LENGTH_LONG).show();
}

private boolean updateMaintenance(String title, String desc, String id, String primary, String secondary, String property) {

    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("maintenance").child(id);
    Maintenance maintenance = new Maintenance (id, title, desc, primary, secondary, property);

    FirebaseUser user = mAuth.getCurrentUser();
    String uid = user.getUid();

    databaseMaintenance.child(uid).child(id).setValue(maintenance);

    databaseReference.setValue(maintenance);

    Toast.makeText(this, "Maintenance Updated Updated Successfully", Toast.LENGTH_LONG).show();

    return true;
}

A: This is happening because when using the following line of code:
databaseMaintenance.child(uid).removeValue();

You are deleting everything that is beneath the maintenance -> uid node. So basically you are deleting the uid node.
To achieve what you want, you need to change the reference. So please change the above line of code with:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("maintenance").child(uid).child(maintenanceId).removeValue();


text:
Q: Calculate next date in week I am building a tutorial schedule application and I need to be able to calculate the next date. Specifically, I need to calculate either the next Saturday or Tuesday in the week (depending which one comes first) based on the current date.
Today is Monday, July 15, 2013. The next Tuesday is on July 16, 2013. The next Saturday is July 20, 2013. Therefore I would need the date Tuesday, July 16, 2013.
Can anyone please tell me how I could figure this out?
Thank you!

A: Use [NSCalendar currentCalendar] to get NSDateComponents from the current date, especially NSWeekdayCalendarUnit and NSWeekOfYearCalendarUnit. the components will have a member weekday, that ranges from 1 — sunday to 7 — saturday. if it is 1 or 2, create a new componets with weekday 2, if it is 7, add one to weekOfYear and set weekday to 2. for all other cases set weekday to 7.
Now use [NSCalendar currentCalendar] again to create a day from the components.


text:
Q: Is there a way to get GPS location on a time interval instead of when the position changes? My client wants a GPS app that will produce a spreadsheet of all the GPS locations in equal time intervals.  You can set the time interval using a spinner.
Right now my app gets the new GPS location when the location changes using LocationManager manager's onLocationChanged(Location loc) callback.
Is there a way to get the new GPS locations on time intervals instead of when the position changes?
Code:
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  //if you want to lock screen for always Portrait mode
  setRequestedOrientation(ActivityInfo
  .SCREEN_ORIENTATION_PORTRAIT);

  pb = (ProgressBar) findViewById(R.id.progressBar1);
  pb.setVisibility(View.INVISIBLE);

  viewLog= (TextView) findViewById(R.id.ViewLong);
  viewLat= (TextView) findViewById(R.id.ViewLat);

  locationMangaer = (LocationManager)
  getSystemService(Context.LOCATION_SERVICE);
  StartGPS();
 }

void  StartGPS()
{

 flag = displayGpsStatus();
  if (flag) {

   pb.setVisibility(View.VISIBLE);
   locationListener = new MyLocationListener();

   locationMangaer.requestLocationUpdates(LocationManager .GPS_PROVIDER, 5000, 10,locationListener);

   } else {
   alertbox("Gps Status!!", "Your GPS is: OFF");
  }

 }

@Override
 public void onClick(View v) {

 }

 /*----------Listener class to get coordinates ------------- */
 private class MyLocationListener implements LocationListener {
        @Override
        public void onLocationChanged(Location loc) {

            String longitude = "Longitude: " +loc.getLongitude();
               viewLog.setText(longitude);
               String latitude = "Latitude: " +loc.getLatitude();
               viewLat.setText( latitude);
               pb.setVisibility(View.INVISIBLE);

        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onStatusChanged(String provider,
  int status, Bundle extras) {
            // TODO Auto-generated method stub
        }
    }

A: Register for location updates as you are now. Ignore the values passed to your LocationListener. On your desired polling frequency, call getLastKnownLocation() for whatever provider you are using for your location updates.


text:
Q: Bootstrap 4 stacking radio btn-group So I have a btn-group of radio buttons which I want to stack responsively.
I simply can't get it to work except when I remove the btn-group but then the radio buttons of course don't know which ones are checked and simply stop working.

                <input hidden="true" type="radio" name="options" id="option1" autocomplete="off" checked> Radio 1

                <input hidden="true"  type="radio" name="options" id="option2" autocomplete="off"> Radio 2

                <input hidden="true" type="radio" name="options" id="option3" autocomplete="off"> Radio 3

A: You can simply achieve that by adding this script :
$("input[type=radio]").on("change",function(){
    $('input:checked').parent().addClass("active"); // Change active with your own class name
});


text:
Q: SQL Query syntax - interlinking table Just looking for a bit of help with an SQL query. I've had a bit of a search, but mostly brings up stuff about simpler joins involving two tables.
The table structure is:
table.Itineraries
ItineraryID, Itinerary, etc

table.Activities:
ActivityID, Activity, etc

And an interlinking table
table.ItineraryActivities:
ItineraryID, ActivityID

And I have a page here, listing Itineraries:
http://www.goodsafariguide.net/itineraries_beta/index101.php
That I would like to include some of the Activities on.
If it was just the first two tables, and tableActivities had an ItineraryID column, I assume it would be:
SELECT *
FROM Itineraries
INNER JOIN Activities ON Itineraries.ItineraryID = Activities.ItineraryID

But I'm not sure what the syntax would be to achieve the same thing with the interlinking table as well.
Hope that makes sense.
EDIT:
I now have it displaying the Activities (in this case Countries):
http://www.goodsafariguide.net/itineraries_beta/index501.php
So where there are two instances of 'Test Itinerary', one for Tanzania and one for Kenya, I just want one instance, which lists Kenya and Tanzania.

A: You just need a second INNER JOIN.
Try this:
SELECT *
FROM Itineraries i
INNER JOIN ItineraryActivities ia ON ia.ItineraryID = i.ItineraryID
INNER JOIN Activities a ON a.ActivityID = ia.ActivityID


text:
Q: Bracket checker So this code is supposed to take user input and see if the brackets are balanced. The instructions just say use a while loop to input multiple lines and print "Exit program". My question: I'm not sure how to break out of the while loop after a few lines of input so that sout("Exit program") will be called - everything else works fine.
PS. still very new to this
import java.util.Scanner;
import java.util.Stack;

public class BracketChecker {
    private Stack<Character> stack = new Stack<>();

    public boolean check(String text) {
        for (int i = 0; i < text.length(); i++){
            char c = text.charAt(i);
            if (c == '{') {
                stack.push(c);
            }

            if (c == '}'){
                if (stack.empty())
                    return false;
                stack.pop();
            }
        }

        if (stack.isEmpty()){
            return true;
        }
        else{
            return false;
        }

    }

    public static void main(String[] args) {
        System.out.println("Starting bracket checker app");
        BracketChecker checker = new BracketChecker();
        Scanner in = new Scanner(System.in);
        String temp;
        while(in.hasNextLine()) {
            temp = in.nextLine();

            if (checker.check(temp)) {
                System.out.println("Syntax correct");
            } else {
                System.out.println("Syntax error");
            }

        }

        System.out.println("Exiting checker");
    }
}

A: Your while loop:
 while(in.hasNextLine()) {
        temp = in.nextLine();

        if (checker.check(temp)) {
            System.out.println("Syntax correct");
        } else {
            System.out.println("Syntax error");
        }

    }

will result in an infinite loop, if you wanted to you could have the user input an int to the amount of times they want to input like
int amount = scanner.nextInt();

and the using the amount in a for loop. Also you can change the part:
if (stack.isEmpty()){
        return true;
    }
    else{
        return false;
    }

to just be return stack.isEmpty();

A: You need to define somekind of stop command like stop, then check if you read this command and if yes end the program:
while(in.hasNextLine()) {
    temp = in.nextLine();

    if ("stop".equals(temp)) {
        System.out.println("Exiting checker");
        return;
    }

    if (checker.check(temp)) {
        System.out.println("Syntax correct");
    } else {
        System.out.println("Syntax error");
    }
}

System.out.println("Error");

you will also need to change the last part of the check method:
if (stack.isEmpty()){
    return true;
}
else{
    stack.clear();
    return false;
}

this way the stack is always empty at the end of the check method.
Then input like
{{
{}
stop

will procude the following output
Starting bracket checker app
Syntax error
Syntax correct
Exiting checker

But since this is for an assigment you should check with your tutor or lecturer how you are supposed to end the program


text:
Q: Initialize static dictionary with EqualityComparer I need to initialize static dictionary with EqualityComparer because I am using custom class as key in this dictionary. When this dictionary is not static I am able to initialize it, but when it is marked as static it does not work and I am getting exception during initialization: "Check to determine if the object is null before calling the method". My code is stated below. Can you please tell me what I am doing wrong?
Thank you in advance.
    public static Dictionary<Date, List<Name>> NameDays;

    public class EqualityComparer : IEqualityComparer<Date>
    {
        public bool Equals(Date x, Date y)
        {
            return ((x.Day.Equals(y.Day)) && (x.Month.Equals(y.Month)));
        }
        public int GetHashCode(Date x)
        {
            return x.Day.GetHashCode() ^ x.Month.GetHashCode();
        }
    }

    public static async void LoadNameDays()
    {
        NameDays = new Dictionary<Date, List<Name>>(new EqualityComparer());
        .....

A: It seems your dictionary is null. You can initialize it with field initializer and you can remove the dictionary initialization code in  LoadNameDays method.
public static Dictionary<Date, List<Name>> NameDays = new Dictionary<Date, List<Name>>(new EqualityComparer());

Also I suggest you to make the field readonly to make sure you're working on the same thing, you don't unintentionally assign something else.

A: You have to create the dictionary when you declare it instead:
public static Dictionary<Date, List<Name>> NameDays =
    new Dictionary<Date, List<Name>>(new EqualityComparer());

A: Your static member must be set prior to use.  You can do this in its containing class constructor or as a field initilizer.  It cannot be initialized by another method.  Think of a static member as belonging to the class itself and not a particular instance.
Read this.


text:
Q: What's the idea behind this inequality? $e^{\frac{\ln x}{x-1}}\geq\frac{e}{3}(1+\frac{1}{\sqrt{x}}+\frac{1}{x})$
This inequality's image (left hand substracted right hand)

which shows a perfect approximation between (1,1.5), where it nearly keeps unchanged.
I wonder how this inequality was created, did it use some series expanding or some famous inequalities?

A: With substitution $x = \frac{1}{y^2}$, the inequality is written as
$$\mathrm{e}^{\frac{-2y^2\ln y}{1-y^2}}
\ge \frac{\mathrm{e}}{3}( 1 + y + y^2).$$
Denote $f(y) = \mathrm{e}^{\frac{-2y^2\ln y}{1-y^2}}$.
Then the inequality above is written as $f(y) \ge f(1) + f'(1)(y-1) + \frac{1}{2}f''(1)(y-1)^2$.
The RHS is the second order Taylor approximation of LHS.
This approximation is nice around $y=1$ because $f'''(1) = 0$ and $f'''(y)$ is small near $y=1$.

A: This is not an answer.
Firt of all, Welcome to the site !.
In the area of function approximation, a lot of things can be done. Let me propose one I just made for you
$$e^{\frac{\log( x)}{x-1}}=e\frac{1+\frac{87}{100} (x-1)+\frac{37}{240}(x-1)^2}{1+\frac{137 }{100}(x-1)+\frac{457 }{1200}(x-1)^2}$$
The inequality does not hold but it is almost OK.

A: Let
$$f(x):=e^{\log x/(x-1)},\qquad g(x):={e\over3}\left(1+{1\over\sqrt{x}}+{1\over x}\right)\ .$$
Then
$$\log\bigl(f(1+t)\bigr)={\log(1+t)\over t}=1-{t\over2}+{t^2\over3}-{t^3\over4}+{t^4\over5}-{t^5\over6}+?\,t^6\ .$$
Some calculation gives
$$\log\bigl(g(1+t)\bigr)=1-{t\over2}+{t^2\over3}-{t^3\over4}+{115t^4\over576}-{239t^5\over1440}+?\,t^6$$
It follows that
$$\log{f(1+t)\over g(1+t)}=\log\bigl(f(1+t)\bigr)-\log\bigl( g(1+t)\bigr)={1\over2880}t^4+?\,t^5\qquad(t\to0)\ .\tag{1}$$
This shows that ${f(x)\over g(x)}\approx1$ and $\geq1$ with high precision when $x\approx1$.
It seems that the function $g$ has been set up in such a way that we get a result in the sort of $(1)$. Other data resulting in a similar result would have been possible.


text:
Q: Why mutex is faster than critical section in my code? DINING PHILOSOPHERS PROBLEM:
The dining philosophers problem states that there are 5 philosophers sharing a circular table and they eat and think alternatively. There is a bowl of rice for each of the philosophers and 5 chopsticks. A philosopher needs both their right and left chopstick to eat. A hungry philosopher may only eat if there are both chopsticks available.Otherwise a philosopher puts down their chopstick and begin thinking again.
The dining philosopher is a classic synchronization problem as it demonstrates a large class of concurrency control problems.

I was tasked with solving the problem of five dining philosophers in two ways. With mutex and critical section. that's what i got

Critical section:
#include <iostream>
#include <windows.h>
#include <time.h>

#define NUMBER_OF_STICKS 5
#define NUMBER_OF_PHILOSOPHERS 5

DWORD WINAPI philosopher_thread(LPVOID philosopherNumber);
CRITICAL_SECTION chopSticks[NUMBER_OF_STICKS]; // will save every stick (ecery critical section)
int eatingTime[NUMBER_OF_PHILOSOPHERS]; // will save eating time of ich philosopher (in miliseconds)

int main()
{
    HANDLE WINAPI philosophers[NUMBER_OF_PHILOSOPHERS]; // will save every philosopher (every thread)

    // init sticks (critical sections)
    for (int i = 0; i < NUMBER_OF_STICKS; i++)
    {
        InitializeCriticalSection(&chopSticks[i]);
    }

    //create philosophers (threads)
    for (int i = 0; i < NUMBER_OF_PHILOSOPHERS; i++)
    {
        philosophers[i] = CreateThread(
            NULL,
            0,
            philosopher_thread,
            &i,
            0,
            NULL
        );

        if (philosophers[i] == NULL) // check if there was trouble in creating thread
        {
            std::cout << GetLastError() << std::endl;
        }
        else
        {
           std::cout << "Philosopher " << i + 1 << " Succsesfully created.\n"; // print this message ig thread was succsesfully created
        }
    }

    // wait for each thread until main will end
    for (int i = 0; i < NUMBER_OF_PHILOSOPHERS; i++)
    {
        WaitForSingleObject(*(philosophers + i), INFINITE);
    }

    // delete critical sections
    for (int i = 0; i < NUMBER_OF_STICKS; i++)
    {
        DeleteCriticalSection(&chopSticks[i]);
    }

    // print the eating time
    for (int i = 0; i < NUMBER_OF_PHILOSOPHERS; i++)
    {
        printf("Philosopher %d Ate %d miliseconds\n", i + 1, eatingTime[i]);
    }

    // close threads
    for (int i = 0; i < NUMBER_OF_PHILOSOPHERS; i++)
    {
        CloseHandle(*(philosophers + i));
    }

    system("PAUSE");
    return 0;
}

// this func will run the philosophers (the threads)
DWORD WINAPI philosopher_thread(LPVOID philosopherNumber)
{
    int philosopherNum = *(int*)philosopherNumber; // will store philosopher index in integer type
    int firstchopStickForEating = 0; // will store the index of first chopstick that philosopher need for eating
    int secondchopStickForEating = 0; // will store the index of second chopstick that philosopher need for eating

    if (philosopherNum == 4) // if philosopher index is 4 (the last philosopher in the array)
    {
        firstchopStickForEating = philosopherNum; //first chopstick is index 4
        secondchopStickForEating = 0; // second chopstick is index 0
    }
    else //if its every other philosopher but 4
    {
        firstchopStickForEating = philosopherNum; // first chopstick is the same index as philosopher
        secondchopStickForEating = philosopherNum + 1; // second philosopher is the same index + 1
    }

    // enter critical sections for the shopscticks
    EnterCriticalSection(&chopSticks[firstchopStickForEating]);
    EnterCriticalSection(&chopSticks[secondchopStickForEating]);

    clock_t start, end; // will store start time and end time for eating
    int msecs; // will save the diffrenece between start and end

    start = clock(); // save time to the start

    // eat
    for (int i = 0; i < 100000; i++)
    {
        printf("Philosopher %d Eating his %d time from 100000\n", philosopherNum + 1, i + 1);
    }

    end = clock(); // save time to the end

    eatingTime[philosopherNum] = ((int)(end - start)) * 1000 / CLOCKS_PER_SEC; // svae to the eating time array the difference between start and end

    // leave critical section
    LeaveCriticalSection(&chopSticks[firstchopStickForEating]);
    LeaveCriticalSection(&chopSticks[secondchopStickForEating]);

    return 0;
}

Mutex:
#include <iostream>
#include <windows.h>
#include <time.h>

#define NUMBER_OF_STICKS 5
#define NUMBER_OF_PHILOSOPHERS 5

DWORD WINAPI philosopher_thread(LPVOID philosopherNumber);
HANDLE mutexChopSticks[NUMBER_OF_STICKS]; // will save every stick (ecery critical section)
int eatingTime[NUMBER_OF_PHILOSOPHERS]; // will save eating time of ich philosopher (in miliseconds)

int main()
{
    HANDLE WINAPI philosophers[NUMBER_OF_PHILOSOPHERS]; // will save every philosopher (every thread)

    // Create a mutex with no initial owner
    for (int i = 0; i < NUMBER_OF_STICKS; i++)
    {
        mutexChopSticks[i] = CreateMutex(
            NULL,              // default security attributes
            FALSE,             // initially not owned
            NULL);             // unnamed mutex
    }

    //create philosophers (threads)
    for (int i = 0; i < NUMBER_OF_PHILOSOPHERS; i++)
    {
        philosophers[i] = CreateThread(
            NULL,
            0,
            philosopher_thread,
            &i,
            0,
            NULL
        );

        if (philosophers[i] == NULL) // check if there was trouble in creating thread
        {
            std::cout << GetLastError() << std::endl;
        }
        else
        {
            std::cout << "Philosopher " << i + 1 << " Succsesfully created.\n"; // print this message ig thread was succsesfully created
        }
    }

    // wait for each thread until main will end
    for (int i = 0; i < NUMBER_OF_PHILOSOPHERS; i++)
    {
        WaitForSingleObject(*(philosophers + i), INFINITE);
    }

    // close mutex
    for (int i = 0; i < NUMBER_OF_STICKS; i++)
    {
        CloseHandle(*(mutexChopSticks + i));
    }

    // print the eating time
    for (int i = 0; i < NUMBER_OF_PHILOSOPHERS; i++)
    {
        printf("Philosopher %d Ate %d miliseconds\n", i + 1, eatingTime[i]);
    }

    // close threads
    for (int i = 0; i < NUMBER_OF_PHILOSOPHERS; i++)
    {
        CloseHandle(*(philosophers + i));
    }

    system("PAUSE");
    return 0;
}

// this func will run the philosophers (the threads)
DWORD WINAPI philosopher_thread(LPVOID philosopherNumber)
{
    int philosopherNum = *(int*)philosopherNumber; // will store philosopher index in integer type
    int firstchopStickForEating = 0; // will store the index of first chopstick that philosopher need for eating
    int secondchopStickForEating = 0; // will store the index of second chopstick that philosopher need for eating

    if (philosopherNum == 4) // if philosopher index is 4 (the last philosopher in the array)
    {
        firstchopStickForEating = philosopherNum; //first chopstick is index 4
        secondchopStickForEating = 0; // second chopstick is index 0
    }
    else //if its every other philosopher but 4
    {
        firstchopStickForEating = philosopherNum; // first chopstick is the same index as philosopher
        secondchopStickForEating = philosopherNum + 1; // second philosopher is the same index + 1
    }

    // Request ownership of mutex.
    WaitForSingleObject(mutexChopSticks[firstchopStickForEating], INFINITE);
    WaitForSingleObject(mutexChopSticks[secondchopStickForEating], INFINITE);

    clock_t start, end; // will store start time and end time for eating
    int msecs; // will save the diffrenece between start and end

    start = clock(); // save time to the start

    // eat
    for (int i = 0; i < 100000; i++)
    {
        printf("Philosopher %d Eating his %d time from 100000\n", philosopherNum + 1, i + 1);
    }

    end = clock(); // save time to the end

    eatingTime[philosopherNum] = ((int)(end - start)) * 1000 / CLOCKS_PER_SEC; // svae to the eating time array the difference between start and end

    // Release ownership of the mutex object
    ReleaseMutex(mutexChopSticks[firstchopStickForEating]);
    ReleaseMutex(mutexChopSticks[secondchopStickForEating]);

    return 0;
}

From what i learned critical section should be faster than mutex
but in my case mutex is faster. What is the problem?


text:
Q: WSO2 ESB - Unable to access properties set in script mediator in a payload mediator I've got a Script mediator where I've set a certain value (mc.setProperty("x",1)) and immediately after the script mediator I've set a PayloadFactory mediator where I'm trying to get the value x (get-property("x")). I used Log mediators in between my mediation logic to check if the property value is set. But the value isn't set. I'm using js for Script mediator.

A: I have same problem. I solved it by add call function "String" in script.
Something like -
<script language="js"><![CDATA[
    mc.setProperty("x", String(1));
]]></script>
<log level="custom">
    <property expression="get-property('x')" name="x" xmlns:ns="http://org.apache.synapse/xsd"/>
</log>

A: Can you try out the following? This is possible with WSO2 ESB 5.0.0
<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="TestProxy"
       startOnLoad="true"
       statistics="disable"
       trace="disable"
       transports="http,https">
   <target>
      <inSequence>
         <script language="js">mc.setProperty("x", 1);</script>
         <log level="custom">
            <property expression="get-property('x')" name="x"/>
         </log>
         <payloadFactory media-type="xml">
            <format>
               <value xmlns="">$1</value>
            </format>
            <args>
               <arg evaluator="xml" expression="get-property('x')"/>
            </args>
         </payloadFactory>
         <respond/>
      </inSequence>
   </target>
   <description/>
</proxy>


text:
Q: Has the window loaded? Is there a way to verify if the page has loaded in c#, I am firing an HTML window from code, and would like to know if the window has loaded? Is that possible?
HtmlPage.Window.Navigate(new Uri(uri), "_blank", "toolbar=no");

A: How things basically work:

*

*Server sends a response to the browser

*Browser accepts it (downloads html/silverlight)

*Browser renders the page

The server has no way to know if the page is successfully loaded or if something interrupted the process after the response is sent. If you really need to know the page is loaded, you need to find it out with a client side code js or silverlight and send information/request back to the server that the page is loaded.


text:
Q: Is the any way to get the sub version of Delphi compiler My component library uses conditional compiling to make the source code compatible to all Delphi compiler since Delphi 7. I use the CompilerVersion define of DCC32.exe. For example
{$IF CompilerVersion >= 24}
   ....
{$IFEND}

This has always worked well but now there are some major difference in VCL library between various 10.4 versions. This requires the code to be different in 10.4, 10.4.1 and 10.4.2.
How can I check what sub version of Delphi the compiler is for?

A: From Delphi 10.4.1, you can check which RTL/source is being used, by using (for example):
{$IF Declared(RTLVersion1042)} // Compiled using Delphi 10.4.2 RTL


text:
Q: variable overwriting in PHP For example I have this code:
$route = 'product/category';

//variable overload
$type  = explode('/',$route);
$type  = $type[1];

My thinking behind this is that I actually don't need unique variable name for exploded variable, so why not to overwrite?
Is this really bad concept? Or is there some more elegant way to write this?

A: No, it's absolutely not bad. All you're doing here is assigning a new value to a variable. It has no special name.
As for more elegantly writing it, you could write the following as of PHP 5.4:
$type = explode("/", $route)[0];

A: Other elegant solution:
list($type, ) = explode("/", $route);

I think it's the best one.


text:
Q: Lowres application icon on window switching (alt-tab) I manually downloaded and installed Sublime Text 2 (instead of adding the repository and installing via apt-get install) and I'm having some trouble getting gnome to find the high res icons for sublime.
I extracted the application to /usr/lib/sublime-text
Added the following executable script as /usr/bin/sublime
#!/bin/sh
export SUBLIME_HOME="/usr/lib/sublime-text"
$SUBLIME_HOME/sublime_text $*

The /usr/lib/sublime-text/Icon directory contains icons for various resolutions in subdirectories (16x16, 32x32, 48x48, 128x128, 256x256), and I used the 256x256 one when I added the menu item to the cinnamon menu.
How does Gnome locate the icon for an application? I renamed the /etc/lib/sublime-text/Icon directory and then I didn't get an icon at all (default gnome icon) so
Gnome's obviously using an icon from the /usr/lib/sublime-text folder, but if so why how do I get it to use a highres one?
Also how does Gnome match the application to the image name? Currently the script in /usr/bin is named sublime, the directory in /usr/lib is named sublime-text, the executable in /usr/bin/lib/sublime-text is named sublime_text and the menu item is defined in a file named Sublime Text.desktop.
I seriously don't understand how the system manages to match all of this...

I'm running Linux Mint 13 (Cinnamon)

A: While this isn't the best solution, I get around the problem of low resolution icons by just pointing directly to the highest possible version inside the .desktop file. In this case specifically, I have it pointing to a local copy of the official 256px icon, but any location should work.
Icon=/home/patrick/.icons/sublime-256.png

A: I copied the Sublime icons over to the various directories /usr/share/icons/hicolor/[NxN]/apps
Then I made a sublime.desktop file and put it under ~/.local/share/applications, with Icon=sublime_text.
That seemed to work.


text:
Q: Test code for the new standard Order object The last line insert ordPd causes exception: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, Price Book Not Set on Order: []
All lines before the last line are all ok, and have confirmed again and again.
Have tried whatever I can do, still can't resolve the problem. It seems the pricebook and order are not related, however, they should be related by the last 2 line.
Also, Have done research and use 'SeeAllData=true' tag.
The code:
Account acct = new Account(Name='tAccount');
insert acct;

Contract ct = new Contract();
ct.AccountId = acct.Id;
ct.Status = 'Draft';
ct.StartDate = Date.Today();
ct.ContractTerm = 12;
insert ct;

ct.Status = 'Activated';
update ct;

Order od = new Order();
od.Name = '14TPE000001';
od.AccountId = acct.Id;
od.EffectiveDate = Date.Today();
od.ContractId = ct.Id;
od.Status = 'Draft';
insert od;

Product2 pd = new Product2(Name='Pord A',isActive=true);
pd.IsActive = true;
insert pd;

PriceBook2 pb2Standard = [select Id from Pricebook2 where isStandard=true];
Id standardPriceBookId = pb2Standard.Id;

PricebookEntry pbe = new PricebookEntry(Pricebook2Id=standardPriceBookId, Product2Id=pd.Id, UnitPrice=99, isActive=true);
insert pbe;
Product2 p2ex = [SELECT Name FROM Product2 WHERE Id = :pd.Id];
System.assertEquals(pd.Name,p2ex.Name);

OrderItem ordPd = new OrderItem(PriceBookEntryId=pbe.Id, OrderId=od.Id, Quantity=1, UnitPrice=99);
insert ordPd;

A: The variable od must have it's Pricebook2Id set before inserting the record. This the same design functionality as the Opportunity and Quote objects.

A: The minimum working test code:
PriceBook2 pb2Standard = [select Id from Pricebook2 where isStandard=true];
Id standardPriceBookId = pb2Standard.Id;

PricebookEntry pbe = [ SELECT Id,Product2Id,Pricebook2Id,UnitPrice FROM PricebookEntry WHERE Pricebook2Id = :standardPriceBookId AND isActive=true LIMIT 1 ];

Order od = [ SELECT Id,Pricebook2Id FROM Order LIMIT 1 ];
od.Pricebook2Id = pb2Standard.Id;
update od;

OrderItem ordPd = new OrderItem(PriceBookEntryId=pbe.Id, OrderId=od.Id, Quantity=1, UnitPrice=pbe.UnitPrice, ServiceDate=Date.Today());
insert ordPd;

The last 3-5 lines are key to resolve the problem.
Ref: http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_objects_orderitem.htm


text:
Q: Unable to connect Azure SQL from Report Builder I am unable to connect to Azure SQL and access my database from Report builder.
Getting following error:

I had enabled the access in Azure portal for the above IP mentioned. Still getting the error.

A: I was able to repro successfully, Make sure you specify the Database Name explicitly and try again.


text:
Q: Eventlisteners for jqm side panel on multiple pages I am new to JQM and I'm using Phongeap with JQM for a new project.
My javascript is in one single js file and I'm loading the views from multiple html files.
As the transitions of the siede panel are poor, when I change pages via <a href="page2.html"> I tried to to use event listeners for the Menuitems.
    function setPanelListeners(){
    $('#menu_search').click(function() {
                            switchPageTo('search.html');
                            });
    $('#menu_schedule').click(function() {
                              switchPageTo('program.html');
                              });
    $('#menu_news').click(function() {
                              switchPageTo('news.html');
                              });
}

I call this function on the pagebeforeshoe event of each page. To fix the transitions to the way I need it, I use this function
    // Close Panel then change page
function switchPageTo(url){
    $('#menupanel').panel('close');
    setTimeout(function() {
               $.mobile.changePage( url, { transition: 'fade'} );
            },200);
}

So here is the Problem. It actually works fine on the first page. But on the second page the Menuitems won't work, I guess the event listers are not listening for the new panel, because in the html the panel is loaded twice! And the Event listeners only listen for the first panel (from the first page) which is not displayed on the second page.
Any help is appreciated!

A: Are you adding panel dynamically on the second page? In JQM 1.3 you have to add panel separately to each page, although this restriction will be removed in future versions.
Use event delegation for dynamic panels:
$(document).on('click' ,'#menu_search' function() {
        switchPageTo('search.html')
   });


text:
Q: IBM MQ - Wake up a MQ Channel I was wondering if you can help me solve the following problem.
After a while of no-messages being received by the Queue Manager, the Queue Manager goes to 'sleep' and unless you use IBM WebSphere Explorer to 'start the queue' using the command.
On the other hand, if you send a message and expect a response, it will say - Cannot connect.
Then, if you send the same message again, expecting the response, I've noticed the Queue Manager wakes-up.
So to summarize, my question is:
Does anyone know of a command to 'wake-up' the Queue Manager, before sending an actual message(as above).
Thanks in Advance,

A: IBM MQ Queue manager does not go to sleep. If queue manager is running, then it's awake and is no "wake up". There must be some reason because of which queue manager might have shutdown. Check logs in "errors" folder.
Can you please explain what you mean by 'start the queue'? because there is nothing like that. There is start queue manager.
What MQ reason code are you getting when it says "cannot connect".

A: Ok,
So I spoke to the admin of the MQ Service and there is a parameter they can set (some timeout I think) that sets it to 0 so it never 'sleeps'.
This will fix the problem.


text:
Q: In Tensorflow, is there a built in function to compute states over time given a transition matrix? I have a system given by this recursive relationship: xt = At xt-1 + bt. I wish to compute xt for all t, with At, bt and x0 given. Is there are built-in function for that? If I use a loop it would be extremely slow. Thanks!

A: There is sort of a way. Let's say you have your A matrices in a 3D tensor with shape (T, N, N), where T is the total number of time steps and N is the size of your vector. Similarly, B values are in a 2D tensor (T, N). The first step in the computation would be:
x1 = A[0] @ x0 + B[0]

Where @ represents matrix product. But you can convert this into a single matrix product. Suppose we add a value 1 at the end of x0, and we call that x0p (for prime):
x0p = tf.concat([x, [1]], axis=0)

And now we build a new 3D tensor Ap with shape (T, N+1, N+1), such that for each A[i] we concatenate B[i] as a new column, and then we add a row with N zeros and a single one at the end:
AwithB = tf.concat([tf.concat([A, tf.expand_dims(B, 2)], axis=2)], axis=1)
AnewRow = tf.concat([tf.zeros((T, 1, N), A.dtype), tf.ones((T, 1, 1), A.dtype)], axis=2)
Ap = tf.concat([AwithB, AnewRow], axis=1)

As it turns out, you can now say:
x1p = Ap[0] @ x0p

And therefore:
x2p = Ap[1] @ x1p = Ap[1] @ Ap[0] @ x0p

So we just need to compute all the matrix product of all matrices in Ap across the first dimension. Unfortunately, there does not seem to be a direct operation to compute that with TensorFlow, but you can do it relatively fast with tf.scan:
Ap_prod = tf.scan(tf.matmul, Ap)[-1]

And with that you just have to do:
xtp = Ap_prod @ x0p

Here is a proof of concept (the code is tweaked to support single examples and batches, either in the A and B values or in the x)
import tensorflow as tf

def compute_state(a, b, x):
    s = tf.shape(a)
    t = s[-3]
    n = s[-1]
    # Add final 1 to x
    xp = tf.concat([x, tf.ones_like(x[..., :1])], axis=-1)
    # Add B column to A
    a_b = tf.concat([tf.concat([a, tf.expand_dims(b, axis=-1)], axis=-1)], axis=-2)
    # Make new final row for A
    a_row = tf.concat([tf.zeros_like(a[..., :1, :]),
                       tf.ones_like(a[..., :1, :1])], axis=-1)
    # Add new row to A
    ap = tf.concat([a_b, a_row], axis=-2)
    # Compute matrix product reduction
    ap_prod = tf.scan(tf.matmul, ap)[..., -1, :, :]
    # Compute final result
    outp = tf.linalg.matvec(ap_prod, xp)
    return outp[..., :-1]

#Test
tf.random.set_seed(0)
a = tf.random.uniform((10, 5, 5), -1, 1)
b = tf.random.uniform((10, 5), -1, 1)
x = tf.random.uniform((5,), -1, 1)
y = compute_state(a, b, x)
# Also works with batches of (a, b) or x
a = tf.random.uniform((100, 10, 5, 5), -1, 1)
b = tf.random.uniform((100, 10, 5), -1, 1)
x = tf.random.uniform((100, 5), -1, 1)
y = compute_state(a, b, x)


text:
Q: Counting visible elements in ng-repeat I want to know the number of visible elements shown after being subject to an ng-if and ng-show. Here is a simplified example:
$scope.fruits = [
        { name: 'apple', shape: 'round', color: 'red' },
        { name: 'stop sign', shape: 'pointy', color: 'red' },
        { name: 'orange', shape: 'round', color: 'orange' },
        { name: 'tomato', shape: 'round', color: 'red'}
    ];

{{fruit.name}}

Is there a way to count the resulting number of items being shown?

A: I ended up not using the ng-if or ng-show at all, and just filtered the ng-repeat. This way, I did not have to hide anything and was easily able to get the length of the results.

{{fruit.name}}

   {{filteredFruits.length}} fruits

$scope.myFilter = function(x) {
    if (x.color == 'red') {
        return x;
    }
}

A: With this you can remove your custom filter and use as keyword to get the li length.

var app = angular.module('myApp', []);
app.controller('Ctrl', function($scope) {
   $scope.fruits = [
        { name: 'apple', shape: 'round', color: 'red' },
        { name: 'stop sign', shape: 'pointy', color: 'red' },
        { name: 'orange', shape: 'round', color: 'orange' },
        { name: 'tomato', shape: 'round', color: 'red'}
    ];
});

{{fruit.name}}

A: try this

{{fruit.name}}

Number of Items: {{Items.length}}

A: You can count number of items,

$scope.fruits = [
            { name: 'apple', shape: 'round', color: 'red' },
            { name: 'stop sign', shape: 'pointy', color: 'red' },
            { name: 'orange', shape: 'round', color: 'orange' },
            { name: 'tomato', shape: 'round', color: 'red' }
        ];

        $scope.FindVisible = function () {
            var visibleObject=0;
            $scope.fruits.forEach(function (v, k) {
                if (v.shape == 'round' && v.color == 'red') {
                    visibleObject = visibleObject + 1;
                }
            });
            alert(visibleObject);
        }

{{fruit.name}}

        <button ng-click="FindVisible()">Find</button>


text:
Q: printer settings changes when RDP to the terminal server Let me explain the problem.
I have network printer mapped on the workstation. Printer on this workstation is set to print as black&white only. I RDP to the Terminal Server and printer is getting populated there as well automatically. Unfortunately after login to terminal server color preferences are changed back to color for this particular printer.
What should I do to get same preferences as on the fat client?
I have heard that it has something to to with initial printer settings on the PC where printer is installed and the advice I got was to uninstall printer from the server, then from all workstations, install it on the server again, set all settings and map it on all workstations.
I was wondering if there is easier way to do it. I will be great for any help. I will provide more information if needed of course.
Regards Mariusz

A: I would start with replacing the driver on the terminal server, with one that is perhaps newer or better matched to the client's driver.
We've made major changes to settings within a few different printer drivers on Server 2008 RDP, and didn't have any issues with the clients logging of and back on. But the drivers we used on the server and PC matched exactly.


text:
Q: Get json ajax php form to work remotely So, essentially I have this Javascript which interprets the JSON from my php code.  It works great on the local server, however, when I try to move the script to a different server it will not work.  I have added the
<?php header("Access-Control-Allow-Origin: *"); ?>

also i've declared my database connection as global within my PHP function.
I'm confused as to why these solutions aren't working..  Also, I understand some of the script is iffy, but I'm only interested in figuring out why its not working from different servers.

Some Info when I look at the web console from firebug:
Access-Control-Allow-Orig...    *
Connection  Keep-Alive
Content-Length  0
Content-Type    application/json
Date    Wed, 24 Sep 2014 04:22:57 GMT
Keep-Alive  timeout=5, max=100
Server  Apache/2.2.27 (Unix) mod_ssl/2.2.27 OpenSSL/1.0.1e-fips DAV/2 mod_bwlimited/1.4
X-Powered-By    PHP/5.4.29

Looks like it is communicating with server but not able to interpret data? thoughts?
Also, this error comes up in the console from the remote server but not when I run on local server:
SyntaxError {stack: (...), message: "Unexpected end of input"}message: "Unexpected end of input"stack: (...)
Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…
parsererror

The PHP code is pretty long (and I prefer not to release all of it) - however here is the shortened version:
<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
require "../database/db.php";

if (is_ajax()) {
  if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
    $action = $_POST["action"];
    switch($action) { //Switch case for value of action
      case "test": test_function(); break;
    }
  }
}

//Function to check if the request is an AJAX request
function is_ajax() {
  return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

function test_function(){
$c="1";
global $con;

  $return = $_POST; //to reference post

$content=$return["content"];

//see if content is 140 characters or less
if(strlen($content)>140){ $c="0"; $lerror="
Your message must be 140 characters or less in length!
"; }

if($c=="0"){  //doesnt pass validation
$return["success"]="no";
$return["errors"]="$lerror";
}

if($c!="0"){ //passes validation
$return["success"]="yes";
}
if(isset($_GET['callback'])){  //jsonp edit
$return["json"] = json_encode($return);
echo $_GET['callback']."(".json_encode($return).")"; //jsonp edit
}

}

Also after converting to JSONP on remote server - get error -
"jQuery111006159528985153884_1411663761720 was not called"

A: When dealing with jQuery AJAX using a data type of JSON, any notice, warning or error produced by the server side script will cause issues.  The reason being is the outputted PHP errors break the JSON encoding that jQuery is expecting.
I suspect the two environments are not identical, perhaps a different PHP version, missing PHP extension or different settings in the php.ini file.
The best thing to do is to use the provided jQuery AJAX error callback to console log any errors allowing you to essentially troubleshoot any issues being thrown by the server side script.
!!! EDIT 3 !!!
Client Code
$.ajax({
    type: "POST",
    dataType: "json",
    url: "http://myurl.com/jsonpost.php",
    data: data,
    success: function(response) {
        console.log(response);
    },
    error: function(xhr, status, error) {
       console.log(xhr);
       console.log(status);
       console.log(error);
    }
});

Server Side Code
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');

echo json_encode(array('success' => 'yes'));

Using this bare bones version of your code I can successfully make a cross domain request and console log the response.  If you implement this code and it still does not work there is something else at play at the server and/or network level.

A: You can make AJAX calls to a backend API, it needs to return JSONP format and not just JSON, otherwise you can get error. This is due to same origin policy:
https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy.
This discussion may be helpful to understand JSONP:
Can anyone explain what JSONP is, in layman terms?
However, one alternative is disable the security of Google Chrome browser, then it will work. But this is not a solution. It is better to use JSonP format.


text:
Q: Initialize static class atributes in python I have the following class
class Test:
    x = None  # this is a static variable common to all object created from this class

    @classmethod
    def initializeX(cls):
        cls.x = 5

Note that x in practice is an object that needs to be common to all objects created from this class and I can not write e.g x = 5 so I need a function to initialize it. So how can I call the function that initializes x only once and not for every object created? Also is it generally good practice in python to skip x = None and define x directly in initializeX(cls)?

A: In the class constructor you could write an if check to see if the class attribute has been created already
if Test.x is None:
  # Do initialization

A: Any reason you can't do something like this?

def _new_x():
    return [1, 2, 3]  # <~~ whatever obj you need to initialize

class Test:
    x = _new_x()

instance_a = Test()
instance_b = Test()

# note they're the same:
assert instance_a.x is instance_b.x

A: You can initialize (and set) it at the class level.
class Test:
    x = None  # this is a static variable common to all object created from this class
    @classmethod
    def initializeX(self, cls):
        type(cls).x = 5    # Test.x

c1 = Test()
c2 = Test()

c1.initializeX(c1)
print(c1.x)   # 5
print(c2.x)   # 5

Test.x = 10
print(c1.x)   # 10
print(c2.x)   # 10

Output
5
5
10
10


text:
Q: Testing the SQL Server driver existence If I have to test for the driver, Is it the correct way of doing it:
try {
    // Loading the Driver

    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
catch(java.lang.ClassNotFoundException e) {
    return false;
}

I keep on getting an error on the line return false that boolean cannot be converted to integer. Please correct me if I am wrong.
Is it really required to perform this step in Netbeans as I already have the jar file in my library?
Thanks

A: The return type of the method is integer and you are trying to return boolean value in the catch block as ::
return false;

Solution : Change the return type of the method as boolean or return integer value from catch.


text:
Q: Store UUID v4 in MySQL I'm generating UUIDs using PHP, per the function found here
Now I want to store that in a MySQL database.  What is the best/most efficient MySQL field format for storing UUID v4?
I currently have varchar(256), but I'm pretty sure that's much larger than necessary.  I've found lots of almost-answers, but they're generally ambiguous about what form of UUID they're referring to, so I'm asking for the specific format.

A: Store it as VARCHAR(36) if you're looking to have an exact fit, or VARCHAR(255) which is going to work out with the same storage cost anyway. There's no reason to fuss over bytes here.
Remember VARCHAR fields are variable length, so the storage cost is proportional to how much data is actually in them, not how much data could be in them.
Storing it as BINARY is extremely annoying, the values are unprintable and can show up as garbage when running queries. There's rarely a reason to use the literal binary representation. Human-readable values can be copy-pasted, and worked with easily.
Some other platforms, like Postgres, have a proper UUID column which stores it internally in a more compact format, but displays it as human-readable, so you get the best of both approaches.

A: This works like a charm for me in MySQL 8.0.26
create table t (
    uuid BINARY(16) default (UUID_TO_BIN(UUID())),
)

When querying you may use
select BIN_TO_UUID(uuid) uuid from t;

The result is:
# uuid
'8c45583a-0e1f-11ec-804d-005056219395'

A: The most space-efficient would be BINARY(16) or two BIGINT UNSIGNED.
The former might give you headaches because manual queries do not (in a straightforward way) give you readable/copyable values.
The latter might give you headaches because of having to map between one value and two columns.
If this is a primary key, I would definitely not waste any space on it, as it becomes part of every secondary index as well. In other words, I would choose one of these types.
For performance, the randomness of random UUIDs (i.e. UUID v4, which is randomized) will hurt severely. This applies when the UUID is your primary key or if you do a lot of range queries on it. Your insertions into the primary index will be all over the place rather than all at (or near) the end. Your data loses temporal locality, which was a helpful property in various cases.
My main improvement would be to use something similar to a UUID v1, which uses a timestamp as part of its data, and ensure that the timestamp is in the highest bits. For example, the UUID might be composed something like this:
Timestamp | Machine Identifier | Counter

This way, we get a locality similar to auto-increment values.

A: If you always have a UUID for each row, you could store it as CHAR(36) and save 1 byte per row over VARCHAR(36).
uuid CHAR(36) CHARACTER SET ascii

In contrast to CHAR, VARCHAR values are stored as a 1-byte or 2-byte
  length prefix plus data. The length prefix indicates the number of
  bytes in the value. A column uses one length byte if values require no
  more than 255 bytes, two length bytes if values may require more than
  255 bytes.
  https://dev.mysql.com/doc/refman/5.7/en/char.html

Though be careful with CHAR, it will always consume the full length defined even if the field is left empty. Also, make sure to use ASCII for character set, as CHAR would otherwise plan for worst case scenario (i.e. 3 bytes per character in utf8, 4 in utf8mb4)

[...] MySQL must reserve four bytes for each character in a CHAR
  CHARACTER SET utf8mb4 column because that is the maximum possible
  length. For example, MySQL must reserve 40 bytes for a CHAR(10)
  CHARACTER SET utf8mb4 column.
  https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html

A: Question is about storing an UUID in MySQL.
Since version 8.0 of mySQL you can use binary(16) with automatic conversion via UUID_TO_BIN/BIN_TO_UUID functions:
https://mysqlserverteam.com/mysql-8-0-uuid-support/
Be aware that mySQL has also a fast way to generate UUIDs as primary key:

INSERT INTO t VALUES(UUID_TO_BIN(UUID(), true))

A: This could be useful if you use binary(16) data type:
INSERT INTO table (UUID) VALUES
   (UNHEX(REPLACE(UUID(), "-","")))

A: Most efficient is definitely BINARY(16), storing the human-readable characters uses over double the storage space, and means bigger indices and slower lookup. If your data is small enough that storing as them as text doesn't hurt performance, you probably don't need UUIDs over boring integer keys. Storing raw is really not as painful as others suggest because any decent db admin tool will display/dump the octets as hexadecimal, rather than literal bytes of "text". You shouldn't need to be looking up UUIDs manually in the db; if you have to, HEX() and x'deadbeef01' literals are your friends. It is trivial to write a function in your app – like the one you referenced – to deal with this for you. You could probably even do it in the database as virtual columns and stored procedures so the app never bothers with the raw data.
I would separate the UUID generation logic from the display logic to ensure that existing data are never changed and errors are detectable:
function guidv4($prettify = false)
{
    static $native = function_exists('random_bytes');

    $data = $native ? random_bytes(16) : openssl_random_pseudo_bytes(16);
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
    if ($prettify) {
        return guid_pretty($data);
    }
    return $data;
}

function guid_pretty($data)
{
    return strlen($data) == 16 ?
        vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)) :
        false;
}

function guid_ugly($data)
{
    $data = preg_replace('/[^[:xdigit:]]+/', '', $data);
    return strlen($data) == 32 ? hex2bin($data) : false;
}

Edit: If you only need the column pretty when reading the database, a statement like the following is sufficient:
ALTER TABLE test ADD uuid_pretty CHAR(36) GENERATED ALWAYS AS (CONCAT_WS('-', LEFT(HEX(uuid_ugly), 8), SUBSTR(HEX(uuid_ugly), 9, 4), SUBSTR(HEX(uuid_ugly), 13, 4), SUBSTR(HEX(uuid_ugly), 17, 4), RIGHT(HEX(uuid_ugly), 12))) VIRTUAL;

A: I just found a nice article going in more depth on these topics: https://www.xaprb.com/blog/2009/02/12/5-ways-to-make-hexadecimal-identifiers-perform-better-on-mysql/
It covers the storage of values, with the same options already expressed in the different answers on this page:

*

*One: watch out for character set

*Two: use fixed-length, non-nullable values

*Three: Make it BINARY
But also adds some interesting insight about indexes:

*

*Four: use prefix indexes

In many but not all cases, you don't need to index the full length of
  the value. I usually find that the first 8 to 10 characters are
  unique. If it's a secondary index, this is generally good enough. The
  beauty of this approach is that you can apply it to existing
  applications without any need to modify the column to BINARY or
  anything else—it's an indexing-only change and doesn't require the
  application or the queries to change.

Note that the article doesn't tell you how to create such a "prefix" index. Looking at MySQL documentation for Column Indexes we find:

[...] you can create an index that uses only the first N characters of the
  column. Indexing only a prefix of column values in this way can make
  the index file much smaller. When you index a BLOB or TEXT column, you
  must specify a prefix length for the index. For example:
CREATE TABLE test (blob_col BLOB, INDEX(blob_col(10)));
[...] the prefix length in
  CREATE TABLE, ALTER TABLE, and CREATE INDEX statements is interpreted
  as number of characters for nonbinary string types (CHAR, VARCHAR,
  TEXT) and number of bytes for binary string types (BINARY, VARBINARY,
  BLOB).

*

*Five: build hash indexes

What you can do is generate a checksum of the values and index that.
  That's right, a hash-of-a-hash. For most cases, CRC32() works pretty
  well (if not, you can use a 64-bit hash function). Create another
  column. [...] The CRC column isn't guaranteed to be unique, so you
  need both criteria in the WHERE clause or this technique won't work.
  Hash collisions happen quickly; you will probably get a collision with
  about 100k values, which is much sooner than you might think—don't
  assume that a 32-bit hash means you can put 4 billion rows in your
  table before you get a collision.

A: This is a fairly old post but still relevant and comes up in search results often, so I will add my answer to the mix. Since you already have to use a trigger or your own call to UUID() in your query, here are a pair of functions that I use to keep the UUID as text in for easy viewing in the database, but reducing the footprint from 36 down to 24 characters. (A 33% savings)
delimiter //

DROP FUNCTION IF EXISTS `base64_uuid`//
DROP FUNCTION IF EXISTS `uuid_from_base64`//

CREATE definer='root'@'localhost' FUNCTION base64_uuid() RETURNS varchar(24)
DETERMINISTIC
BEGIN
    /* converting INTO base 64 is easy, just turn the uuid into binary and base64 encode */
    return to_base64(unhex(replace(uuid(),'-','')));
END//

CREATE definer='root'@'localhost' FUNCTION uuid_from_base64(base64_uuid varchar(24)) RETURNS varchar(36)
DETERMINISTIC
BEGIN
    /* Getting the uuid back from the base 64 version requires a little more work as we need to put the dashes back */
    set @hex = hex(from_base64(base64_uuid));
    return lower(concat(substring(@hex,1,8),'-',substring(@hex,9,4),'-',substring(@hex,13,4),'-',substring(@hex,17,4),'-',substring(@hex,-12)));
END//


text:
Q: Attempt to invoke virtual method on a null object reference(String equals method) Kotlin Version I have gone through some of the answers related to the topic but in code below I am the using any String method explicitly and hence I am not able to figure out the actual cause of error.
Code for MainScreenAdapter.kt file:
    package adapters

import android.content.Context
import android.os.Bundle
import android.support.v4.app.FragmentActivity
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.TextView
import com.example.champion.echo_12.R
import fragments.SongPlayingFragment
import fragments.Songs

**class MainScreenAdapter(_songDetails: ArrayList<Songs>, _context: Context) :RecyclerView.Adapter<MainScreenAdapter.MyViewHolder>()** {

    var songDetails: ArrayList<Songs>? = null
    var mContext: Context? = null

    init {
        this.songDetails = _songDetails
        this.mContext = _context
    }
    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val songObject = songDetails?.get(position)

        holder.trackTitle?.text = songObject?.songTitle
        holder.trackArtist?.text = songObject?.artist
        holder.contentHolder?.setOnClickListener {
            //Toast.makeText(mContext,songObject?.songTitle+" is Playing",Toast.LENGTH_SHORT).show()
            val songPlayingFragment = SongPlayingFragment()
            val args = Bundle()
            args.putString("songArtist", songObject?.artist)
            args.putString("songTitle", songObject?.songTitle)
            args.putString("path", songObject?.songData)
            //to int required here
            args.putInt("songID",songObject?.songID?.toInt() as Int)
            args.putInt("songPosition", position)
            args.putParcelableArrayList("songData", songDetails)
            songPlayingFragment.arguments = args

            (mContext as FragmentActivity).supportFragmentManager
                    .beginTransaction()
                    .replace(R.id.details_fragment, songPlayingFragment)
                    .addToBackStack("SongPlayingFragment")
                    .commit()
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        **val itemView = LayoutInflater.from(parent.context)
                .inflate(R.layout.row_custom_mainscreen_adapter, parent, false)**

        return MyViewHolder(itemView)

    }
    override fun getItemCount(): Int {

        if (songDetails == null) {
            return 0
        }

        else {
            return (songDetails as ArrayList<Songs>).size
        }
    }

    class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        /*Declaring the widgets and the layout used*/
        var trackTitle: TextView? = null
        var trackArtist: TextView? = null
        var contentHolder: RelativeLayout? = null
        /*Constructor initialisation for the variables*/
        init {
            trackTitle = view.findViewById(R.id.trackTitle) as TextView
            trackArtist = view.findViewById(R.id.trackArtist) as TextView
            contentHolder = view.findViewById(R.id.contentRow) as RelativeLayout
        }
    }
}

Line 56 and Line 16(Bold marked **) are subjected to the error condition.

Call for MainScreenAdapter() Class.
package fragments
import adapters.MainScreenAdapter
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.provider.MediaStore
import android.support.v4.app.Fragment
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.RelativeLayout
import android.widget.TextView
import com.example.champion.echo_12.R

private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 *
 */
class MainScreenFragment : Fragment() {

    var getSongsList: ArrayList<Songs>? = null
    var nowPlayingBottomBar: RelativeLayout? = null
    var playPauseButton: ImageButton? = null
    var songTitle: TextView? = null
    var visibleLayout: RelativeLayout? = null
    var noSongs: RelativeLayout? = null
    var recyclerView: RecyclerView? = null
    var myActivity: Activity? = null
    var _mainScreenAdapter: MainScreenAdapter? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        val view = inflater!!.inflate(R.layout.fragment_main_screen, container, false)

        visibleLayout = view?.findViewById(R.id.visibleLayout)
        noSongs = view?.findViewById(R.id.noSongs)
        nowPlayingBottomBar = view?.findViewById(R.id.hiddenBarMainScreen)
        songTitle = view?.findViewById(R.id.songTitleMainScreen)
        playPauseButton = view?.findViewById(R.id.playPauseButton)
        recyclerView = view?.findViewById(R.id.contentMain)

        return view
        //return inflater.inflate(R.layout.fragment_main_screen, container, false)
    }

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        myActivity=context as Activity
    }

    override fun onAttach(activity: Activity?) {
        super.onAttach(activity)
        myActivity=activity
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        getSongsList=getSongsFromPhone()
        _mainScreenAdapter= MainScreenAdapter(getSongsList as ArrayList<Songs>,myActivity as Context)

        val _mLayoutManager=LinearLayoutManager(myActivity)
        recyclerView?.layoutManager=_mLayoutManager
        recyclerView?.itemAnimator=DefaultItemAnimator()
        recyclerView?.adapter=_mainScreenAdapter

    }

    fun getSongsFromPhone(): ArrayList<Songs>{

        var arrayList = ArrayList<Songs>()
        var contentResolver = myActivity?.contentResolver
        var songUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
        var songCursor = contentResolver?.query(songUri, null, null, null, null)

        if (songCursor != null && songCursor.moveToFirst()) {
            val songId = songCursor.getColumnIndex(MediaStore.Audio.Media._ID)
            val songTitle = songCursor.getColumnIndex(MediaStore.Audio.Media.TITLE)
            val songArtist = songCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)
            val songData = songCursor.getColumnIndex(MediaStore.Audio.Media.DATA)
            val dateIndex = songCursor.getColumnIndex(MediaStore.Audio.Media.DATE_ADDED)

            while (songCursor.moveToNext()) {
                var currentId = songCursor.getLong(songId)
                var currentTitle = songCursor.getString(songTitle)
                var currentArtist = songCursor.getString(songArtist)
                var currentData = songCursor.getString(songData)
                var currentDate = songCursor.getLong(dateIndex)

                arrayList.add(Songs(currentId, currentTitle, currentArtist, currentData, currentDate))
            }
        }
        return arrayList

    }
}

If any one could help me in pointing out the Reason for Null Reference then I would be very thankful.


text:
Q: Probability of getting back to the starting point - Part 2 (unequal probabilities) Points A, B and C lie on a circle and are arranged in clockwise order. We roll a fair 6-sided die and perform any of the 3 following operations based on the roll of the die.

*

*Move Clockwise - if 1 or 2 shows up.

*Move Anti-Clockwise - if 3 or 4 shows up.

*Do not move - if 5 or 6 show up.

We take A as our starting point. We roll the dice 8 times and perform the operations based on the dice roll.
What is the probability that we end up getting back to A.
This is how A, B & C lie on the circle
I was able to solve this question with some help.
I wanted to add some twists to the problem statement and came up with assigning different probabilities to the operations -
We pick and choose the operations at random instaad of the dice roll -

 - There is a 2/6 chance of selecting the Clockwise Operation
 - There is a 3/6 chance of selecting the Anti-Clockwise Operation
 - There is a 1/6 chance of not moving at all (No Movement Operation)

Now, what is the probability that we end up getting back to A.
I was able to pinpoint all the valid states in the previously asked question.
As all the operations were equally likely before, we could use combinatorics to calculate all valid states and divide it by the total number of states to get the answer.
Here, I assigned probabilities to each of the valid states. For example -
P({2, 2, 4}) = $(2/6)^2 * (3/6)^2 * (1/6)^4$  - (as the events are independent)
and then added all of them.
However, I strongly believe my approach is incorrect. If I use the same approach on the unmodified version of the problem, I would reach the wrong answer i.e $15 * (1/3)^8$.
How should one approach this problem ? I believe this is related to Markov Chains but still unsure on the procedure.


text:
Q: Фильтрация полей gridview для связанных таблиц Есть GridView в которой надо отобразить данные из связанной модели.
Это можно сделать двумя способами: через объявление публичного виртуального поля в модели и манипулирование наименованиями и значениями этих полей в dataProvider и gridView. Так же есть способ не указывать виртуальное поле, а просто в методе search прописать $query->joinWith с необходимой моделью, а в фильтр добавить условие поиска по id, например:
public function search($params) {
    $query = User::find();
    $query->joinWith('user');

    ...
    $query->andFilterWhere(['ilike', Settings::tableName() . '.name', $this->settings_id])
    ...
}

и в гриде можно будет манипулировать через атрибут user.settings_id без проблем.
Первый вариант выглядит очень костыльно (хоть и описан в гайдах фреймворка).
А второй вариант не пройдет если будет несколько связанных моделей, например три или четыре
Есть несколько вопросов:

*

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

*Как можно сделать поиск и сортировку для связанных полей через одну или даже две, три таблицы не прибегая к виртуальным полям? Например firm → subdepartment → user → settings → name. Т.е. в gridView это будет как:
[
    'attribute' => 'Наименование настройки',
    'value' => 'subdepartment.user.setttings.name',
]

A: В смысле костыльно?! Создаете SerchModel которая наследуется от класса Modal, добавляете нужные поля для фильтра к примеру $settingName, пишете rulse для данного поля, джойните таблицу. В GridView в элемент ('attribute' => 'settingName') вписываете значения атрибута фильтра, в 'value' как у вас или через 'content' => function ($model) { return $model->user->setttings->name } связи можно оформлять также как и в вывод:
$query = User::find();
$query->joinWith('user.setttings'); // екземпляр User -> Setttings
$query->andFilterWhere(['LIKE', Settings::tableName() . '.name', $this->settingName])

Так работает фильтр в фреймовому, у фреймворка хватает других костелен, так что
на такую мелочь как фильтр можно закрыть глаза.