text:
Q: React-intl: Why need to define Messages using either  Component or defineMessagesAPI function I currently have the translated English and Japanese .json file in the format:
{
"en": [{
    "id": "Cancel",
    "defaultMessage": "Cancel"
}, {
    "id": "CommonTags",
    "defaultMessage": "Common Tags"
}]
"ja": [{
    "id": "Cancel",
    "defaultMessage": "キャンセル"
}, {
    "id": "CommonTags",
    "defaultMessage": "共通タグ"
    }]}

My question is, why do I need to define the messages now considering that I already have all of these generated and translated? I am simply like to access them in the following way but getting an error:
var messages_ja = require("../../../Resources/Resources.ja2.js.json");

class LocalizedApp extends React.Component {
props: any;
static propTypes: { intl: (object: any, key: string, componentName: string, ...rest: any[]) => Error | null; };
render() {
    return (...
       <h1>{this.props.intl.formatMessage({ id: messages_ja.Cancel })}</h1>);}}

I get the following error:
[React Intl] An id must be provided to format a message.
Repeating my question:

*

*Do I really need to incorporate the ecosystem for defining messages.
If so, why?

*Is it possible to simply access the strings based on
    locale from the json, without creating formattedMessages for them.

Thanks in advance.

A: Answer for question 1:
I'd say yes. You have to choose between using the declarative (e.g.: <FormattedMessage />) or the imperative api (e.g.: intl.formatMessage()).
Answer for question 2:
You could, but then why would you use react-intl then?
 (You could say that you only want to use its localization methods for date, numbers, percentage.. which would be ok, but IMHO you'd have much more effort to build your own solution other than using the lib.)
I always prefer to use the declarative API, and it's a good practice to have an ID and a default message. This default message that react-intl complains is actually to help you. It's a fallback for in case you missed one translation, it defaults to this message.
I recommend using the imperative api if you want to reuse labels or if you need to use them outside react components (from my experience, these were the only cases where it could be done). You can also use the babel-plugin-react-intl to auto-extract the labels from your application and make your life pretty much easy!


text:
Q: How do I avoid URL redirect when using SSLRequireSSL + ErrorDocument Ok, so I have an Apache host I'm working on (shared host) who has this in their root .htaccess file.:
Options -Indexes

SSLOptions +StrictRequire

ErrorDocument 401 "<!DOCTYPE html><html lang='en'> ... "
ErrorDocument 403 "<!DOCTYPE html><html lang='en'> ... "

SSLRequireSSL

So when a user tries to connect without SSL, they are prompted with the custom 403 html listed in the file. This occurs while keeping their old URL in the address bar so they can just add the https quickly.
However, for error page improvements, it is desired to load a php file from ./error and use that file in the definition for ErrorDocument. Now this is the kicker, if one just specifies the document directly...
ErrorDocument 403 /error/script.php

They will get another 403 or Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request. since the connection to the file is not under SSL. In an attempt to fix that, one may try this...
ErrorDocument 403 https://site.tld/error/script.php

But that redirects the client to https://site.tld/error/script.php which is UNDESIRED because they have to retype the url, and thus unable to just change the http to https.
So, I imagine I must do one of the following:

*

*EXCLUDE ./error from the SSL requirement with some .htaccess handling OR

*Build a REWRITE rule that detects the use of an error page, and doesn't rewrite the URL

I was unable to do either of this things yesterday. Perhaps neither of those options are viable, but I'm stuck at what to do.
How can I instruct .htaccess to allow http connections in ./error, or some other fix, so I still get my error pages, but the client still keeps their original URL?

A: Ok, here is my fix for now.
I have a folder structure as follows:
/ (web root)
|
|- .htaccess
|- index.php
|
|- error
|- dir1
|- dir2
~
|- dir(n - 1)
`- dir(n)

In (web root).htaccess I have the following:
Options -Indexes

ErrorDocument 403 /error/script.php

And within ANY subdir's folder (EXCEPT FOR /error/):
SSLOptions +StrictRequire
SSLRequireSSL

This allows me to load error pages without SSL, but still enforce it for every other folder. Is it pretty? No, I'd like to be able to control this from the root's .htaccess. But this is the only thing I have gotten to work so far.
If you can find a better solution, please post your work here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: QuickBlox Android NoResponse I'm developing a simple Android based chat application using QuickBlox. For that I have created a Quickblox Free account. Now sometimes when I try to login to the chat service I get following error. Any idea on this ?
03-15 15:58:37.589  15897-16016/com.ne.chatapp D/QBASDK﹕ Connecting to chat..
03-15 15:58:43.499  15897-16020/com.ne.chatapp D/SMACK﹕ SENT (0): <stream:stream to="chat.quickblox.com" xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams" version="1.0">
03-15 15:58:48.380  15897-16020/com.ne.chatapp D/SMACK﹕ SENT (0): </stream:stream>
03-15 15:58:48.390  15897-16016/com.ne.chatapp E/Login error1﹕ NoResponseException
03-15 15:58:48.420  15897-15897/com.ne.chatapp E/Login error﹕ NoResponseException

Java code for user authentication
public void AuthenticateUser(String Email,String Password,final Context context)
{
    loginActivity = (LoginActivity)context;
    applicationSingleton = (ApplicationSingleton)loginActivity.getApplication();

    QBChatService.setDebugEnabled(true);
    QBSettings.getInstance().fastConfigInit(GlobalData.APP_ID, GlobalData.AUTH_KEY, GlobalData.AUTH_SECRET);
    if (!QBChatService.isInitialized()) {
        QBChatService.init(context);
    }
    chatService = QBChatService.getInstance();

    final QBUser user = new QBUser();
    user.setLogin(Email);
    user.setPassword(Password);

    QBAuth.createSession(user, new QBEntityCallbackImpl<QBSession>() {
        @Override
        public void onSuccess(QBSession session, Bundle args) {
            user.setId(session.getUserId());
            applicationSingleton.setCurrentUser(user);

            if(chatService.isLoggedIn())
            {
                applicationSingleton.setLoginType(LoginType.UNKNOWN);
                loginActivity.onLoginSuccess();
                return;
            }

            chatService.login(user, new QBEntityCallbackImpl() {
                @Override
                public void onSuccess() {
                    try {
                        chatService.startAutoSendPresence(GlobalData.AUTO_PRESENCE_INTERVAL_IN_SECONDS);
                        applicationSingleton.setChatService(chatService);
                        applicationSingleton.setLoginType(LoginType.NORMAL);
                        loginActivity.onLoginSuccess();

                    } catch (SmackException.NotLoggedInException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(List errors) {
                    Log.e("Login error1", errors.get(0).toString());
                    loginActivity.onLoginError(errors);
                }
            });
        }

        @Override
        public void onError(List<String> errors) {
            Log.e("Session : ", errors.get(0).toString());
            loginActivity.onLoginError(errors);
        }
    });

}

A: Everything is ok. Perhaps it was related with problems on internet connection or XMPP servers.
How often does this problem reproduce\appear in app
Could you reproduce this bug by yourself, if you could please describe the steps to reproduce this bug below?

A: In timeout case, you can increase timeout by
final static int TIME_OUT=100000;
QBChatService.setDefaultPacketReplyTimeout(TIME_OUT);


text:
Q: How to take input from user while using CountDownTimer in android Here at CountDownTimer below, I want to have a user input value in milli seconds instead of pre loaded value of 30000.
Please anybody help in this case. I am not able to figure out myself.
public class MainActivity extends AppCompatActivity {

    TextView mTextField;
    EditText mEditText;
    Button mButton;

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

        mTextField = (TextView) findViewById(R.id.timerView);
        mButton = (Button) findViewById(R.id.startButton);

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Turning of the button until the timer finishes
                mButton.setEnabled(false);
                mButton.setClickable(false);

                new CountDownTimer(30000, 1000) { // Here I want to have a user input value in milli seconds instead of pre loaded value of 30000

                    public void onTick(long millisUntilFinished) {
                        mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
                    }

                    public void onFinish() {
                        mTextField.setText("done!");
                        // Turning on the button when the timer has finnished
                        mButton.setEnabled(true);
                        mButton.setClickable(true);
                    }
                }.start();

            }
        });

    }

}**strong text**

A: It is very simple, give any option for user input like an edit text and then pass those values as parameters in the CountDownTimer.
// 3000 and 200 will be input from user
long millisinFuture= 3000;
long delayTime=200;

new CountDownTimer(millisinFuture, delayTime) { // Here I want to have a user input value in milli seconds instead of pre loaded value of 30000

                public void onTick(long millisUntilFinished) {
                    mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
                }

                public void onFinish() {
                    mTextField.setText("done!");
                    // Turning on the button when the timer has finnished
                    mButton.setEnabled(true);
                    mButton.setClickable(true);
                }
            }.start();


text:
Q: what is the difference between host and slot in mulicore-multiprocessor environment? i know that resource manager(R.M.) conveys slot information to openmpi but

*

*how R.M. determines number of slots in a multi-core processor(is 1 core == 1 slot always?) and,

*if i run a.out on a 4 core processor, then what is the difference between:

*

*myshell$ mpirun --host n1,n1,n1,n1,n1 ./a.out

*myshell$ mpirun -np 5 --host n1 ./a.out

I mean in which case ,am I "oversubscribing" the node ?

A: When it comes to resource managers, e.g. SLURM, LSF, SGE/OGE, Torque, etc., the mapping between slots and cores is entirely left to the system administrator. It depends usually on the nature of the jobs that are to be executed on the nodes. In HPC, where most tasks are CPU-bound, the usual mapping is one slot per core (or per hardware thread). In data processing, where most tasks are I/O bound, having more slots than cores could be more beneficial.
The same applies to launching MPI processes. When the hosts are described in the hostfile, the number of slots per host does not necessarily have to match the hardware configuration. Again, it depends on the nature of the MPI job. Slot information is usually used to control how ranks are to be distributed. For example, the default policy in Open MPI is to fill the provided slots on the first host and then move to the next one. Once all hosts are filled, if more ranks remain to be launched, the process starts again from the first node in the host list.
The end effect of --host n1,n1,n1,n1,n1 and --host n1 -np 5 is the same: 5 ranks are launched on host n1. The difference is how Open MPI interprets it.

*

*mpiexec --host n1,n1,n1,n1,n1 ./a.out tells Open MPI that there are 5 slots on host n1. Since the -np parameter is omitted, mpiexec starts one rank per defined slot, therefore 5 ranks are started at host n1.

*mpiexec --host n1 -np 5 ./a.out tells Open MPI that there is a single slot on host n1. One rank is launched on n1. Since no more slots are left, mpiexec starts again from the first defined slot, i.e. launches another rank on host n1. This is repeated until all 5 ranks are launched on n1 and results in it being oversubscribed.

Note that the node is oversubscribed only from the point of view of the MPI library - one slot was provided on n1, but it had to start 5 ranks there. This has nothing to do with oversubscribing the node itself, i.e. there could be much more CPU free cores than 5.
When the host list is provided by the resource manager, oversubscribing the nodes is a very bad idea, especially since some or all nodes might be shared with other jobs. In that case it is recommended that the --nooversubscribe option is used in order to prevent mpiexec from launching more ranks than slots granted. Note though that there are legitimate cases of oversubscription, e.g. when the nodes are granted exclusively (no sharing with other jobs) and the MPI job is I/O intensive.

A: You can also specify number of available slots on each host:
mpirun -np 5 --host n1:2,n2:3 ./a.out

This will run 2 processes on n1 and 3 on n2.


text:
Q: Placeholder For Dynamically Created Textbox I am new to winForms. This is the first time I am trying creating a textbox dynamically. It looks there is no problem creating it, but I have problem creating-using  my own placeholder. After some search, I am still stuck and got no progress, thanks for any help.
public partial class Form1 : Form
    {
        Button buttonC=new Button();
        TextBox txtOrder = new TextBox();
        public Form1()
        {

            InitializeComponent();

            txtOrder.Top = 100;
            txtOrder.Left = 300;
            this.Controls.Add(txtOrder);

         }

        private void txtOrder_Enter(object sender, EventArgs e)
        {
            if (txtOrder.Text == "my_placeholder_text")
            {
                txtOrder.Text = "";
                txtOrder.ForeColor = Color.Black;
            }
        }

        private void txtOrder_Leave(object sender, EventArgs e)
        {
            if (txtOrder.Text == "")
            {
                txtOrder.Text = "my_placeholder_text";
                txtOrder.ForeColor = Color.LightBlue;
            }
        }


text:
Q: angular 4 nested formArray Cannot find control with path: 'segmentRows3 -> 1 -> segmentId3' I cannot push to an array.
I have a segment(id, time) that can have one or several people (role, infos). The field are generated dynamically. On load the page shows the fields (see image below).

When try to add a segment I get error : ERROR TypeError: Cannot find control with path: 'segmentRows3 -> 1 -> segmentId3'
Here is code from the .ts file:
addSegment() {
let segmentRows3 = this.mySummaryForm.get('segmentRows3') as FormArray;
    segmentRows3.push(this.fb.array([
        this.fb.group({
            segmentTime3: '',
            segmentId3: '',
            personRows3: this.fb.array([
            this.fb.group({
               personR3: '',
               personI3: ''
              })
            ])
        })
      ]));
  }

  segmentRows3: this.fb.array([
    this.fb.group({
        segmentId3: '',
        segmentTime3: '',
        personRows3: this.fb.array([
        this.fb.group({
           personR3: '',
           personI3: ''
          })
        ])
    })
  ]),

The .html code

New segment

   {{i+1}}
        Segment ID
            <select formControlName="segmentId3" placeholder="pick" type="text" id="segmentId3" class="form-control" [(ngModel)]="levelNumSegment3" (ngModelChange)="toNumberSegment3()">
                <option *ngFor="let level of segmentId" [value]="level.num">{{level.name}}</option>
            </select>

        Segment time
            <input formControlName="segmentTime3" type="text" id="segmentTime3" class="form-control" placeholder="select a time" (ngModelChange)="onChange($event)">

        <button type="button" (click)="addPerson(i)" class="btn btn-info">Add a person</button>

   {{j+1}}
                        person Role
                        <input formControlName="personR3" [typeahead]="personRole" [typeaheadOptionsLimit]="10" [typeaheadMinLength]="0" type="text" id="personR3" class="form-control" placeholder="select a role" (ngModelChange)="onChange($event)" >

                        Person infos
                        <input formControlName="personI3" [typeahead]="states" [typeaheadOptionsLimit]="10" [typeaheadMinLength]="0" type="text" id="personI3" class="form-control" placeholder="select infos" (ngModelChange)="onChange($event)" >

                        Remove

<button type="button" (click)="addSegment()" class="btn btn-primary">Add a segment</button>

When i try to add it adds the segment(id, time) but not the person (role, infos) unlike on load (image below), and throws error : ERROR TypeError: Cannot find control with path: 'segmentRows3 -> 1 -> segmentId3'   . Why?

A: You're adding FormArray to segmentRow3 array whilst your template expects only FormGroup:
segmentRows3.push(this.fb.array([
                  ^^^^^^^^^^^^^^
                       why?
        this.fb.group({

So, try changing it to:
segmentRows3.push(
  this.fb.group({
    segmentTime3: '',
    segmentId3: '',
    personRows3: this.fb.array([
      this.fb.group({
        personR3: '',
        personI3: ''
      })
    ])
  })
);


text:
Q: Converting a string containing year and week number to datetime in Pandas I have a column in a Pandas dataframe that contains the year and the week number (1 up to 52) in one string in this format: '2017_03'  (meaning 3d week of year 2017).
I want to convert the column to datetime and I am using the pd.to_datetime() function.  However I get an exception:
pd.to_datetime('2017_01',format = '%Y_%W')
ValueError: Cannot use '%W' or '%U' without day and year

On the other hand the strftime documentation mentions that:

I am not sure what I am doing wrong.

A: You need also define start day:
a = pd.to_datetime('2017_01_0',format = '%Y_%W_%w')
print (a)
2017-01-08 00:00:00

a = pd.to_datetime('2017_01_1',format = '%Y_%W_%w')
print (a)
2017-01-02 00:00:00

a = pd.to_datetime('2017_01_2',format = '%Y_%W_%w')
print (a)
2017-01-03 00:00:00


text:
Q: How to do I get object keys by a pattern? I have an object with named keys:
var names = {
  "Peter Pan": {...},
  "Peter Parker": {...},
  "Tony Stark": {...},
  ...
}

Is there a way to get all keys by a pattern eg. all keys having Peter in it?
The case is that I want to have all the filtered keys in an array eg:
var filteredNames: [
  "Peter Pan",
  "Peter Parker",
  ...
]

A: var filteredNames = Object.keys(names).filter((name) => /Peter/.test(name));

A: If you want it case sensitive:
var filteredNames = [];

for( name in names ) {
    if( name.indexOf( "Peter" ) > -1 ) {
        filteredNames.push( name );
    }
}

If not:
var filteredNames = [];

for( name in names ) {
    if( /peter/gi.test( name ) ) {
        filteredNames.push( name );
    }
}

A: You can easily do it by looping over the keys yourself:
var filtered_keys = function(obj, filter) {
  var key, keys = [];
  for (key in obj) {
    if (obj.hasOwnProperty(key) && filter.test(key)) {
      keys.push(key);
    }
  }
  return keys;
}
// example:
var filteredNames = filtered_keys(names, /Peter/); // second parameter is a javascript regex object, so for exemple for case insensitive you would do /Peter/i

ES6
let filtered_keys = (obj, filter) => {
  let key, keys = []
  for (key in obj)
    if (obj.hasOwnProperty(key) && filter.test(key))
      keys.push(key)
  return keys
}

// example:
let filteredNames = filtered_keys(names, /Peter/)

A: You could extend the JavaScript Array prototype, like so:
Array.prototype.regex_search = function(pattern) {
  var returns = [];
  for(var i = 0; i < this.length; i++) {
    if(this[i].match(pattern) {
      returns.push(i);
    }
  }
  if(returns.length) {
    return returns;
  } else {
    return false;
  }
}

Now I haven't actually tested this code but this would give all arrays you create in JavaScript a method .regex_search which takes an argument 'pattern'. This will either return false when no matches are found or an array of indices when elements match.
You could then iterate over this array and take those indices from the original array.


text:
Q: Python Recursion List Output returns last element multiple times I'm trying to create a list of all possible combinations of a list "places", that fulfil a condition. Unfortunately my function returns only the result of the last recursion and that one several times. I can't figure out what I'm doing wrong.
Here's what I have so far:
places = [0,1,2,3,4] #these are the values that the combinations are made of
distance = [1,2,1,2,1] #these are the distances of each place

def get_combinations(combi, i):

    # go a level higher and count to the next item
    if i == 5:
        i = places.index(combi[-1])
        combi.pop()
        return get_combinations(combi, i+1)

    # add place to the current list
    combi.append(places[i])

    d = sum(distance[i] for i in combi)

    if d <= max_d:
        print(combi) #This is what I want in the final list

        if combi == [places[4]]: # this is the base case
            return combi
        else:
            return combi + get_combinations(combi, i+1)

    else:
        if combi == [places[4]]: # this is the base case
            return []
        else:
            combi.pop()
            return get_combinations(combi, i+1)

combi = []
x = 0
max_d = 3

result = get_combinations(combi, x)
print("List of all combinations: ", result)

[0]
[0, 1]
[0, 2]
[0, 2, 4]
[0, 3]
[0, 4]
[1]
[1, 2]
[1, 4]
[2]
[2, 3]
[2, 4]
[3]
[3, 4]
[4]
List of all combinations:  [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]

Based on the print output I can tell that the function is technically working the way I want it to.
But the function output should look like this: [[0],[0, 1],[0, 2],[0, 2, 4],[0, 3],[0, 4],[1],[1, 2],[1, 4],[2],[2, 3],[2, 4],[3],[3, 4],[4]]
What is wrong with my return statements or is there an easier way to do this?

A: The main issue is that combi is returned in return combi, but is also mutated later on with calls to pop and append... which still affect the list that was returned (since it is the same list).
To avoid that, make sure to never return combi itself, but a copy.
Secondly, you'll want to return a list of lists and not concatenate combinations with combi + into one long list. This should be a nested list.
So change:
        if combi == [places[4]]: # this is the base case
            return combi
        else:
            return combi + get_combinations(combi, i+1)

to:
        if combi == [places[4]]: # this is the base case
            return [combi[:]]
        else:
            return [combi[:]] + get_combinations(combi, i+1)


text:
Q: What does the mteTrigger option in snmpd's SNMPDOPTS do?

I am trying to determine why a number of sites are recommending the mteTrigger,mteTriggerConf optons below be placed as options in SNMPDOPTS for snmpd's /etc/default/snmpd (Ubuntu).

SNMPDOPTS='-Lsd -Lf /dev/null -u snmp -g snmp -I -smux,mteTrigger,mteTriggerConf -p /var/run/snmpd.pid'

What is the benefit of adding these options as apposed to leaving them out?

A: Although I'm not entirely sure if Stack Overflow is the best place for this question, I'll try to answer it.
First note that the part -I -smux,mteTrigger,mteTriggerConf is one option. The -I option specifies which modules should (or should not) be initialized when the agent starts up. The '-' before the second part means that the specified modules should not be started.
My guess is that smux is disabled because it has been deprecated by the AgentX protocol (source), and the mteTrigger and mteTriggerConf modules because they don't work without non-free MIBs (source).


text:
Q: After compiling ans installing wxPython Robot IDE cannot see it I have just compiled wxPython 2.8.12.1 downloaded from sourceforge, with the following log of make install (this is just the install part). I have ran make in the main dir and then make install (with this output).
/usr/bin/install -c -d /usr/local/lib
/usr/bin/install -c -m 644 /root/packages/wxPython/wxPython-src-2.8.12.1/lib/libwx_base-2.8.so /usr/local/lib
/usr/bin/install -c /root/packages/wxPython/wxPython-src-2.8.12.1/lib/libwx_base-2.8.so.0.8.0 /usr/local/lib
(cd /usr/local/lib ; rm -f libwx_base-2.8.so libwx_base-2.8.so.0; ln -s libwx_base-2.8.so.0.8.0 libwx_base-2.8.so.0; ln -s libwx_base-2.8.so.0 libwx_base-2.8.so)
/usr/bin/install -c -d /usr/local/lib
/usr/bin/install -c -m 644 /root/packages/wxPython/wxPython-src-2.8.12.1/lib/libwx_base_net-2.8.so /usr/local/lib
/usr/bin/install -c /root/packages/wxPython/wxPython-src-2.8.12.1/lib/libwx_base_net-2.8.so.0.8.0 /usr/local/lib
(cd /usr/local/lib ; rm -f libwx_base_net-2.8.so libwx_base_net-2.8.so.0; ln -s libwx_base_net-2.8.so.0.8.0 libwx_base_net-2.8.so.0; ln -s libwx_base_net-2.8.so.0 libwx_base_net-2.8.so)
/usr/bin/install -c -d /usr/local/lib
/usr/bin/install -c -m 644 /root/packages/wxPython/wxPython-src-2.8.12.1/lib/libwx_gtk2_core-2.8.so /usr/local/lib
/usr/bin/install -c /root/packages/wxPython/wxPython-src-2.8.12.1/lib/libwx_gtk2_core-2.8.so.0.8.0 /usr/local/lib
(cd /usr/local/lib ; rm -f libwx_gtk2_core-2.8.so libwx_gtk2_core-2.8.so.0; ln -s libwx_gtk2_core-2.8.so.0.8.0 libwx_gtk2_core-2.8.so.0; ln -s libwx_gtk2_core-2.8.so.0 libwx_gtk2_core-2.8.so)
/usr/bin/install -c -d /usr/local/lib
/usr/bin/install -c -m 644 /root/packages/wxPython/wxPython-src-2.8.12.1/lib/libwx_gtk2_adv-2.8.so /usr/local/lib
/usr/bin/install -c /root/packages/wxPython/wxPython-src-2.8.12.1/lib/libwx_gtk2_adv-2.8.so.0.8.0 /usr/local/lib
(cd /usr/local/lib ; rm -f libwx_gtk2_adv-2.8.so libwx_gtk2_adv-2.8.so.0; ln -s libwx_gtk2_adv-2.8.so.0.8.0 libwx_gtk2_adv-2.8.so.0; ln -s libwx_gtk2_adv-2.8.so.0 libwx_gtk2_adv-2.8.so)
/usr/bin/install -c -d /usr/local/lib
/usr/bin/install -c -m 644 /root/packages/wxPython/wxPython-src-2.8.12.1/lib/libwx_gtk2_html-2.8.so /usr/local/lib
/usr/bin/install -c /root/packages/wxPython/wxPython-src-2.8.12.1/lib/libwx_gtk2_html-2.8.so.0.8.0 /usr/local/lib
(cd /usr/local/lib ; rm -f libwx_gtk2_html-2.8.so libwx_gtk2_html-2.8.so.0; ln -s libwx_gtk2_html-2.8.so.0.8.0 libwx_gtk2_html-2.8.so.0; ln -s libwx_gtk2_html-2.8.so.0 libwx_gtk2_html-2.8.so)
/usr/bin/install -c -d /usr/local/lib
/usr/bin/install -c -m 644 /root/packages/wxPython/wxPython-src-2.8.12.1/lib/libwx_gtk2_qa-2.8.so /usr/local/lib
/usr/bin/install -c /root/packages/wxPython/wxPython-src-2.8.12.1/lib/libwx_gtk2_qa-2.8.so.0.8.0 /usr/local/lib
(cd /usr/local/lib ; rm -f libwx_gtk2_qa-2.8.so libwx_gtk2_qa-2.8.so.0; ln -s libwx_gtk2_qa-2.8.so.0.8.0 libwx_gtk2_qa-2.8.so.0; ln -s libwx_gtk2_qa-2.8.so.0 libwx_gtk2_qa-2.8.so)
/usr/bin/install -c -d /usr/local/lib
/usr/bin/install -c -m 644 /root/packages/wxPython/wxPython-src-2.8.12.1/lib/libwx_base_xml-2.8.so /usr/local/lib
/usr/bin/install -c /root/packages/wxPython/wxPython-src-2.8.12.1/lib/libwx_base_xml-2.8.so.0.8.0 /usr/local/lib
(cd /usr/local/lib ; rm -f libwx_base_xml-2.8.so libwx_base_xml-2.8.so.0; ln -s libwx_base_xml-2.8.so.0.8.0 libwx_base_xml-2.8.so.0; ln -s libwx_base_xml-2.8.so.0 libwx_base_xml-2.8.so)
/usr/bin/install -c -d /usr/local/lib
/usr/bin/install -c -m 644 /root/packages/wxPython/wxPython-src-2.8.12.1/lib/libwx_gtk2_xrc-2.8.so /usr/local/lib
/usr/bin/install -c /root/packages/wxPython/wxPython-src-2.8.12.1/lib/libwx_gtk2_xrc-2.8.so.0.8.0 /usr/local/lib
(cd /usr/local/lib ; rm -f libwx_gtk2_xrc-2.8.so libwx_gtk2_xrc-2.8.so.0; ln -s libwx_gtk2_xrc-2.8.so.0.8.0 libwx_gtk2_xrc-2.8.so.0; ln -s libwx_gtk2_xrc-2.8.so.0 libwx_gtk2_xrc-2.8.so)
/usr/bin/install -c -d /usr/local/lib
/usr/bin/install -c -m 644 /root/packages/wxPython/wxPython-src-2.8.12.1/lib/libwx_gtk2_aui-2.8.so /usr/local/lib
/usr/bin/install -c /root/packages/wxPython/wxPython-src-2.8.12.1/lib/libwx_gtk2_aui-2.8.so.0.8.0 /usr/local/lib
(cd /usr/local/lib ; rm -f libwx_gtk2_aui-2.8.so libwx_gtk2_aui-2.8.so.0; ln -s libwx_gtk2_aui-2.8.so.0.8.0 libwx_gtk2_aui-2.8.so.0; ln -s libwx_gtk2_aui-2.8.so.0 libwx_gtk2_aui-2.8.so)
/usr/bin/install -c -d /usr/local/lib
/usr/bin/install -c -m 644 /root/packages/wxPython/wxPython-src-2.8.12.1/lib/libwx_gtk2_richtext-2.8.so /usr/local/lib
/usr/bin/install -c /root/packages/wxPython/wxPython-src-2.8.12.1/lib/libwx_gtk2_richtext-2.8.so.0.8.0 /usr/local/lib
(cd /usr/local/lib ; rm -f libwx_gtk2_richtext-2.8.so libwx_gtk2_richtext-2.8.so.0; ln -s libwx_gtk2_richtext-2.8.so.0.8.0 libwx_gtk2_richtext-2.8.so.0; ln -s libwx_gtk2_richtext-2.8.so.0 libwx_gtk2_richtext-2.8.so)
(if test -d utils/wxrc ; then cd utils/wxrc && make all ; fi)
make[1]: Entering directory `/root/packages/wxPython/wxPython-src-2.8.12.1/utils/wxrc'
make[1]: Nothing to be done for `all'.
make[1]: Leaving directory `/root/packages/wxPython/wxPython-src-2.8.12.1/utils/wxrc'
(if test -d utils/wxrc ; then cd utils/wxrc && make install ; fi)
make[1]: Entering directory `/root/packages/wxPython/wxPython-src-2.8.12.1/utils/wxrc'
/usr/bin/install -c -d /usr/local/bin
/usr/bin/install -c wxrc /usr/local/bin
rm -f /usr/local/bin/wxrc /usr/local/bin/wxrc-2.8
/usr/bin/install -c wxrc /usr/local/bin
mv -f /usr/local/bin/wxrc /usr/local/bin/wxrc-2.8
(cd /usr/local/bin && ln -s wxrc-2.8 wxrc)
make[1]: Leaving directory `/root/packages/wxPython/wxPython-src-2.8.12.1/utils/wxrc'
/usr/bin/install -c -d /usr/local/bin
/usr/bin/install -c -d /usr/local/lib/wx/config
/usr/bin/install -c lib/wx/config/gtk2-ansi-release-2.8 /usr/local/lib/wx/config
(cd /usr/local/bin && rm -f wx-config && ln -s /usr/local/lib/wx/config/gtk2-ansi-release-2.8 wx-config)
/usr/bin/install -c -d /usr/local/share/locale
for l in ca cs da de el es fi fr hu id it ja nl pl ru sl sv tr uk zh zh_CN zh_TW ; do \
  /usr/bin/install -c -d /usr/local/share/locale/$l ; \
  /usr/bin/install -c -d /usr/local/share/locale/$l/LC_MESSAGES ; \
  if test -f ./locale/$l.mo ; then \
  /usr/bin/install -c -m 644 ./locale/$l.mo /usr/local/share/locale/$l/LC_MESSAGES/wxstd.mo ; \
  fi ; \
  done
/usr/bin/install -c -d /usr/local/share/locale
for l in it ; do \
  /usr/bin/install -c -d /usr/local/share/locale/$l ; \
  /usr/bin/install -c -d /usr/local/share/locale/$l/LC_MESSAGES ; \
  if test -f ./locale/msw/$l.mo ; then \
  /usr/bin/install -c -m 644 ./locale/msw/$l.mo /usr/local/share/locale/$l/LC_MESSAGES/wxmsw.mo ; \
  fi ; \
  done
/usr/bin/install -c -d /usr/local/share/aclocal
(cd . ; /usr/bin/install -c -m 644  wxwin.m4 /usr/local/share/aclocal)
/usr/bin/install -c -d /usr/local/share/bakefile/presets
(cd ./build/bakefiles/wxpresets/presets ; /usr/bin/install -c -m 644  wx.bkl wx_unix.bkl wx_win32.bkl /usr/local/share/bakefile/presets)
/usr/bin/install -c -d /usr/local/lib/wx/include/gtk2-ansi-release-2.8/wx
for f in setup.h ; do \
  if test ! -d /usr/local/lib/wx/include/gtk2-ansi-release-2.8/wx/`dirname $f` ; then \
  /usr/bin/install -c -d /usr/local/lib/wx/include/gtk2-ansi-release-2.8/wx/`dirname $f`; \
  fi; \
  /usr/bin/install -c -m 644 ./lib/wx/include/gtk2-ansi-release-2.8/wx/$f /usr/local/lib/wx/include/gtk2-ansi-release-2.8/wx/$f; \
  done
/usr/bin/install -c -d /usr/local/include/wx-2.8

After that I have downloaded robotframework-ide from here https://pypi.python.org/pypi/robotframework-ride
and ran :
python setup.py install

with the following output: http://pastebin.com/TqiBcs78
...
byte-compiling /usr/local/lib/python2.7/site-packages/robotide/action/actioninfo.py to actioninfo.pyc
byte-compiling /usr/local/lib/python2.7/site-packages/robotide/action/shortcut.py to shortcut.pyc
running install_egg_info
running egg_info
writing requirements to src/robotframework_ride.egg-info/requires.txt
writing src/robotframework_ride.egg-info/PKG-INFO
writing top-level names to src/robotframework_ride.egg-info/top_level.txt
writing dependency_links to src/robotframework_ride.egg-info/dependency_links.txt
reading manifest file 'src/robotframework_ride.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
writing manifest file 'src/robotframework_ride.egg-info/SOURCES.txt'
removing '/usr/local/lib/python2.7/site-packages/robotframework_ride-1.3-py2.7.egg-info' (and everything under it)
Copying src/robotframework_ride.egg-info to /usr/local/lib/python2.7/site-packages/robotframework_ride-1.3-py2.7.egg-info
running install_scripts
copying build/scripts-2.7/ride_postinstall.py -> /usr/local/bin
copying build/scripts-2.7/ride.py -> /usr/local/bin
changing mode of /usr/local/bin/ride_postinstall.py to 755
changing mode of /usr/local/bin/ride.py to 755
No wxPython installation detected!

Please ensure that you have wxPython installed before running RIDE.
You can obtain wxPython 2.8.12.1 from http://sourceforge.net/projects/wxpython/files/wxPython/2.8.12.1/

why can't it see my wxPython ? I am using Red Hat 6

A: It is likely to be one of two problems:

*

*The package didn't install correctly and needs to be reinstalled

*You have multiple Python versions installed and the package installed against one of the others.

If it's the latter, you can usually fix it by reinstalling using the appropriate Python:
/path/to/python27 setup.py install


text:
Q: What is the best way to ignore columns while reading a CSV in C#? So I read a large CSV file and it might look something like
"Intelligent Mail barcode","Sack and Pa","Opt. Endorsement Line","Label ","NAME","COMPANY","DELADDR","CITY","ST","ZIP"
"xxxxxxxxxxxxxxxxxxxxxxxxx","T1  P1","******AUTO**MIXED AADC 403","xxxx","xxxxxxxx","xxxxxxxxxxxxxxxx","xxxxxxxx","xxxxx","xxxx","xxxxx"
"xxxxxxxxxxxxxxxxxxxxxxxxx","T1  P1","******AUTO**MIXED AADC 403","xxxx","xxxxxxxxxx","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","xxxxxx","xxxxx","xx","xxxxx"

I want to be able to remove the first 4 columns in this case. So Intelligent Mail, Sack and Pa, Opt. Endorse, and Label1 would be ignored and the data associated with them would also be ignored or blank.
So the output would be like
"NAME","COMPANY","DELADDR","CITY","ST","ZIP"
"xxxxxxxx","xxxxxxxxxxxxxxxx","xxxxxxxx","xxxxx","xxxx","xxxxx"
"xxxxxxxxxx","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","xxxxxx","xxxxx","xx","xxxxx"

How can I accomplish this? Looking for the easiest way to do this.
Here is how I read the CSV currently:
        using (StreamReader reader = new StreamReader(fileSaveLocation))
        {
            string line;
            header = reader.ReadLine();

            while ((line = reader.ReadLine()) != null)
            {
                sb.Append(line);
                sb.Append(Environment.NewLine);
            }
        }


text:
Q: celery excess argument [True, False] subtask, callback, How do I remove them? How to ignore arguments allowed [True, False] when you pass an argument ((status_id)) to function success ()?
status_id=11

callback = success.subtask((status_id,))
chord(results)(callback)

@app.task(routing_key="message_status", queue="message_status")

def success(status_id):

    try:
        global db
        db = connection()
        db.query(MessageTask).filter_by(id=status_id).update({
            'status': 'success',
            'date': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        })

        db.commit()
        return True
    except Exception as e:
        print(e)

status_id comes in result of [[True, False], '11']. How do I remove them?


text:
Q: Strawberry Perl v5.30.0 not able to install Tcl (Windows 10) I downloaded and installed strawberry-perl-5.30.0.1-64bit.msi from strawberryperl.com on my Windows 10 and tried to install Tcl module using cpan, but it fails for missing tclsh. What could be the problem?
C:\Strawberry>cpan Tcl
Loading internal logger. Log::Log4perl recommended for better logging
CPAN: CPAN::SQLite loaded ok (v0.217)
Database was generated on Thu, 24 Oct 2019 12:40:15 GMT
Running install for module 'Tcl'
CPAN: Digest::SHA loaded ok (v6.02)
CPAN: Compress::Zlib loaded ok (v2.086)
Checksum for C:\STRAWB~1\cpan\sources\authors\id\V\VK\VKON\Tcl-1.27.tar.gz ok
CPAN: Archive::Tar loaded ok (v2.32)
CPAN: YAML::XS loaded ok (v0.78)
CPAN: CPAN::Meta::Requirements loaded ok (v2.140)
CPAN: Parse::CPAN::Meta loaded ok (v2.150010)
CPAN: CPAN::Meta loaded ok (v2.150010)
CPAN: Module::CoreList loaded ok (v5.20190522)
Configuring V/VK/VKON/Tcl-1.27.tar.gz with Makefile.PL
'tclsh' is not recognized as an internal or external command,
operable program or batch file.
error starting tclsh: $?=256; $!=
No 'Makefile' created  VKON/Tcl-1.27.tar.gz
  C:\Strawberry\perl\bin\perl.exe Makefile.PL -- NOT OK
Stopping: 'install' failed for 'Tcl'.

C:\Strawberry>dir C:\Strawberry\cpan\build\Tcl-1.27-0
 Volume in drive C is OSDisk
 Volume Serial Number is BCC0-703E

 Directory of C:\Strawberry\cpan\build\Tcl-1.27-0

25.10.2019  13.05    <DIR>          .
25.10.2019  13.05    <DIR>          ..
14.07.2018  11.00             5 207 Changes
22.08.2018  11.21            10 139 Makefile.PL
22.08.2018  11.45             1 723 MANIFEST
22.08.2018  11.45             1 140 META.json
22.08.2018  11.44               617 META.yml
14.07.2018  20.26             1 246 README
25.10.2019  13.05    <DIR>          t
25.10.2019  13.05    <DIR>          tcl-core
22.08.2018  11.43            43 540 Tcl.pm
22.08.2018  10.57            46 049 Tcl.xs
16.06.2018  15.18               439 tclcfg.tcl
16.06.2018  15.18                48 typemap
              10 File(s)        110 148 bytes
               4 Dir(s)  316 953 681 920 bytes free

A: You can build the missing dependency tclsh by downloading the source distribution from https://prdownloads.sourceforge.net/tcl/tcl8420-src.zip. To compile the source you need a C compiler. I tried the community edition of visual studio:
https://visualstudio.microsoft.com/vs/

*

*Click download community edition..

*Then choose what to install

*Then click "Install"
After installation, go to menu "Tools->Command Line->Developer Command Prompt" and run
nmake -f makefile.vc

from the win sub folder of the extracted Tcl source distribution (on my computer it was located at C:\Users\Bruker\tcl\tcl8.4.20\win)
The above nmake command creates a new folder Release_VC13 with an executable file tclsh84.exe. Note that the name of the executable is not tclsh.exe.
Now add the folder of the executable to the system PATH environment variable:
C:\Users\Bruker\tcl\tcl8.4.20\win\Release_VC13, then close the command prompt and reopen again to refresh the path settings.
Try type tclsh84, and you should get a tcl shell command prompt with a leading % prompt. Then type exit to exit the tcl shell.
The next problem is to install the Tcl module using Strawberry perl. Trying first to run:
> cpan Tcl
[...]
'tclsh' is not recognized as an internal or external command,
operable program or batch file.
error starting tclsh: $?=256; $!=
No 'Makefile' created  VKON/Tcl-1.27.tar.gz
  C:\Strawberry\perl\bin\perl.exe Makefile.PL -- NOT OK
Stopping: 'install' failed for 'Tcl'.

The problem is that the executable is not called tclsh but tclsh84 (see above).
The next thing I did was to download the source distribution for the Tcl module:
> cpan -g Tcl

Then extracted the downloaded file Tcl-1.27.tar.gz and changed to the source distribution directory. By inspecting the Makefile.PL I found that the Makefile.PL took a command line argument --tclsh that gave the name of the tcl shell command. So I tried:
> perl Makefile.PL --tclsh=tclsh84

and this worked fine now. Then I tried to compile with gmake (which comes with the Strawberry Perl distribution):
> gmake

This also worked, but running gmake test failed, and also installing and testing the module:
> gmake install
> perl -MTcl -e1
failed dlopen(C:/Users/Bruker/tcl/tcl8.4.20/win/Release_VC13/tcl84.dll,...);
failed dlopen(./tcl84.dll,...);
failed dlopen(tcl84.dll,...);
trying dlopen(tcl89.dll,...)
trying dlopen(tcl88.dll,...)
trying dlopen(tcl87.dll,...)
trying dlopen(tcl86.dll,...)
trying dlopen(tcl85.dll,...)
trying dlopen(tcl84.dll,...)
trying dlopen(tcl83.dll,...)
trying dlopen(tcl82.dll,...)
trying dlopen(tcl81.dll,...)
trying dlopen(tcl80.dll,...)
failed all posible tcl vers 8.x from 9 down to 0 at C:/Strawberry/perl/lib/XSLoader.pm line 111.
Failed to load Tcl dll! at C:/Strawberry/perl/lib/XSLoader.pm line 111.
Unable to initialize Tcl at C:/Strawberry/perl/lib/XSLoader.pm line 111.
Compilation failed in require.
BEGIN failed--compilation aborted.

I plan to come back to this problem later and investigate further.


text:
Q: How to run a service of installed app in devices programatically I have a function to get running services:
public ArrayList<String> getRunningServices() {

    ActivityManager activityMg = (ActivityManager)context.getSystemService(context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningServiceInfo> serviceList = activityMg.getRunningServices(100);
    ArrayList<String> serviceName = new ArrayList<String>();

 for (int i=0; i<serviceList.size(); i++) {
       ActivityManager.RunningServiceInfo currentService = serviceList.get(i);
       boolean serviceNam = currentService.started;
       if (serviceNam == true) {
           serviceName.add(currentService.service.getPackageName());
    }

     }

    return serviceName;

}

Now I want to run one of these services if it is stopped.
To run an installed app I have to use intent like this code:
      Intent intent = context.getPackageManager().getLaunchIntentForPackage(nameOfPakage);
    context.startActivity(intent);

But I want to just run a service of this app or another one.
I have a String name of package of app and i want start its service.
Is it possible?

A: Hi there below is to start a service from another application.
Intent intent = new Intent();
String pkg = currentService.service.getPackageName();
String cls = currentService.service.getPackageName() + "." + currentService.service.getClassName();
intent.setComponent(new ComponentName(pkg, cls));
startService(intent);


text:
Q: Understanding the output of an arithmatic expression I have a java class as follows:
class A{
    public static void main(String[] args){
       int a=10;
       a*=a++ +a;
       System.out.println(a);
    }
}

Output:210

In my opinion the output should be 231 calculated as follows:
a*=10+11;
a*=21;
a=a*21;
a=11*21;
a= 231;

Can anyone please explain me where am I wrong and why?

A: In any statement of the type:
x *= y;

The initial value of the LHS is evaluated before the RHS. So your statement:
a *= a++ + a;

Is equivalent to:
a = a * (a++ + a);

Which sets a to the value 10 * (10 + 11) => 210.
If you're particularly interested in the formal specification related to this point you can find it here which contains the rule "If the operator is a compound-assignment operator (§15.26.2), then evaluation of the left-hand operand includes both remembering the variable that the left-hand operand denotes and fetching and saving that variable's value for use in the implied binary operation."

A: Consider 15.7.1. Evaluate Left-Hand Operand section of java specs where it says - First, the left-hand operand is evaluated to produce a variable then the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator
In your case it is a = 10 * ((11)+10) = 201


text:
Q: ValueError: I/O operation on closed file while looping Hi I am facing I/O error while looping file execution. The code prompt 'ValueError: I/O operation on closed file.' while running. Does anyone have any idea while says operation on closed as I am opening new while looping? Many thanks
code below:
with open('inputlist.csv', 'r') as f:  #input list reading
    reader = csv.reader(f)
    queries2Google = reader
print(queries2Google)

def QGN(query2Google):
    s = '"'+query2Google+'"' #Keywords for query, to solve the + for space
    s = s.replace(" ","+")
    date = str(datetime.datetime.now().date()) #timestamp
    filename =query2Google+"_"+date+"_"+'SearchNews.csv' #csv filename
    f = open(filename,"wb")   #open output file

    pass

    df = np.reshape(df,(-1,3))
    itemnum,col=df.shape
    itemnum=str(itemnum)
    df1 = pd.DataFrame(df,columns=['Title','URL','Brief'])
    print("Done! "+itemnum+" pieces found.")

    df1.to_csv(filename, index=False,encoding='utf-8')
    f.close()

    return

for query2Google in queries2Google:
    QGN(query2Google) #output should be multiple files

A: with closes the file that you are trying to read once it it is done. So you are opening file, making a csv reader, and then closing the underlying file and then trying to read from it. See more about file i/o here
Solution is to do all of your work on your queries2Google reader INSIDE the with statement:
with open('inputlist.csv', 'r') as f:  #input list reading
    reader = csv.reader(f)
    for q2g in reader:
        QGN(q2g)

Some additional stuff:
That pass isn't doing anything and you should probably be using with again inside the QGN function since the file is opened and closed in there. Python doesn't need empty returns. You also don't seem to even be using f in the QGN function.


text:
Q: How to filter/get Test Lab instances/configurations using cross filter in ALM using OTA API? Hi am trying to get a list of test configurations using complex filter I got from ALM GUI (its from the button Copy Filter Settings)
[Filter]{
TableName:CYCLE,
ColumnName:CY_CYCLE_ID,
LogicalFilter:409,
VisualFilter:409,
NO_CASE:
}
{
TableName:CYCLE,
ColumnName:CY_FOLDER_ID,
LogicalFilter:\0000001a\^Root\Test sety 01\Podzim^,
VisualFilter:\0000001a\^Root\Test sety 01\Podzim^,
NO_CASE:
}
{
FLT:[X],
TYPE:TESTSET-TSTEST,
EXISTS_IN_IDS:Y,
IN_IDS:\0000007a\[Filter]{
TableName:TESTCYCL,
ColumnName:TC_TESTER_NAME,
LogicalFilter:username,
VisualFilter:username,
NO_CASE:
}

}

I only know how to filter easily using
TestConfigFactory.Filter.SetXFilter ("Value from database") = "Value"

I only found this example in OTA API Documentation:
' Get the Test filter object. This filter is unconditional.
' We want all the tests from the test set.
'
    Dim testF As TestFactory, testFilter As TDFilter
    Set testF = tdc.TestFactory
    Set testFilter = testF.Filter

' Set the cross filter: All tests associated with the
' test sets that meet the criteria - in this case, the
' one test set whose name was passed to this routine.
    testFilter.SetXFilter "TEST-TESTSET", True, tsFilter.Text

Is there any way in ALM Customization to achieve it like this?:
   set testConfigFact = TDConnection.TestConfigFactory
   set testConfigFilter = testConfigFact.Filter
   testConfigFilter.SetXFilter ("SOMETHING") = [Filter]{
                TableName:CYCLE,
                ColumnName:CY_CYCLE,
                LogicalFilter:igor,
                VisualFilter:igor,
                NO_CASE:
                }
   set testConfigList = testConfigFilter.NewList()
   set testCfg = testConfigList.Item(1)
   msgbox "test config: " & testCfg.ID

A: As far as I know, there is no way to get TestConfig entities from any other entity using cross filters.
Try this (in C#):
TSTestFactory tsTestFact = entTestSet.TSTestFactory;

// tdFilter is the TDFilter you want to apply to __TestInstances__
List tsTestList = tdFilter == null ?
    tsTestFact.NewList(String.Empty) :
    tsTestFact.NewList(tdFilter.Text);

foreach (TSTest testInstance in tsTestList)
{
    TestConfig testConfig = testInstance.TestConfiguration;
}

Hope this helps.

A: Actually you can use the copied filter text directly like below using F# (for C# it is very similar, just set the filter.Text using the copied filter):
let bf = connection.BugFactory :?> BugFactory
let filter = bf.Filter :?> TDFilter
filter.Text <- @"[Filter]{
TableName:BUG,
ColumnName:\00000012\BG_DETECTED_IN_REL,
SortOrder:2,
SortDirection:0,
NO_CASE:
}
{
TableName:BUG,
ColumnName:BG_RESPONSIBLE,
LogicalFilter:[CurrentUser],
VisualFilter:[CurrentUser],
NO_CASE:
}
{
TableName:BUG,
ColumnName:BG_SUMMARY,
SortOrder:1,
SortDirection:0,
NO_CASE:
}
[Grouping]{
ColumnName:BG_STATUS,
GroupOrder:1
}"
let result = bf.NewList(filter.Text)
printfn "%d" result.Count

But if you want to modify the filter text you copied, it will be not very convenient. For example in the code block line 5, in \00000012\BG_DETECTED_IN_REL, \00000012\ in HEX defined the length of it`s rear value "BG_DETECTED_IN_REL" which has 18 characters. So if you modified any value which has prefix like ********\ you should also modify the prefix accordingly.
However, I think using XFilter is more easy and convenient.


text:
Q: thor websocket load testing - add custom http header in web socket handshake request I am using thor for load testing my twisted based autobahn websocket server. For authentication purposes my websocket application need a custom http header (Authorization : Bearer token) in websocket handshake request as part of authentication. How can I do this ?

A: It doesn't look like thor supports adding headers so you either need to patch it to add this support or consider another tool like:

*

*Gatling

*Apache JMeter


text:
Q: Rotation around Z axis of world I am trying to apply a rotation to fix the camera pose in my setup, since one of the axes seems to be off. I suspect this axis to be Z of "world" frame. In other words, I need to rotate "stereo_camera" frame around the Z axis of the "world frame" by 90 degrees. Then all should be OK.

I've tried using several Python libraries and Octave to achieve this but I failed. Somehow either the multiplication or the way I express the quarternion doesn't seem to comply.
# Here is the current quarternion of "stereo_camera"
q = np.array([0.0, 0.70710678, 0.0, 0.70710678])

# Rotation matrix, 90 degrees around Z would be:
I = np.array([[0, -1, 0],[1,0,0],[0,0,1]])

# apply the transformation
q.dot(I)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: shapes (4,) and (3,3) not aligned: 4 (dim 0) != 3 (dim 0)

Is there anyone who could suggest me a nice Python package which can handle such situations, with a minimal example? It shouldn't be hard to apply 1 single rotation to a quarternion.

A: So, what had to be done was to use the rotation matrix, not the quarternion. I used this to convert from quarternion to rotation matrix.
Rotation matrix is a matrix which looks like this:
[  0.0000000, -1.0000000,  0.0000000;
   0.0000000,  0.0000000,  1.0000000;
  -1.0000000,  0.0000000,  0.0000000 ]

Once this matrix is acquired, it can be multiplied.


text:
Q: How to get a music player with circular progress bar and play button in center? I want an audio player app just like this image:

I'm playing the audio using dependency injection on button click.

A: I know there's some external nuget like Telerik and Syncfusion that provides API for you to implement a circular gauge, so you can create your audio player button in Xamarin.
If you want to implement that feature yourself, you can create your own layouts.
Let the total length of the audio is total and the length played already is played.

Approach 1:

Let's call this layout Base:

*

*When the audio bar is less than or equal to 50% filled, create a blue circle base B.  Cover the left half of B with a gray semicircle G1 and the right half of B with another gray semicircle G2.  Then Rotate G2 by 360.0 * played / total.

*When the audio bar is more than 50% filled, create a gray circle base G instead.  Cover the right half of G with a blue semicircle B1 and the right half of G again with another blue semicircle B2.  Then Rotate B2 by 360.0 * played / total - 180.0
Finally put a play/pause icon on top of a smaller white circle on top of Base to create your final audio player button.

Approach 2:

You can use SkiaSharp in Xamarin.Forms to draw circles and arcs.  You can create your audio play button by drawing a gray arc and a blue arc with length according to played and total.  They have a documentation on how to use SkiaSharp.


text:
Q: Using variables inside terraform.tfvars file I need to create VPC subnet tags using map variable.
Getting below error while passing value from locals tag in the terraform.tfvars file.
"Variables may not be used here"

I want to pass values from tfvars file instead of setting a default value for subnet_tags variable in the variables.tf file.
Below are the details.
variables.tf:

variable "project_name" {
  type        = string
}

variable "subnet_tags" {
  description = "public subnets"
  type        = map
}

---------------------------------------------------------

terraform.tfvars:

subnet_tags={
    "project"                                   = "${local.project_name}"
    "environment"                               = "development"
    "managed-by"                                = "terraform"
    "role"                                      = "public"
    }

--------------------------------------------------------------------------------

main.tf:

locals {
  project_name = var.project_name

}

module "vpc" {
  source      = "../modules/vpc
  subnet_tags = var.subnet_tags
  ...

}

A: You can use the merge [1] built-in function. Variables cannot be used inside tfvars file as you can see. So in your case, to combine two different sets of tags, you could drop the project tag from the subnet_tags variable:
subnet_tags={
    "environment"                               = "development"
    "managed-by"                                = "terraform"
    "role"                                      = "public"
    }

And then in the module call, just use merge and the project tag:
module "vpc" {
  source      = "../modules/vpc
  subnet_tags = merge(
    { "project" = local.project_name },
    var.subnet_tags
   )
  ...

}

[1] https://www.terraform.io/language/functions/merge


text:
Q: Wrapping an element inside a new element right where it is I have a content which contains many TextNodes, paragraphs and images. I want to put all the images tag inside a parent div. Well, I think there is no direct way to do this (in jQuery, I mean). How should I approach such displacement of elements. The following example illustrates my intent:
Original Content:

  Here are some texts.
  A second line.
  Click Here!
  Another Line.

  Another another line.

  Last line and many more to come.

After it is processed:

  Here are some texts.
  A second line.
  Click Here!
  Another Line.

  Another another line.

  Last line and many more to come.

The only different is that a new div is wrapping each image, now.

A: Use .wrap() to wraping HTML structure around each element.

$("#content > img").wrap("

");
.image-parent {
    border: 1px solid red;
}

  Here are some texts.
  A second line.
  Click Here!
  Another Line.

  Another another line.

  Last line and many more to come.


text:
Q: Asterisk quits intermittently I have been working on a project which requires Asterisk as SIP proxy. I am able to register, call and recieve calls with the my setup of asterisk.
Only problem is that Asterisk quits intermittently without any crash dumps or segregation fault nothing!. Also I found that as there's not any reachable users it quits. On restarting i see messages for last qualify 0 for user last reached.
Pretty much stuck on this issue, any help would be much appreciated.!

A: Asterisk is not PROXY, it is pbx.
For proxy(load over 1k calls or CPS over 80) please use kamailio.
You have enable core dump and compile asterisk with debug flags to do debugging.
You also may consider change pjsip to chan_sip or via versa.
https://wiki.asterisk.org/wiki/display/AST/Getting+a+Backtrace

A: Core dumps must be manually enabled: https://wiki.asterisk.org/wiki/display/AST/Getting+a+Backtrace
Then you can dubug the problem using:

gdb `which asterisk` /tmp/core*

Then type bt full to show all threads.


text:
Q: How i change ListView Item Background Color according to listview item HarfNotu value in wpf My ListView looks like:
http://oi36.tinypic.com/ek5n3o.jpg
My listview xaml:
<ListView  Name="notListView" Width="550" HorizontalAlignment="Left">
        <ListView.View>
        <GridView AllowsColumnReorder="true">
            <GridViewColumn Header="Ders Kodu" Width="100" DisplayMemberBinding="{Binding Path=DersKodu}" />
            <GridViewColumn Header="Ders Adı" Width="200" DisplayMemberBinding="{Binding Path=DersAdi}" />
            <GridViewColumn Header="Vize" Width="50" DisplayMemberBinding="{Binding Path=Vize}" />
            <GridViewColumn Header="Final" Width="50" DisplayMemberBinding="{Binding Path=Final}" />
            <GridViewColumn Header="Ortalama" Width="60" DisplayMemberBinding="{Binding Path=Ortalama}" />
            <GridViewColumn Header="Harf Notu" Width="60" DisplayMemberBinding="{Binding Path=Harf}" />
        </GridView>
    </ListView.View>
</ListView>

My .cs code:
notListView.ItemsSource = notGoruntule(1, 1); // notGoruntule() function returns an Arraylist, which contains my "Notlar" objects.

I tried this:
ListViewItem lvitem = (ListViewItem)notListView.Items[0];
lvitem.Background = Brushes.Red;

But first line throws:
Unable to cast object of type 'OBS_Interface_5.Classes.Notlar' to type 'System.Windows.Controls.ListViewItem'.

How i solve this problem?

A: You can Style the ListViewItem in xaml directly,
Example:
Assuming your "Harf" variable is a string, you can try
<ListView Name="notListView"
          Width="550"
          HorizontalAlignment="Left">
  <ListView.Resources>
    <Style TargetType="{x:Type ListViewItem}">
      <Style.Triggers>
        <DataTrigger Binding="{Binding Harf}"
                      Value="1">
          <Setter Property="Background"
                  Value="Red" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </ListView.Resources>
  ...

Now any ListView Row with "Harf" Value of 1 will have a "Red" Background


text:
Q: How do I get scanf in C to print an error when a char is detected? This is what I think the code should look like. It's inside a function (main) by the way.
char a;
if (a [is detected]) {
    printf("Incorrect input format \n");
    exit( EXIT_FAILURE );
}

A: Remember that digits are also characters. What you want to do is to use scanf to scan for an integer, and check the return value. The return value from the scanf family of function is the number of successfully scanned items, or -1 on error. If you scan for a single integer (format "%d") then if scanf doesn't return 1 there was an error.
So you could do something like
if (scanf(" %d", &number) == 1)
{
    /* Got a number okay */
}
else
{
    /* Not a number in the input */
}

Also remember that if scanf fails, the input is still there, so you can't just loop and hope the current input will be disregarded. A simply way to get by that is to use fgets to read one line of input, and then use sscanf to scan the newly read line.

A: Use fread instead of scanf to read the input from stdin. Parse the input provided by user to check if char is given as input, then print the error.


text:
Q: angular otherwise not working with spring boot I am facing some weird type of behavior with spring boot + angular js while doing routing. Although routing is working but otherwise redirect to is not working.
For example:

*

*if the url is http://localhost/admin/home#/analysis(working)

*if the url is http://localhost/admin/home#/ (working)

*but if the url is http://localhost/admin/home  (not working)

I have configured otherwise but its not doing any benefit
Below is my code:
 .config(['$routeProvider','$httpProvider',function ($routeProvider, $httpProvider) {
    $routeProvider.when('/analysis', {
        templateUrl : '../resources/views/includes/dashboard.html',
        controller : "RegistrationController"
    }).when('/', {
        templateUrl : '../resources/views/includes/profile.html',
        controller : "RegistrationController"
    })
    .otherwise({
        redirectTo: '/'
    });
     $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
}]);

I have placed      in html

A: I would suggest you to take a look at $locationProvider.html5Mode(true).
It tells angularJS to use HTML5 strategy if available. Basically # is required for those browsers who do not support HTML5.
Also, you will be required to configure <base> tag of html.
Even when you will implement these concepts, you will stumble across another issue which I faced as well. If you navigate via href in the application, it would work , but if you copy the url and paste it directly in the browser, you'll get error as it would directly hit the server and will try to find necessary URL mapping on the server.
For more details, you can look at this this question which I asked for this issue
I hope it'll help.

A: Your problem is more related to SEO-related AngularJS implementation, basically, the solution to this is using the rewrite functionality of Apache or Nginx.
For more information, you can start here.


text:
Q: Moving background to infinite scroll help Swift Sprite Kit I'm having trouble understanding what I did wrong here. It's supposed to infinite scroll downwards and I can't fix it. Help!
 func moveBackground() {

    let moveBackground = SKAction.moveByX(0, y: -self.size.height, duration: 1.0)
    let repeatBackground = SKAction.repeatActionForever(moveBackground)
    let removeBackground = SKAction.removeFromParent()
    let sequenceThis = SKAction.sequence([moveBackground, repeatBackground, removeBackground])
}
func repeatBackground() {

    let generateBackground = SKAction.sequence([
        SKAction.runBlock(self.moveBackground),
        SKAction.waitForDuration(2.7)])
    let endlessAction = SKAction.repeatActionForever(generateBackground)
    runAction(endlessAction)
}

override func didMoveToView(view: SKView) {
    scene?.scaleMode = .AspectFill

    var backgroundTexture = SKTexture(imageNamed: "Background.png")
    background.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2)
    background.texture = backgroundTexture
    background.size.width = self.frame.size.width
    background.size.height = self.frame.size.height
    self.addChild(background)

}

Whenever I run the app the background just stays in its position and won't move.

A: First of all moveBackground() doesn't do anything except creating actions, it doesn't run them. You probably forgot to run runAction(sequenceThis) in the end.
There are many more issues like, you are removing the sprite for some reason but making action repeat forever, it will remove that sprite again, but nothing is adding it back.
repeatBackground() runs moveBackground() forever but it doesn't create new background, it just moves one forever.
Lastly didMoveToView doesn't call repeatBackground() nor moveBackground().

A: In moveBackground() you are not "running" the action. The result would presumably be that it does nothing.
You need to tell the background to run this action.
backgroundView.runAction(sequenceThis)


text:
Q: Error due to Site.Master file - asp.net using c# I am receiving an error due to the Site.Master file. I have made numerous adjustments and still cannot get past this issue with the Site.Master file. Do I have the wrong specification perhaps? My code executes perfectly in Microsoft Visual Studios, however when I export the site files to the hosted servers this is where I run into issues.

Compiler Error Message: CS1002: ; expected
Line 1365:            System.Web.UI.WebControls.ListViewDataItem
Container; Line 1366:            System.Web.UI.DataBoundLiteralControl target;
Line 1367:            across-america.Models.Category Item;
line 83 "E:\server\USER\across-america\Site.Master"

The error is due to the following:
<asp:ListView ID="categoryList" ItemType="across-america.Models.Category" runat="server" SelectMethod="GetCategories">

I have modified the temType="across-america.Models.Category" to remove across-america but then I still get an error. Any advice???
C# code with error:

    <asp:ListView ID="categoryList" ItemType="Models.Category" runat="server" SelectMethod="GetCategories">
        <ItemTemplate>

                <a href="/ProductList.aspx?id=<%#: Item.CategoryID %>">
                <%#: Item.CategoryName %>

        </ItemTemplate>
        <ItemSeparatorTemplate>  |  </ItemSeparatorTemplate>
    </asp:ListView>

Models Class in Category.cs:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace Models
{
    public class Category
    {
        [ScaffoldColumn(false)]
        public int CategoryID { get; set; }

        [Required, StringLength(100), Display(Name = "Name")]
        public string CategoryName { get; set; }

        [Display(Name = "Product Description")]
        public string Description { get; set; }

        public virtual ICollection<Product> Products { get; set; }
    }
}

Site.Master Models Reference, towards the end of code:
using Models;
using across-america.Logic;

namespace across-america
{
    public partial class SiteMaster : MasterPage
    {
        private const string AntiXsrfTokenKey = "__AntiXsrfToken";
        private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
        private string _antiXsrfTokenValue;

        protected void Page_Init(object sender, EventArgs e)
        {
            // The code below helps to protect against XSRF attacks
            var requestCookie = Request.Cookies[AntiXsrfTokenKey];
            Guid requestCookieGuidValue;
            if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
            {
                // Use the Anti-XSRF token from the cookie
                _antiXsrfTokenValue = requestCookie.Value;
                Page.ViewStateUserKey = _antiXsrfTokenValue;
            }
            else
            {
                // Generate a new Anti-XSRF token and save to the cookie
                _antiXsrfTokenValue = Guid.NewGuid().ToString("N");
                Page.ViewStateUserKey = _antiXsrfTokenValue;

                var responseCookie = new HttpCookie(AntiXsrfTokenKey)
                {
                    HttpOnly = true,
                    Value = _antiXsrfTokenValue
                };
                if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
                {
                    responseCookie.Secure = true;
                }
                Response.Cookies.Set(responseCookie);
            }

            Page.PreLoad += master_Page_PreLoad;
        }

        protected void master_Page_PreLoad(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Set Anti-XSRF token
                ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
                ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
            }
            else
            {
                // Validate the Anti-XSRF token
                if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
                    || (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
                {
                    throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void Page_PreRender(object sender, EventArgs e)
        {
            using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
            {
                string cartStr = string.Format("Cart ({0})", usersShoppingCart.GetCount());
                cartCount.InnerText = cartStr;
            }
        }
        public IQueryable<Category> GetCategories()
        {
            var _db = new Models.ProductContext();
            IQueryable<Category> query = _db.Categories;
            return query;
        }
        protected void Unnamed_LoggingOut(object sender, LoginCancelEventArgs e)
        {
            Context.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
        }
    }

}


text:
Q: Scraping hover over figure using Python and Selenium I am trying to scrape the data from http://fuelinsights.gasbuddy.com/Charts using Python and Selenium.  The difficult part is that the data only appear when a point on the line graph is hovered over.  Currently, my issue is an inability to create a list of all the hover over objects.  My code so far is below:
from selenium import webdriver as web
from selenium.webdriver.common.action_chains import ActionChains

driver = web.Chrome('driver path')

driver.get('http://fuelinsights.gasbuddy.com/Charts')

test= driver.find_elements_by_xpath('//*[@class="highcharts-markers"]')

print(test)

`
which gives me test=[].  Previously, I have used beautifulsoup for all of my scraping projects, but I have redone some of my previous projects to make sure that I understand how Selenium works and haven't had issues.
If anyone can help me solve this issue so I can create a list of the items that I can use ActionChains to hover over and extract the price and date from it would be much appreciated.
Thank you!
****EDIT****
To clarify, I have looked over numerous other posts concerning SVG and g elements and Highcharts, but I am still short on a solution to this problem.  I have tried numerous Xpaths (and other find_elements_by options), but have only been able to come to two results: (1) the Xpath is valid, but does not contain any elements, or (2) InvalidSelectorException indicating that I was unable to locate an element with the xpath expression.  I believe this comes down to simply incorrectly specifying my Xpath, but I am at a loss for how to find the correct Xpath.

A: You can't use the Xpath which you have mentioned above for locating the elements inside the svg tag.
Xpath which you can use to create a list of hover objects is:
//*[name()='svg']//*[name()='g' and @class='highcharts-markers']/*[name()='path']

I have written a java program for getting the text of all the tool-tip elements. You can use the logic and write a corresponding python code:
1. Get List of tooltip Elements
 List <WebElement> highChartElements= driver.findElements(By.xpath("//*[name()='svg']//*[name()='g' and @class='highcharts-markers']/*[name()='path']"));

2. Iterate through the list and use action class for moving and clicking on all the tooltip Elements
3. Get the text of the tooltip elements.
for(WebElement element:highChartElements){
        Actions action = new Actions(driver);
        action.moveToElement(element).click().perform();
        Thread.sleep(3000);
        List<WebElement> highChartToolTipTextElements= driver.findElements(By.xpath("//*[name()='svg']//*[name()='g' and @class='highcharts-tooltip']/*[name()='text']/*[name()='tspan']"));
        for(WebElement toolTipElement:highChartToolTipTextElements){
            System.out.println("The text for the elements is"+toolTipElement.getText());
        }
    }

A: Thanks You ! 2 years later, i'm facing to an equivalent project and used your example to learn how to get the job done with python & Firefox.
Perhaps the following code will be useful to some people.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Firefox(executable_path=r'path\to\the\geckodriver.exe')
driver.get('http://fuelinsights.gasbuddy.com/Charts')
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "highcharts-markers")))
test = driver.find_elements_by_xpath("//*[name()='svg']//*[name()='g' and @class='highcharts-markers']/*[name()='path']")

res = []
for el in test:
    hover = ActionChains(driver).move_to_element(el)
    hover.perform()
    date = driver.find_elements_by_css_selector(".highcharts-tooltip > text:nth-child(5) > tspan:nth-child(1)")
    price = driver.find_elements_by_css_selector(".highcharts-tooltip > text:nth-child(5) > tspan:nth-child(4)")
    res.append((date[0].text, price[0].text))

"res" contains :
('Saturday, May 30, 2020', '1.978 $/gal')
('Friday, May 29, 2020', '1.979 $/gal')
('Thursday, May 28, 2020', '1.977 $/gal')
('Wednesday, May 27, 2020', '1.972 $/gal')
('Tuesday, May 26, 2020', '1.965 $/gal')
.......


text:
Q: Getting the multiple of two integers in C programming I'm new to programming and I'm trying to write a C program with two integer variables a and b. When the user types in these two variables, it should tell me if b is a multiple of a. Here's what I've done so far..
int main(void) /* standard header in c programming */
{
  int a;
  int b;

  printf("first number : \n");
  scanf("%d", &a);
  printf("second number : \n");
  scanf("%d", &b);
}

I don't really know, if I should use "if..else" and what my algorithm should look like?
Any help will be much appreciated. Thanks !

A: You can use the modulo operator % to find out if one value is a multiple value of another value. If you can do a integer-division without remainder (remainder == 0), then it's a multiple.
See also here
#include <stdio.h>

int main(void){
  int a, b;
  printf("first number : \n");
  scanf("%d", &a);
  printf("second number : \n");
  scanf("%d", &b);
  if(b % a == 0){
    printf("b is a multiple of a");
  }
  return 0;
}


text:
Q: How to alert if user not log in in shiny? I use the googleAuthR package in shiny, I want to alert users if they are not log in and I also want to save user's google id if they have successfully logged in. But sign_ins() is reactive consumer that I cannot do this. Any suggestions?
library(shiny)
library(googleAuthR)
library(shinyWidgets)

options(googleAuthR.webapp.client_id = "**********************")

ui <- fluidPage(

    titlePanel("Sample Google Sign-In"),

    sidebarLayout(
      sidebarPanel(
        googleSignInUI("demo")
      ),

      mainPanel(
        with(tags, dl(dt("Name"), dd(textOutput("g_name")),
                      dt("Email"), dd(textOutput("g_email")),
                      dt("Image"), dd(uiOutput("g_image")) ))
      )
    )
  )

server <- function(input, output, session) {

  sign_ins <- shiny::callModule(googleSignIn, "demo")

  output$g_name = renderText({ sign_ins()$name })
  output$g_email = renderText({ sign_ins()$email })
  output$g_image = renderUI({ img(src=sign_ins()$image) })

  if(is.null(sign_ins())){
    shinyWidgets::show_alert(title = "not log in",

                             type = NULL,
                             btn_labels = "Ok")
  else{
      write.csv(sign_ins(),"file.csv")
      }

  }
}

# Run the application
shinyApp(ui = ui, server = server)

A: I'm not familiar with googleAuthR but every google-api product in R is most likely has "*_has_token" feature to validate if there is an active credential logged in the session. I've checked the googleAuthR package and i think you can use googleAuthR::gar_has_token(). So instead of
 if(is.null(sign_ins())) {...}

you can use
if(googleAuthR::gar_has_token() == FALSE){...}

to check if there is an active credentials and do your things.
Hope this helpful


text:
Q: Least number of local trivializations of a vector bundle Let $X$ be a compact Hausdorff space, and let $\pi: E \to X$ be a real or complex vector bundle over $X$ of rank $r$. Then there exist finitely many local trivializations of $E$, i.e. there exists an open covering $(U_j)_{j=1}^k$ and homeomorphisms $h_j : \pi^{-1}(U_j) \to U_j \times \mathbb{K}^r$ such that $\pi(h_j^{-1}(x,v)) = x$ for $j=1, \ldots, k$.
Is there a name for the least such $k$, i.e. the least number of local trivializations required for the vector bundle? Also, are there some references looking into this concept?


text:
Q: jquery smartbanner without apple smartbanner I am using http://jasny.github.io/jquery.smartbanner/  but the default apple smartbanner is showing so there are two, I only want the one I created using that plugin and not the apple one. How can I achieve this?

A: I'd advise removing Apple's apple-itunes-app meta tag and implementing something that is completely standalone instead, e.g. smartbanner.js.
smartbanner.js also gives you more flexibility and the most recent release also allows advanced filtering as per platform.


text:
Q: Good practice for using almost identical sprites in phaser. Alternatives to using more sprites So, I have been working in Unity but I've decided it's time to change to something I know better: JavaScript. I've been considering switching to Phaser.js but I have some questions regarding an issue I've been having even in Unity and that I found no solution to at the moment while searching on the internet. I have no code to provide as I haven't yet started actually programming in Phaser, so I'll try to be explicit.
My game idea basically revolves around some lights that change colors. The sprites I have for the lights look identical, but just with different colors, but not entirely (only parts of them are colored differently). The problem is that my game has many different colored lights and it has to change between them. Like, if one light is red and you click on it, it becomes green, for example. Creating and loading so many sprites that look almost the same seems like a bad practice, and I wonder if there is a way to change the color of a sprite or a part of the sprite by code. I know that Phaser doesn't support svg and that svg in games is a bad idea in general because of performance issues but it would have saved me a lot of time to just add the generated svg code of the sprites I use and just change the fill of the parts I want.
So, my question is: what are the best alternatives (if any) to using multiple sprites or how can you change the color of specific parts of them?

A: Another alternative, depending upon your light sprites, is to use Phaser's tinting capabilities.
Both sprites and images in Phaser can be tinted, and since Phaser supports sprite grouping, even if you wanted to change only a part of the image you could easily have each displayed object consist of two sprites, one of which is the same for all lights (the part that doesn't change) and another that is also shared, but tinted.
Phaser 3 example of tinting an image:
this.add.image(300, 300, 'pixel').setTint(0xff0000);

Phaser 3's setTint() documentation.
Phaser 2 CE example of tinting a sprite, in case you're looking at using this version:
sprite = game.add.sprite(game.world.centerX, game.world.centerY, 'atlas', 'greenJellyfish0000');
sprite.tint = Math.random() * 0xffffff;

A: If the lights don't have to move, then you can just have a few images and change their src's. Alternatively, I believe you could have it so that when the sprite is clicked it changes to a different looking animation. That is, after all, the point of a spritesheet, isn't it?


text:
Q: detecting change in variance with age I have some data on some measure of performance for a group of participants of different ages (11-30 years). The scatterplot suggests that the variance changes over that time, with a wide range of scores in younger participants and a narrower range of scores in older participants. The scores at the top of the range don't vary much with age, but the lower scores get higher with age. Sorry for the poor description - a graph would help here, but I hope you get what I mean.
Linear regression tells me that there is a significant relationships between age and mean performance (i.e., performance improves with age).
What I want to know is how to formally test for a change in the variance with age. Can I just do a linear regression through the lowest values in each of, say, 10 equal age bands and show that there is a significant increase? Is there a better way?

A: There are quite a few possibilities. I'll mention just a couple.

*

*You might fit a heteroskedastic regression, perhaps via REML. These can be fitted in a number of packages. (In R you can fit them with remlscore in statmod.)

*You might look at quantile regression, say a high quantile and a low quantile; the  slopes of the two quantiles can be considered as modelling the spread. Again, quantile regression can be done in a number of packages. (In R you can fit these with rq in quantreg, for example).


text:
Q: Execute an external program from an android app I need to execute 'nmap' binary for my app. I use the wrapper nmap4j, in which i write the path on the device "sdcard/Nmap/bin/nmap".
try {
    nmap4j.execute();
} catch(Exception e) {
    System.out.println("error execute " + e);
}

The following error :
        error execute org.nmap4j.core.nmap.NMapExecutionException: Cannot run program "sdcard/Nmap/bin/nmap": error=13, Permission denied
showed up, and the app crashes because of a null pointer exception later

A: So, I found the solution to THIS problem.
I used the Android Studio "Device File Explorer", and I uploaded my binay executable in the application data folder:
root/data/data/com.example.appname/
Hope it can help


text:
Q: Scope with a self-invoking function in Javascript Take below code iterates over 6 input buttons and attaches an onclick event to every button that alerts the index number of the respective iteration:
for (var i = 1; i < 6; ++i) {
    var but = document.getElementById('b_' + i);
    (function (el) {
        var num = i;
        but.onclick = function () {
            alert(num);
        };
    })(but);
}

As you can see, in each iteration there is a self-invoking function that creates a scope to store the iteration index in that scope.
I have always used this type of pattern to attach an event that is dependant on a variable that is changed during iterations.

Can anyone explain to me exactly why the above works, and how the num variable is captured in the scope?
Also, is the self-invoking function used above called a closure ?

A: Yes this is a closure.
Everytime a function is executed a new object is created to hold (as its properties) the variables that are declared with var and every function declared inside it. This object is called the execution context (or sometimes the scope object).
Everytime a function is declared (or defined in an expression) the new function has attached to it the execution context object that is current.  This creates what is known as a scope chain.
When executing code needs to resolve an identifier to a value it first looks for it in the properties of the current execution context.  If the identifier is not found it uses the exection context object attached to the function that is being executed.  It keeps going up the scope chain until it reaches the global level.
In your example each time "self-invoking function" gets executed a new execution context object is create holding the properies el and num.  Since the function assigned to onclick is created inside this execution context you will get a new instance of this function each time.  These instances will each have the corresponding execution context object attached.  Hence the first will have the execution context when num has been assigned 1, the second will have the execution context where num has been assigned 2 and so on.
When each of the onclick functions run the code will initially look for the identifier num in the current execution context.  However this inner function doesn't var a num so its not found.  So Javascript looks to the execution context attached to the function when it was created.  Here it will find num, the num will contain the value assigned to it during that iteration as described above.

A: Hey guys. Yep it is a closure. If you want to know what exactly occurs when function is creating then study following article.
http://www.jibbering.com/faq/faq_notes/closures.html

A: Wouldn't that mean that the var i defined outside the closure is a global variable, thus giving the self-invoking function access to it?

A: Each time through the loop, evaluating function (el) {...} creates a new anonymous function, which is immediately invoked. Within the anonymous function, a variable named num is created (because JS doesn't do static variables, it's a new one each time). num is assigned the value of i when the function is invoked (which is immediately). This gives us 6 anonymous functions and 6 nums, each holding the values 1 through 6.
With each invocation of the anonymous function, an inner anonymous function is created and stored as the click handler. The inner function references a num. As a result, a closure is created which ensure that when the outer function exits, num isn't destroyed. Should the inner function ever be discarded, num will soon follow.

A: for (var i = 1; i < 6; ++i) {
    var but = document.getElementById('b_' + i);
    (function (el) {
        var num = i;
        but.onclick = function () {
            alert(num);
        };
    })(but);
}

Now lets start the execution of the loop
initially i=1,but= domelement with id ='b1'
now comes the function invoke,
ok it calls the inner function(with parameter el) with value of parameter of but('b1')
and starts executing it that is what invoking actually means execute it now.
Now inside it ,
new instance of num is assigned 1
but.onclick is assigned a function so stores function in memory also sees that it accesses num so num is now closed variable that means its lifetime is increased so as to be accessed by onclick function when invoked.
Next iterationnow value of i=2,but= domelement with id ='b2'
now comes the function invoke,
it calls the inner function(with parameter el) with value of parameter of but(value='b2') .
Now inside it ,
new instance of num is assigned 2
but.onclick is assigned a function so stores function in memory also sees that it accesses num so num is now closed variable that means its lifetime is increased so as to be accessed by onclick function when invoked.
Similary all others are exectuted till the loop terminates.


text:
Q: Latex Beamer - Vertically center aligned text to the left of tcolorbox I want to place three tcolorboxes among themselves with arrows between them. To the left of each colorbox is a text that should be center aligned with respect to the box.
The following code produces the boxes, arrows and texts, but I miss the vertical center alignment.
\begin{tabularx}{0.5\textwidth}{p{0.6cm}c}
        1979 &
        \begin{tcolorbox}[colframe=tubsred,colback=white,arc=4pt,
            left=6pt,right=6pt,top=6pt,bottom=6pt,boxsep=0pt,width=0.7\textwidth, halign = center]
            Text A
        \end{tcolorbox} \\
        %
        & \begin{tikzpicture}[line cap = round]
        \draw[tubsred, line width = 3pt, ->] (0,0) -- (0,-0.5);
        \end{tikzpicture} \\
        %
        1992 &
        \begin{tcolorbox}[colframe=tubsred,colback=white,arc=4pt,
            left=6pt,right=6pt,top=6pt,bottom=6pt,boxsep=0pt,width=0.7\textwidth, halign = center]
            Text B
        \end{tcolorbox} \\
        %
        & \begin{tikzpicture}[line cap = round]
        \draw[tubsred, line width = 3pt, ->] (0,0) -- (0,-0.5);
        \end{tikzpicture} \\
        %
        This \newline Work &
        \begin{tcolorbox}[colframe=tubsred,colback=white,arc=4pt,
            left=6pt,right=6pt,top=6pt,bottom=6pt,boxsep=0pt,width=0.7\textwidth, halign = center]
            Text C
        \end{tcolorbox} \\
        %
    \end{tabularx}

Current:

Wanted:

What's the best way to achieve this behavior?

A: Here I use the baseline= key to tcolorbox.  For the single line entries, its value should be that of bottom plus the line thickness, estimated here as 7.5pt.  For the 2-line entry, I had to add 1/2 of a \normalbaselineskip.
\documentclass{article}
\usepackage{tcolorbox,tabularx,tikz}
\begin{document}
\begin{tabularx}{0.5\textwidth}{p{0.6cm}c}
        1979 &
        \begin{tcolorbox}[baseline=7.5pt,
        colframe=red,colback=white,arc=4pt,
            left=6pt,right=6pt,top=6pt,bottom=6pt,boxsep=0pt,
            width=0.7\textwidth, halign = center]
            Text A
        \end{tcolorbox} \\
        %
        & \begin{tikzpicture}[line cap = round]
        \draw[red, line width = 3pt, ->] (0,0) -- (0,-0.5);
        \end{tikzpicture} \\
        %
        1992 &
        \begin{tcolorbox}[baseline=7.5pt,
        colframe=red,colback=white,arc=4pt,
            left=6pt,right=6pt,top=6pt,bottom=6pt,boxsep=0pt,
            width=0.7\textwidth, halign = center]
            Text B
        \end{tcolorbox} \\
        %
        & \begin{tikzpicture}[line cap = round]
        \draw[red, line width = 3pt, ->] (0,0) -- (0,-0.5);
        \end{tikzpicture} \\
        %
        This \newline Work &
        \begin{tcolorbox}[baseline=\dimexpr7.5pt+.5\normalbaselineskip\relax,
        colframe=red,colback=white,arc=4pt,
            left=6pt,right=6pt,top=6pt,bottom=6pt,boxsep=0pt,
            width=0.7\textwidth, halign = center]
            Text C
        \end{tcolorbox} \\
        %
    \end{tabularx}
\end{document}


text:
Q: std::vector and std::list find_if and max_element performance I am confused about performance of my code tested for std::vector and std::list. Is there a difference between these two when it comes to find_if and max_element?

A: In terms of big-O notation, both have identical performance of O(n). (find_if can be less if the element is found sooner, but this is equally true for both containers.)
In terms of actual wall-clock time, the vector will perform better due to cache coherency; all the vector elements are sequential in memory, so accessing them will make better use of the CPU cache. A linked list's elements can be scattered throughout memory, and you also need to follow the list links which takes time.

A: Both algorithms are O(n) in terms of computational complexity, but vectors allocate their elements in a contiguous region of storage, which will most likely result in a higher cache hit rate. Traversing a lists, on the other hand, involves a scattered memory access pattern that is likelier to result in a higher rate of cache misses.
As always when it comes to performance, anyway, do measurements before making decisions.

A: For max_element, all elements of both list and array will be traversed. So, both are O(n) in terms of performance.
Again for find_if, the traversal will be linear (O(n)) for both the data structures.
I don't think there should not much of a difference apart from the constants relative to each.


text:
Q: why it reverse the opration after it do? I try to add a numbers from 1 to 10 by JavaScript using the concept of recursion and it didn't work as intended. it revers the operation and it come up with the first result and when i use variable to store the result i get it come up with undefined.
here is the code
var total = 0, count = 1;
function sum(total, count){
    if(count <= 3){
        total +=count;
        count++;
        sum(total, count);
    }else{
        return total;
    };
}
var result = sum(total, count);
console.log(result);

A: You are not returning from your first if condition. Default return value for any function is undefined.

var total = 0, count = 1;
function sum(total, count){
    if(count <= 3){
        total +=count;
        count++;
        return sum(total, count);
    }else{
        return total;
    };
}
var result = sum(total, count);
console.log(result);


text:
Q: What are the best practices/setup for applying caching techniques in web application? I want to apply caching techniques to improve my asp.net web application performance. I am going to use .NET default cash. I want to store the data in the XML file as well so that If the system fails to found the data from the cache, I can use the XML file as a secondary option. Is this workflow seems well or standard? Will file i/o operation degrade the performance instead of improving it or break the system integrity? The data volume will be medium and the number of files will be around 1k~2k.

A: Using XML files as data source seems like a rather unorthodox approach. A more common way would be using a database as data source and something like the Distributed Redis Cache for caching.
See the docs for further information.


text:
Q: How to exclude empty values and keys in array with jquery? I have an array;
[
  {pre_ref_fullname: "", pre_ref_position: "", pre_ref_phone: ""},
  {pre_ref_fullname: "", pre_ref_position: "", pre_ref_phone: ""},
  {pre_ref_fullname: "", pre_ref_position: "", pre_ref_phone: ""}
]

So, I want to remove elements if values is empty. If user added 2 referance info I want to get this data like this;
[
{pre_ref_fullname: "Name", pre_ref_position: "Job", pre_ref_phone: "Number"},
{pre_ref_fullname: "Name2", pre_ref_position: "Job2", pre_ref_phone: "Number2"}
]

I'm used some methods but not working. This is the last try with reduce and $prerefData is have this array;
var arr = $prerefData.reduce((result, item) => {
    if (item.value != "") {
       result.push(item);
    }
    return result;
    }, []);
console.log(arr);

A: You can use Javascript Array filter method
Briefly Array.filter will loop over your array, and run the callback on each element:

*

*If it returns true: Element is included in result

*If it returns false: Element is filtered out

let data = [
  {pre_ref_fullname: "", pre_ref_position: "", pre_ref_phone: ""},
  {pre_ref_fullname: "", pre_ref_position: "", pre_ref_phone: ""},
  {pre_ref_fullname: "", pre_ref_position: "", pre_ref_phone: ""},
  {pre_ref_fullname: "Name", pre_ref_position: "Job", pre_ref_phone: "Number"},
  {pre_ref_fullname: "Name2", pre_ref_position: "Job2", pre_ref_phone: "Number2"}
];

let result = data.filter(function (item) {
  for(key in item) {
    if (item[key]) {
      // Means one of the object keys have values, include it in the result
      return true
    }
  }
})

console.log(result)

A: try
data.filter(x=> Object.values(x).join(''));

let data = [
  {pre_ref_fullname: "", pre_ref_position: "", pre_ref_phone: ""},
  {pre_ref_fullname: "", pre_ref_position: "", pre_ref_phone: ""},
  {pre_ref_fullname: "", pre_ref_position: "", pre_ref_phone: ""},
  {pre_ref_fullname: "Name", pre_ref_position: "Job", pre_ref_phone: "Number"},
  {pre_ref_fullname: "Name2", pre_ref_position: "Job2", pre_ref_phone: "Number2"}
];

let r = data.filter(x=> Object.values(x).join(''));

console.log(r);

A: You can use filter, use Object.values to extract all values of individual objects.use every to check if all array values are not empty strings.

let data = [{"pre_ref_fullname":"","pre_ref_position":"","pre_ref_phone":""},{"pre_ref_fullname":"","pre_ref_position":"","pre_ref_phone":""},{"pre_ref_fullname":"","pre_ref_position":"","pre_ref_phone":""},{"pre_ref_fullname":"Name","pre_ref_position":"Job","pre_ref_phone":"Number"},{"pre_ref_fullname":"Name2","pre_ref_position":"Job2","pre_ref_phone":"Number2"}];

let result = data.filter(o => Object.values(o).every(e => e.trim() !== ""));

console.log(result);

You can use some if you want to check at least one is not an empty string.

let data = [{"pre_ref_fullname":"","pre_ref_position":"","pre_ref_phone":""},{"pre_ref_fullname":"","pre_ref_position":"not Empty","pre_ref_phone":""},{"pre_ref_fullname":"","pre_ref_position":"","pre_ref_phone":""},{"pre_ref_fullname":"Name","pre_ref_position":"Job","pre_ref_phone":"Number"},{"pre_ref_fullname":"Name2","pre_ref_position":"Job2","pre_ref_phone":"Number2"}]

let result = data.filter(o => Object.values(o).some(e => e.trim() !== ""));

console.log(result);

A: You should use the filter method:
let filtredArr = arr.filter(ele => ele.pre_ref_fullname && ele.pre_ref_position && ele.pre_ref_phone)

Since empty strings return false you don't need to add comparisons if this is the only case to filter out elements in the array.

A: Use filter with Object.values and every, and use trim to make sure it excludes whitespace:

const data = [{pre_ref_fullname:"",pre_ref_position:"",pre_ref_phone:""},{pre_ref_fullname:"",pre_ref_position:"",pre_ref_phone:""},{pre_ref_fullname:"",pre_ref_position:"",pre_ref_phone:""},{pre_ref_fullname:"Name",pre_ref_position:"Job",pre_ref_phone:"Number"},{pre_ref_fullname:"Name2",pre_ref_position:"Job2",pre_ref_phone:"Number2"}];

const res = data.filter(e => Object.values(e).every(s => s.trim != ""));

console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }