Q:

When I run a test suite with ChromeDrive Chrome is opened at every test

I'm trying to use the same code with Appium driver and Java , TestNG but with ChromeDriver I changed the configuration by adding that code :
File file = new File("C:/QA/Emna/chromedriver.exe");
        System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
        WebDriver driver = new ChromeDriver();

The problem is that any test case the chrome window is opened a new one, even if my tests are in a correct order with Priority (by TestNG).
Is there a way to work in only one window?

A:

I have fixed my problem by this way in @BeforeClass:
@BeforeClass
    public static void before() {
        // check active session
        System.out.println("Becore Test Method");
        File file = new File("C:/QA/Emna/chromedriver.exe");
        System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
        wd = new ChromeDriver();
    }

I made an instance like that:
static WebDriver driver ;

Then in every test I put the following :
@Test
public static void run1() {
//my tests using wd
}

@Test
public static void run2() {
//my tests using wd
}


Q:

SQL change a query to return results for all users

I use sql server and I have the tables:
tbl_GroupUser:
user_id, group_id

which is a table containing the users and the groups they are in (each group has more than one user_id and each user has more than one group).
tbl_group:
id, name

tbl_User:
id, age,....(information about the user)

There is a one to many relationship between id of tbl_Group to group_id and between id of tbl_User to user_id.
I created a query returning percentage of groups that has only 2 users in them for a specific user and I want a query that returns the results for all users. This is the query I made:
SELECT cast((SELECT count(*) FROM
(SELECT user_id FROM tbl_GroupUser WHERE group_id in
(SELECT group_id FROM (SELECT t1.group_id, count(distinct t1.user_id) as numberOfUsers
FROM tbl_GroupUser as t1 JOIN tbl_GroupUser as t2 ON t1.group_id = t2.group_id group by
t1.group_id) y WHERE y.numberOfUsers = 2)) as x WHERE x.user_id = 'user') as decimal) * 100 /
(SELECT count(*) FROM tbl_GroupUser WHERE user_id = 'user')

Which means, count all the groups the user is in that contains 2 users and divide it by the total number of groups the user is in.
An Example of what I want:
tbl_GroupUser:
group_id | user_id
------------------
 1       | 1
 1       | 2
 2       | 1

The results:
user_id | p_Grp2
----------------
 1      | 50.0
 2      | 100.0

A:

simple create User define function and use in select query
  alter function UDF_GetPercentage(@UserId int)
returns decimal(18,10)
as begin

declare @Percentage decimal(18,10)
SELECT @Percentage = cast(
(SELECT count(*) FROM
(SELECT user_id FROM tbl_GroupUser WHERE group_id in
(SELECT group_id FROM (SELECT t1.group_id, count(distinct t1.user_id) as numberOfUsers
FROM tbl_GroupUser as t1 JOIN tbl_GroupUser as t2 ON t1.group_id = t2.group_id group by
t1.group_id) y
WHERE y.numberOfUsers = 2)
)
as x

WHERE x.user_id in (@UserId)
) as decimal)
* 100
/
(SELECT count(*) FROM tbl_GroupUser WHERE user_id in (@UserId ))

return @Percentage

end

and use in select query like this
SELECT   user_id, dbo.UDF_GetPercentage(user_id) as p_Grp2
FROM     tbl_GroupUser
group by user_id


Q:

how to read facebook signed_request to get user_id

According to Facebook - Authentication within a Canvas Page Document, they say that we will be getting a signed_request which consists a JSON object. Now they say that signed_request can be get through $_POST['signed_request'] I agree its working for me.
Now according to them if the user is logged in i will be getting a JSON object value like this:-
{
  "expires":UNIXTIME_WHEN_ACCESS_TOKEN_EXPIRES,
  "algorithm":"HMAC-SHA256",
  "issued_at":UNIXTIME_WHEN_REQUEST_WAS_ISSUED,
  "oauth_token":"USER_ACCESS_TOKEN",
  "user_id":"USER_ID",
  "user":{
    "country":"ISO_COUNTRY_CODE",
    "locale":"ISO_LOCALE_CODE",
    ...
  }
}

Now i want to fetch the user_id out of this so i am using this piece of code but its not working:-
if(isset($_POST['signed_request']))
{
    echo 'YES';
    $json = $_POST['signed_request'];
    $obj = json_decode($json);
    print $obj->{'user_id'};
}

It just print the YES. Why is it so?
I have read somewhere that without app authentication i will not be able to extract the user_id but according to the facebook, this is the 1st step and authenticating the application would be 4th. I am new to it, if somebody can please help me, it will be of great help. Thanks.

A:

If you don't want to work with the FB SDK you can use this snippet of code to get the user_id and other variables (snippet from https://developers.facebook.com/docs/facebook-login/using-login-with-games/)
function parse_signed_request($signed_request) {
  list($encoded_sig, $payload) = explode('.', $signed_request, 2);

  // decode the data
  $sig = base64_url_decode($encoded_sig);
  $data = json_decode(base64_url_decode($payload), true);

  // confirm the signature
  $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
  if ($sig !== $expected_sig) {
    error_log('Bad Signed JSON signature!');
    return null;
  }

  return $data;
}

function base64_url_decode($input) {
  return base64_decode(strtr($input, '-_', '+/'));
}

A:

Old post I know but wanted to add a reply to Art Geigel's answer (I can't comment directly on it).
Your code snippet is missing the line,
   $secret = "appsecret"; // Use your app secret here

and the complete snippet,
function parse_signed_request($signed_request) {
   list($encoded_sig, $payload) = explode('.', $signed_request, 2);

   $secret = "appsecret"; // Use your app secret here

   // decode the data
   $sig = base64_url_decode($encoded_sig);
   $data = json_decode(base64_url_decode($payload), true);

   // confirm the signature
   $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
   if ($sig !== $expected_sig) {
      error_log('Bad Signed JSON signature!');
      return null;
   }

   return $data;
}

function base64_url_decode($input) {
   return base64_decode(strtr($input, '-_', '+/'));
}

To answer the original question
To get data from the signed_request, include the functions above and...
$data = parse_signed_request($_POST['signed_request']);

echo '<pre>';
print_r($data);

A:

I think it failed at json_decode($json) because $json is not a valid json string, as you've mentioned in comment about print_r($_POST['signed_request']);.
According to Facebook - Authentication within a Canvas Page Document, the signed_request parameter is encoded and, parsing the signed_request string will yield a JSON object.
if you're using the PHP SDK, just as Abhishek said in the comment, $facebook->getSignedRequest(); will give you the decoded json.
look here for more details on the Signed Request


Q:

React material UI form validation using error and helperText

I have created a form on which I want to validate the inputs and I saw the material UI have an attribute called error boleean and another attribute called helperText for TextField input of the form but I didn't found nothing about how to inject that error on element when the validation conditon is not fulfiled

here is my code example: https://codesandbox.io/s/material-demo-hip84?file=/demo.js:1020-1055
const [form, setForm] = useState({ name: "", email: "", remember: "" });

  const onChange = i => {
    setForm({ ...form, [i.target.name]: i.target.value });
  };

  const handleSubmit = e => {
    e.preventDefault();
    console.log(form);
    e.target.reset();
  };

  return (
    <form className={classes.root} autoComplete="off" onSubmit={handleSubmit}>
      <Grid container spacing={4}>
        {Object.keys(form).map((objKey, idx) => {
          return (
            <Grid item xs={12} sm={6} md={4} key={idx}>
              <TextField
                error
                helperText="No Value added in this field"
                id={`input${idx}`}
                label={objKey}
                name={objKey}
                fullWidth={true}
                onChange={onChange}
              />
            </Grid>
          );
        })}
        <Grid item xs={12} sm={12} md={12}>
          <Button type="submit" variant="contained" color="primary">
            Submit
          </Button>
        </Grid>
      </Grid>
    </form>
  );

A:

To use the error prop of the TextField you will need to manage the errors on your own (just like you manage the value for your fields).
To do that - the value of error should not be fixed, but should be true/false, based on some calculation that you are doing.
I used your code to do the checking if the value (for each field) equals specific value. This is not a real-life example, and you probably want to change this to some kind of a regex check, but this should give you a good starting point:
export default function SubmitForm() {
  const classes = useStyles();
  const [form, setForm] = useState({ name: "aaa", email: "bbb", remember: "ccc" });
  const isValidData = {name: "aaa", email: "bbb", remember: "ccc"};

  ...

  const checkIsValid = (fieldName, value) => {
    // Here you probably what to check this to some regex validation
    if (isValidData[fieldName] === value) {
      return true;
    }
    return false;
  }

  return (
        ...
        {Object.keys(form).map((objKey, idx) => {
          return (
            <Grid item xs={12} sm={6} md={4} key={idx}>
              <TextField
                error={!checkIsValid(objKey, form[objKey])}
                ...
              />
            </Grid>
          );
        })}
  );
}

To see the complete working example please check this: https://codesandbox.io/s/mui-textfield-control-errors-z0tfo?file=/demo.js


Q:

Laravel : How to update boolean value using foreign key in a table

here is my database table I want to work with I want to update the participation column of form_submissions table with boolean 1 by using the user_id
here is mycontroller
 public function update($id)
    {
        $submission = Form_Submission::find($id);
        $submission->participation=1;
        $submission->save();
        return back();
    {

I got the user_id from the link using a button and passed it to the function
can someone tell me how I can update the above record using user_id?

A:

Having user_id, you can retrieve that specific Form_Submission using where, like this:
Form_Submission::where('user_id', $user_id)->get();

Resource for this: https://laravel.com/docs/7.x/queries#where-clauses
Also, to update it, you can use where - update, like this:
Form_Submission::where('user_id', $user_id)->update(['participation' => 1]);

Resource for this: https://laravel.com/docs/7.x/queries#updates
Hope this helps!


Q:

how can I get rid of GPT if I want to install single boot Ubuntu

I have got my new laptop and want to install Ubuntu 14.04 on it(single boot system) from usb live disk. Since my disk is less than 1 TB, I want to have legacy boot and non-GPT partition. What can I do for this? Thanks in advance.

A:

This problem is because of buggy BIOS firmware of the laptop I was working on, ThinkPad 440p. Downgrading its BIOS (to version 1.14) solved the problem as people pointed out in this link: problem with ThinkPad 440p


Q:

LDAP Syntax/Semantics: Filter vs. Base DN?

This is probably pretty stupid, but I'm still green to LDAP. So I hope someone can lend me a hand.
I am using Apache Directory Studio to do my searches and I am confused about when I should be using a filter or when I should be breaking up my filter into two, using one part as the filter and the other as my search base.
Here's an example where I'm trying filter out a group.
Filter: CN=JohnTestGroup,OU=TECH,DC=lab,DC=ing
Base:   DC=lab,DC=ing

This yielded zero results. I realized that perhaps I am being redundant as part of the base is in the filter, so I got rid of that part in the filter.
Filter: CN=JohnTestGroup,OU=TECH
Base:   DC=lab,DC=ing

This still did not yield anything. So I tried this:
Filter: CN=JohnTestGroup
Base:   OU=TECH,DC=lab,DC=ing

I moved the OU parameter into the Base. This worked, but I don't understand why the first or second attempts didn't. Someone care to drop some knowledge on me?
This is probably a matter of syntax/semantics, so if anyone could point me to a resource, I'd be more than willing to read more about it.

A:

I think you are misunderstanding how the filter works.  It is meant to be key=value pairings.
So (objectClass=iNetOrgPerson) as an example.
If you wish a filter to find a DN, then you pick an identifying chracteristic like CN, and filter (CN=JohnTestGroup) or perhaps (mail=John@mail.net).
The base tells the LDAP server where to start looking, as seriyPS notes in his/her answer, the SCOPE is the next question.  How deep should the server search, as that adds overhead and performance issues. Subtree is simplist conceptually.  Just keep looking from here down, till you run out of tree to look through.
That is why your last one works.
Now, if you want to find a specific object and you know its DN, you do an ENTRY scope query for the base of the specific DN.


Q:

How to see git stash modification when it was done by git stash push filename

I stash few files earlier by git stash push file_path. Now I can see them as list as by
git stash list
stash@{0}: WIP on web_09_11: a6c038e7 Merged PR 25503: Get latst commites
stash@{1}: WIP on web_09_11: a6c038e7 Merged PR 25503: Get latst commites
stash@{2}: WIP on web_09_11: a6c038e7 Merged PR 25503: Get latst commites
stash@{3}: WIP on web_09_11: a6c038e7 Merged PR 25503: Get latst commites

I want to see the content of each stash. I found that it should show if I try

git stash show stash@{1}
But it gives me error as:
  fatal: ambiguous argument 'stash@': unknown
  revision or path not in the working tree. Use '--' to separate paths
  from revisions, like this:
Or Too many revisions specified: 'stash@' 'MQA=' 'xml' 'text'

how can I see it?

A:

This is a shell issue : use quotes around 'stash@{xx}'
git show 'stash@{1}'

In Powershell for example : { cmd1; cmd2 } defines a script block
Here is an example of what I get :
> echo stash@{1}
stash@
1
> echo 'stash@{1}'
stash@{1}


Q:

Issue with the checkbox that duplicate the check with bootstrap for Ember.js

when I click on a checkbox, for Monday for example, the checbox is validated, but all the other Monday, for each element are validated.
I'll show you the template, that can be more clear for you.

When I click on Monday, the check is validated for both, and the value inside the js is validated for both.
Here is the Handlebars.js templates that define the page. This file is shedule-timeframe.hbs.

{{#if timeframe}}
    {{log "monday " timeframe.enabledOnMonday}}
    {{log "start " timeframe.startTime}}

            {{form.element controlType='checkbox' label=(t 'schedule.monday')
                           property="enabledOnMonday" value=timeframe.enabledOnMonday}}
            {{form.element controlType='checkbox' label=(t 'schedule.friday')
                           property="enabledOnFriday" value=timeframe.enabledOnFriday}}

            {{form.element controlType='checkbox' label=(t 'schedule.tuesday')
                           property="enabledOnTuesday" value=timeframe.enabledOnTuesday}}
            {{form.element controlType='checkbox' label=(t 'schedule.saturday')
                           property="enabledOnSaturday" value=timeframe.enabledOnSaturday}}

            {{form.element controlType='checkbox' label=(t 'schedule.wednesday')
                           property="enabledOnWednesday" value=timeframe.enabledOnWednesday}}
            {{form.element controlType='checkbox' label=(t 'schedule.sunday')
                           property="enabledOnSunday" value=timeframe.enabledOnSunday}}

            {{form.element controlType='checkbox' label=(t 'schedule.thursday')
                           property="enabledOnThursday" value=timeframe.enabledOnThursday}}

        {{#form.element label=(t 'schedule.start_time')}}
            {{input type='text' placeholder='13:37'value=(mut timeframe.startTime) class='form-control'}}
        {{/form.element}}

        {{#form.element label=(t 'schedule.end_time')}}
            {{input type='text' placeholder='18:42'value=(mut timeframe.endTime) class='form-control'}}
        {{/form.element}}

{{/if}}

And here, this where I call this templates. This file is shedule-form.js. You can see that I call the file schedule-timeframe.hbs at the line 20.

{{#bs-form formLayout="horizontal" model=schedule as |form|}}

    <legend>{{t 'timeframes'}}</legend>

                {{bs-button defaultText=(t 'add') type='success' onClick=(action                'addTimeframe')}}

                {{bs-button defaultText=(t 'submit') type="primary" onClick=action      buttonType="submit"}}

            {{#each schedule.timeframes as |tf|}}
                {{log "tf " tf}}

                        {{schedule-timeframe form=form timeframe=tf model=tf}}

                        {{bs-button defaultText=(t 'remove_selected') type='danger'
                                    onClick=(action 'removeTimeframe')}}

            {{/each}}

{{/bs-form}}

tldr: I have an issue with the checbox that duplicate when I click on one of them, for same value, but on different [timeframe].

A:

So I solve it by creating my own onChange!

{{form.element controlType='checkbox' label=(t 'schedule.monday')
                           value=(mut timeframe.enabledOnMonday)
                           onChange=(action (mut timeframe.enabledOnMonday))}}

With this onChange, I can set the value of each timeframe.


Q:

Modify grep results to print a particular word from a match string

I have a grep ouput which looks as follows:
Path to log files = /data/db2inst1/NODE0000/SQL00001/LOGSTREAM0000/
Database is in write suspend state = YES
Path to log files = /data/db2inst1/NODE0001/SQL00001/LOGSTREAM0001/
Database is in write suspend state = NO

I want to edit this as follows:
Node = NODE0000
Database is in write suspend state = YES
Node = NODE0001
Database is in write suspend state = NO

Is that possible?

A:

You don't need to keep pipelines of grep to generate the output you are looking for. Awk is a bit powerful than grep in a way it allows you to do transformation on the text that you've matched, which is quite powerful. So with that, all you need for your example would be
awk '/Path to log files/{match($0,/NODE([^/]+)/,a); printf "Node = NODE%s\n",a[1];next}
    /Database is in write suspend state/' file


Q:

feathers-authentication-hooks: restrictToRoles for a user with more then one role

I have implemented feathers-authentication-hooks in my project and it is working verifying against a custom user column containing a role. Now I want to have it working with more then one role per user. I've trying several formats in the database column, but all have failed:
Data formats (exact format per line):

role1, role2
role1; role2
[role1,role2]
{"column_name": ["role1","role2"]}
does someone know what I need to do?

A:

Most hooks in that package can be implemented manually often with the same amount of code and less time than it takes to read the documentation. In this case for your example with a custom hook like this:
const { Unauthorized } = require('feathers-errors');

return function() {
  return function(context) {
    if(context.params.user.roles.indexOf('admin') === -1) {
      throw new Unauthorized('You are not allowed to access this');
    }
  }
}


Q:

Can we add how to disable syntax highlighting to the editing help (FAQ)?

Syntax highlighting for code has a long section about syntax highlighting but it fails to mention how to disable it.
I guess one can use "lang-none" as a language code (it's listed in Interface options for specifying language prettify):
<!-- language: lang-none -->

Is this correct?
I think it should be added to the FAQ. It's a special case, i.e. non-obvious.

A:

That's a great idea; I've added it to the Markdown help page (will be visible after the next deploy).

A:

That's correct. It would be worth adding to the help page I think.
See also Syntax highlighting language hints for the full list of highlighting options.


Q:

Do minor syntax error edit suggestions get rejected and discouraged?

I was looking at a useful answer and found a minor ternary operator syntax error which I suggested an edit for:
// Error: Uncaught SyntaxError: Unexpected token :
num = typeof(num) == 'number' && num % 1 === 0 : num : 0;
                                               ^
// Fix:
num = typeof(num) == 'number' && num % 1 === 0 ? num : 0;

Of course, edits must be at least 6 characters, so I had to do some minor format changes. (like adding <!-- language: lang-js --> or <!-- language: lang-none -->)
But my edit was immediately rejected by the first reviewer, even though I mentioned in the edit comment:
fix syntax error for num ternary operator

So it left me wondering, do minor syntax error edit suggestions get rejected and discouraged?

A:

No.
This edit is fine, and it shouldn't have gotten a reject vote in my opinion.
However, sometimes, such edits do get rejected. There might be plenty reasons, such as the reviewers not being knowledgeable on the subject (bad reason, they should filter their queue), mistaking an answer for a question (obviously, you shouldn't edit out errors in questions), accidentally miss-clicking, etc.
Don't be discouraged by reject votes or rejected edits. Instead, read and ask on meta if what you're doing is okay, and keep up the good work.


Q:

Random numbers in Java when working with Android

I need to make a random number between 1 and 20, and based on that number (using "If - Then" statements), I need to set the image of an ImageView.
I know that in Objective-C, it goes like this:
int aNumber = arc4Random() % 20;
if (aNumber == 1) {
    [theImageView setImage:theImage];
}

How can I do this in Java? I have seen it done this way, but I do not see how I can set the range of numbers (1-20, 2-7, ect).
int aNumber = (int) Math.random()

A:

Docs are your friends
Random rand = new Random();
int n = rand.nextInt(20); // Gives n such that 0 <= n < 20

Documentation:

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.
  Thus, from this example, we'll have a number between 0 and 19

A:

Math.random() returns an double from [0,1[.
Random.nextInt(int) returns an int from [0, int[.

A:

You can try:
int aNumber = (int) (20 * Math.random()) + 1;

or
Random rand = new Random();
int n = rand.nextInt(20) + 1;


Q:

How to set onclick event in yii custom radio button?

This is my Html for custom radio button in yii2
<?php
     echo $form->field($ProductShipping, 'id_shipping')->radioList(
          ['1'=>'Free', '2'=>'Pickup','3'=>'Country Wise','4'=>'API'],
              ['item' => function($index, $label, $name, $checked, $value) {

               $return = '';
               $return .= '<input type="radio" name="' . $name . '" value="' . $value . '">';
               $return .= '' . ucwords($label) . '';
               $return .= '';
               return $return;
             }
           ]
         )->label(false);

?>

How to set an onclick event in this custom radio button?

A:

You could implement it following way:
<?php
     echo $form->field($ProductShipping, 'id_shipping')->radioList(
          ['1'=>'Free', '2'=>'Pickup','3'=>'Country Wise','4'=>'API'],
              ['item' => function($index, $label, $name, $checked, $value) {
               $return = '';
               $return .= '<input type="radio" name="' . $name . '" value="' . $value . '">';
               $return .= '' . ucwords($label) . '';
               $return .= '';
               return $return;
             },
               'onclick' => "alert('test')"
           ]
         )->label(false);

?>


Q:

fork() bomb explanation in terms of processes?

I am just wondering how a fork bomb works, I know that there are similar questions but the answers aren't quite what I am looking for (or maybe I just haven't been able to come across one)
How does it work in terms of processes?
Do children keep being produced and then replicating themselves? is the only way to get out of it is by rebooting the system?
Are there any long lasting consequences on the system because of a fork bomb?
Thanks!

A:

How does it work in terms of processes?

It creates so many processes that the system is not able to create any more.

Do children keep being produced and then replicating themselves?

Yes, fork in the name means replication.

is the only way to get out of it is by rebooting the system?

No, it can be stopped by some automated security measures, eg. limiting the number of processes per user.

Are there any long lasting consequences on the system because of a fork bomb?

A fork bomb itself does not change any data but can temporarily (while it runs) cause timeouts, unreachable services or OOM. A well-designed system should handle that but, well, reality may differ.


Q:

C++ - assignment to 'this' anachronism

I was given this code and asked to state what was wrong with it, and how to fix it. The code gives me an error something like c++ assignment to this anachronism, and I'm not sure what this means.
I am new in C++ and I don't know what to do here. Please help. Here is the code in question:
class SELF
{
  private:
    SELF * me;
  public:
     SELF()
     {
          this = me;
     }
 };

How can I assign the value

A:

This is a C++ construct that was removed from the language over 30 years ago. It's from the early days of cfront in mid-80s and you could still find compilers that did things this way until the very early 90s. It's been replaced with operator new. I wrote some of my very first C++ code (a complex class for a Mandlebrot set generator) on a compiler that worked this way.
You didn't originally give enough context here to know how to fix the problem in this case. There is no trivial transformation that can be prescriptively applied to all situations.
The construct was initially created so that you could allocate memory for the object in the constructor. If you assigned to this in the constructor, the compiler wouldn't allocate memory for your object when you created it, it would assume that you did it yourself in the constructor.
In a comment, you stated that this was directly copied from a university assignment, and I bet not even your professor is aware of this old construct, the solution is probably to simply say me = this; instead of this = me;.
But the reason your compiler is calling this an 'anachronism' is that it is.
For anybody who is interested in the history, the original construct can be seen on page 42 of the manual for cfront version 'E'.


Q:

Cygwin tmux: "failed to connect to server: No error"

Just as the title says, whenever I try to start tmux in Cygwin 64-bit (Win7), with any or no arguments besides --help, I get the following error:
$ tmux
failed to connect to server: No error

I can't reproduce this on Linux. Any help would be greatly appreciated.
Thanks!

A:

This works for me too on 32-bit Win7. But I need to delete the directory every time before launching tmux so I just added an alias to .bashrc.
alias tmux='rm -rf /tmp/tmux* && tmux'

A:

The alias method suggested by bender doesn't really work if you're trying to reattach, because it kills the existing session(s). The following seems to have solved the problem for me:

Save the Perl script at http://pastebin.com/nN6zX37K to "~/bin/tmux" or elsewhere in your path, ahead of /usr/bin.
Give it execute permissions: "chmod +x ~/bin/tmux".
Exit and reopen Cygwin.
Run tmux commands normally.

This works because it detects the state where tmux has closed entirely but did not remove its temporary directory, which it solves by removing the temp directory (as suggested by bender), but then runs the desired command.


Q:

ASG can't launch instances anymore with encrypted EBS root volume

We have recently deployed a new application that uses an ASG configured to launch instances with encrypted EBS root volumes. We have plenty of existing applications that work using exactly this setup, but our new ASG refuses to launch instances. The instances don't even appear and we see an error in the ASG activity history: Client.InternalError: Client error on launch.
After experimenting, we've discovered that if we swap the AMI we are using for one that isn't encrypted it all starts working as expected. Confusingly we are using exactly the same AMI on a different ASG and it's all working as expected (formed from almost identical CloudFormation templates). Likewise we can launch an EC2 instance directly from the console using the same AMI and instance profile.
Has anyone seen this behaviour before?
I've found some solutions elsewhere (that led us to prove it was something to do with the encrypted volume) such as this from AWS but they don't seem to directly relate to our scenario.

A:

We eventually found an AWS forum post that details Service Linked Roles (SLRs). It seems that sometime in the last couple of months they have changed the way that ASGs behave (for newly created ASGs only). Previously an ASG could use any KMS CMK, but this has been changed so that it can only access the default key. We're using a "customer managed" CMK so our newly created ASG can no longer access it by default.
Apparently this will be changed on existing ASGs towards the end of June.
In order to fix this we set about creating a new SLR with access to our key but later discovered that CloudFormation doesn't yet allow you to specify an SLR for an ASG.
In the meantime we've decided to essentially create the situation we had before by changing the policy on our CMK to allow access from the default SLR.
The CloudFormation we use to create our CMK now looks like this:
KmsKey:
  Type: AWS::KMS::Key
  DeletionPolicy: Retain
  Properties:
    Description: Used to encrypt AMIs
    EnableKeyRotation: True
    KeyPolicy:
      Version: 2012-10-17
      Id: ami-kms-key
      Statement:
      - Sid: Enable IAM User Permissions
        Effect: Allow
        Principal:
          AWS: !Sub arn:aws:iam::${AWS::AccountId}:root
        Action: kms:*
        Resource: "*"
      - Sid: Allow use of the key by the default service linked role
        Effect: Allow
        Principal:
          AWS:
          - !Sub arn:aws:iam::${AWS::AccountId}:role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling
        Action:
        - kms:Encrypt
        - kms:Decrypt
        - kms:ReEncrypt*
        - kms:GenerateDataKey*
        - kms:DescribeKey
        Resource: "*"
      - Sid: Allow attachment of persistent resources
        Effect: Allow
        Principal:
          AWS:
          - !Sub arn:aws:iam::${AWS::AccountId}:role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling
        Action:
        - kms:CreateGrant
        Resource: "*"
        Condition:
          Bool:
            kms:GrantIsForAWSResource: true


Q:

Django and Google App Engine Helper not finding the ipaddr module

I'm trying to get Django running on GAE using this tutorial.
When I run python manage.py runserver I get the stacktrace below. I'm new to both django and python so I don't know what my next steps are (This is Ubuntu Jaunty btw). It seems django isn't finding the GAE module ipaddr which comes with SDK 1.3.1.
How do I get django to find this module?
/home/username/bin/google_appengine/google/appengine/api/datastore_file_stub.py:40: DeprecationWarning: the md5 module is deprecated; use hashlib instead
  import md5

/home/username/bin/google_appengine/google/appengine/api/memcache/__init__.py:31: DeprecationWarning: the sha module is deprecated; use the hashlib module instead
  import sha
Traceback (most recent call last):
  File "manage.py", line 18, in <module>
    InstallAppengineHelperForDjango()
  File "/home/username/Development/GAE/myapp/appengine_django/__init__.py", line 543, in InstallAppengineHelperForDjango
    InstallDjangoModuleReplacements()
  File "/home/username/Development/GAE/myapp/appengine_django/__init__.py", line 260, in InstallDjangoModuleReplacements
    import django.db
  File "/home/username/Development/GAE/myapp/django/db/__init__.py", line 57, in <module>
    'TIME_ZONE': settings.TIME_ZONE,
  File "/home/username/Development/GAE/myapp/appengine_django/db/base.py", line 117, in __init__
    self._setup_stubs()
  File "/home/username/Development/GAE/myapp/appengine_django/db/base.py", line 128, in _setup_stubs
    from google.appengine.tools import dev_appserver_main
  File "/home/username/bin/google_appengine/google/appengine/tools/dev_appserver_main.py", line 82, in <module>
    from google.appengine.tools import appcfg
  File "/home/username/bin/google_appengine/google/appengine/tools/appcfg.py", line 53, in <module>
    from google.appengine.api import dosinfo
  File "/home/username/bin/google_appengine/google/appengine/api/dosinfo.py", line 25, in <module>
    import ipaddr
ImportError: No module named ipaddr

A:

http://code.google.com/p/ipaddr-py/
To install.
Information about issue:
http://code.google.com/p/google-app-engine-django/issues/detail?id=161#c3
From google:
> Hi, just apply this patch from: http://code.google.com/p/google-app-engine-
django/source/detail?r=102

-------

Log message

Adds new dependency, ipaddr, from SDK
Affected files     expand all   collapse all
    Modify  /trunk/appengine_django/__init__.py diff
...
129 129             SDK_PATH,
130 130             os.path.join(SDK_PATH, 'lib', 'antlr3'),
131 131             os.path.join(SDK_PATH, 'lib', 'django'),
132 +           os.path.join(SDK_PATH, 'lib', 'ipaddr'),
132 133             os.path.join(SDK_PATH, 'lib', 'webob'),
133 134             os.path.join(SDK_PATH, 'lib', 'yaml', 'lib'),
134 135         ]

A:

It happens also with  app-engine-patch
The solution is to add $GOOGLE_APP_ENGINE/lib/ipaddr to your pythonpath, as you must have done with other dependencies like antlr3 or yaml.


Q:

Is it possible to override a driver that has been compiled into the kernel?

I have a USB device for which I have an API.  This API only works if the USB device doesn't use the ftdi_sio/usbserial drivers.
On my laptop, if I plug the USB device in, these drivers get loaded (as modules) and I have to unload them using modprobe -r after which code using the API can see the device.
I have another device which experiences the same issue although no modules are loaded so I'm guessing these drivers are compiled into the kernel.  My question is this - is there any way to stop this device from using these drivers or do I have to recompile the kernel, etc?
Thanks for any help!

A:

You are essentially looking for a way to :

unbind the default driver from your USB device
and
bind a driver of your choice to it.

Take a quick look at this to get you started.
A slightly more detailed description of the same is available in this excellent LWN article of (un)binding device drivers.


Q:

Using a Sprite Image for Search Box Input Button

EDIT: You can see the search box live here.
Before I explain, let me show you the code I am using:
HTML
<div class="SiteSearch">
    <form action="/search" id="searchform" method="get">
        <input x-webkit-speech="" autocomplete="off" type="text" id="gText" name="q" id="q" onblur="if (this.value == '') {this.value = 'Search';}" onfocus="if (this.value == 'Search') {this.value = '';}" value ='' "search" placeholder="Search.."/>
        <input type="submit" id="gBtn"/>
    </form>
</div>

CSS
#Head .SiteSearch {
  top: 12px;
  right: 0;
}

#Head .SiteSearch {
  float: right;
  position: relative;
}

input#gText {
  float: left;
  width: 225px;
  height: 23px;
  line-height: 24px;
  text-indent: 5px;
  font-family: arial,sans-serif;
  font-size: 1em;
  color: #333;
  background: white;
  border: solid 1px #D9D9D9;
  border-top: solid 1px silver;
  border-right: none;
  vertical-align: middle;
  -webkit-appearance: none;
  -webkit-border-radius: 0px;
}

#searchform #gBtn {
  background-image: url('search.png');
  width: 31px;
  height: 27px;
}

#gBtn {
  vertical-align: middle;
  cursor: pointer;
  width: 40px;
  height: 31px;
  line-height: 100%;
  padding: 0;
  font-size: 0;
  text-indent: -999px;
  color: transparent;
  background-position: 0 0;
  border: none;
  -webkit-appearance: none;
  -webkit-border-radius: 0px;
}

input#gBtn:hover {
  background-position: 31px 0;
  border: none;
}

This is how the search box looks on IE7 vs. IE8/IE9:
 vs.
As you can see above, the input button image isn't being shown in IE7. How can I fix this?
Any help is appreciated. Thanks!

A:

I fixed it by modifying the CSS code like so:
#Head .SiteSearch {
  top: 12px;
  right: 0;
}

#Head .SiteSearch {
  float: right;
  position: relative;
}

input#gText {
  float: left;
  width: 225px;
  height: 23px;
  line-height: 24px;
  text-indent: 5px;
  font-family: arial,sans-serif;
  font-size: 1em;
  color: #333;
  background: white;
  border: solid 1px #D9D9D9;
  border-top: solid 1px silver;
  border-right: none;
  vertical-align: middle;
  -webkit-appearance: none;
  -webkit-border-radius: 0px;
}

/* REMOVED THIS PIECE
  #searchform #gBtn {
  background-image: url('search.png');
  width: 31px;
  height: 27px;
}*/

#gBtn {
  vertical-align: middle;
  cursor: pointer;
  width: 40px;
  height: 31px;
  line-height: 100%;
  padding: 0;
  font-size: 0;
  text-indent: -999px;
  color: transparent;
  background-image: url('search.png'); /* ADDED */
  background-position: 0 0;
  border: none;
  -webkit-appearance: none;
  -webkit-border-radius: 0px;
}

input#gBtn:hover {
  background-image: url('search.png'); /* ADDED - BUT OPTIONAL */
  background-position: 31px 0;
  border: none;
}


Q:

Show that exactly one of the following two systems has a solution.

Let A be a $m \times n$ matrix, $\mathbf{c}$ an $n$-dimensional ector and $\mathbf{b} \ge \mathbf{0}$ an $m$-dimensional vector. Show that exactly one of the following two systems has a solution:
  $\begin{align*}
1. \ Ax \le z, \mathbf{c}^tx \gt \mathbf{d}^tz, x \ge \mathbf{0}, z \le \mathbf{0}, x \in \mathbb{R}^n, z\in \mathbb{R}^m
\end{align*}$
  $\begin{align*}
2. \ A^t y \ge c \, , y\ge \mathbf{d} \, , y\in \mathbb{R}^m
\end{align*}$
  I usually put here what I've done so far, but in this case I only know what I should do instead of some concrete calculations.

That statement above looks pretty similar to Farka's lemma, and I've seen some corollaries that are consequences of Farka's lemma whose proofs consist in some modifications on the matrix of the formulation of Faka's lemma. However, I don't know how I should modify the matrix so the exercise follows. Any help will be highly appreciate and thanks in advance!
By the way, I don't know if the tags are accurate so feel free to edit them.

A:

We can rewrite (2) as $By \leq a$, where
$$
B = \begin{bmatrix}
-A^t \\ -I
\end{bmatrix}
\text{ and }
a = \begin{bmatrix}
-c \\ -d
\end{bmatrix}
$$
By this question, this system has a solution if and only if $y \geq 0, y^t B = 0, y^t a < 0$ has no solution $y$. So now, we just need to show that this system is equivalent to (1).
If we let $y = \begin{bmatrix} y_1 \\ y_2 \end{bmatrix}$ and expand the definition of $A$ and $b$, then the system looks like this:
$$
y_1 \geq 0, y_2 \geq 0, \qquad
y_1^t (-A^t) + y_2^t (-I) = 0, \qquad
y_1^t (-c) + y_2^t (-d) < 0
$$
We can simplify this to:
$$
y_1, y_2 \geq 0, \qquad
A y_1 + y_2 = 0, \qquad
c^t y_1 + d^t y_2 > 0
$$
Now, if we replace $y_1$ by $x$ and $y_2$ by $-z$, we get (1)!


Q:

CASE statement still returning multiple rows

the following query is returning two rows per ID.
select distinct ID,
count (COURSE_IDENTIFICATION) as tot_course_id,

COUNT(case when course_level = 'G'
     then (COURSE_IDENTIFICATION)
     else '0'end) count_grad,

COUNT (case when course_level = 'U'
       then (COURSE_IDENTIFICATION)
       else '0'end) count_under

from ods.STUDENT_COURSE

where ACADEMIC_PERIOD = '201890'
and COURSE_BILLING_CREDITS >0.0
group by ID, course_level
order by 1

I receive the following results:
ID      |TOT_COURSE_NUM |COUNT_GRAD |COUNT_UNDER
-------------------------------------------------
12345   |1              |1          |1
12345   |2              |2          |2

Is there any way to ensure both grad and undergrad totals are counted in the same row?

A:

Your immediate problem is that course_level is in the group by.  A secondary problem is that the count() is incorrect.  I think this should be sufficient:
select ID,
       count(*) as tot_course_id,
       sum(case when course_level = 'G' then 1 else 0 end) as count_grad,
       sum(case when course_level = 'U' then 1 else 0 end) as count_under
from ods.STUDENT_COURSE sc
where ACADEMIC_PERIOD = '201890' and
      COURSE_BILLING_CREDITS > 0.0
group by ID
order by 1;

count(<expression>) counts the number of non-NULL values.  Your else '0' is still non-null, so it gets counted.  sum() is a simple way to take care of this.
This version assumes that COURSE_IDENTIFICATION is not NULL.  That seems like a reasonable assumption in a table called STUDENT_COURSE.  It is easily modified to handle NULL values.
And, select distinct is almost never appropriate with group by.

A:

In your group by statement, you are specifying course_level.  Remove course_level from your group by statement and it should consolidate the rows.


Q:

Why does Xcode 11 attribute selector for colors have 2 different colors in the thumbnail?

Here is an image of the color selector in the attribute inspector of Xcode 11.x. I could not figure out why a lot of the color thumbnails show 2 colors. I suspected that the pair of colors indicate the Light and Dark Modes but this does not seem to be the case.

A:

Those colors have an opacity less than 100%.
The left side is what we see when the color is on black background. The right side is on white background.


Q:

Intent custom permission not working

UPDATE
My immediate problem is solved as per my answer below. My environment (PC + devices) does not allow custom permissions in DEBUG builds.
I'm convinced I was able to run DEBUG builds fine a few weeks ago - hence the description of an "intermittent" error.
UPDATE 2
The code synced out on a different developer's machine, works fine on his device in DEBUG mode through Eclipse. On my devices, it does not work from his machine.
Also the DEBUG build from my machine works fine on this other device.
This leads me to question if something has gone wrong on my devices?

I have an intermittent "Permission Denial" problem with custom permission Intents. It's one of those where the code is in production and works, but sometimes when making new builds, it stops working. I have only managed to fix it by luck before, through a process of reboot (device & pc), clean project, uninstall/reinstall, repeat etc... this is unacceptable.
As far as I can see I am doing everything correct for custom permissions on my Intents that I am broadcasting within my app. But logcat is giving me the usual errors of:

W/BroadcastQueue(  389): Permission Denial: broadcasting Intent { act=A_ACTION flg=0x10 } from com.test (pid=22030, uid=10002) requires A_PERMISSION due to registered receiver
BroadcastFilter{43918d50 u0 ReceiverList{4391cad8 22030 com.test/10002/u0 remote:430576d0}}

on 4.2.1 (Galaxy Nexus) & 4.2.2 (Nexus 7), or

W/ActivityManager( 2002): Permission Denial: receiving Intent { act=A_ACTION flg=0x10 } to ProcessRecord{41a12748 31496:com.test/10115} (pid=31496, uid=10115) requires A_PERMISSION due to sender com.test (uid 10115)

on 4.0 (S2) & 2.3.3 (Samsung Ace).
i.e. standard errors.

My MANIFEST says:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test"
    android:versionCode="1"
    android:versionName="4.10.0.3" >

    <permission
        android:name="A_PERMISSION"
        android:description="@string/broadcast_permission_desc"
        android:label="@string/broadcast_permission_label"
        android:permissionGroup="@string/broadcast_permission_group"
        android:protectionLevel="signature" />

    <uses-permission android:name="A_PERMISSION" />

    etc.....

Those STRINGS are defined as (fwiw):
<string name="broadcast_permission_label">Private Broadcast</string>
<string name="broadcast_permission_desc">This permission allows the necessary components of the application to receive private broadcasts that are sent within the application.</string>
<string name="broadcast_permission_name">A_PERMISSION</string>
<string name="broadcast_permission_group">A_GROUP</string>

I have a method in my base APPLICATION subclass that I use to do the broadcasting:
public void sendBroadcast(Intent i)
{
    // hardcoded custom permission
    super.sendBroadcast(i, "A_PERMISSION");
}

I REGISTER for my BroadcastReceiver from within a Fragment like this:
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    // hardcoded custom permission
    MyApp.getInstance().registerReceiver(myReceiver, myFilter,
        "A_PERMISSION", null);
}

I have checked the following related questions without joy:

Android Permission Denial: broadcasting Intent
How to use custom permissions in Android?
how to declare user defined permissions in android

I think that covers similar questions on this site.
My problem is that its intermittent but wastes lots of time i.e. some builds work on all phones, some builds fail on all phones.
I wonder if this is an issue in one of the frameworks (either Android OS, or perhaps Eclipse / Android SDK). Unfortunately my googling only leads me to the more common issues with the common solutions.

A:

Final Solution - I agree it doesn't seem to make sense, but here it is:
I have 2 apps using the same permission - com.test and com.runtest.
As above, com.test was broken for DEBUG builds. But I noticed that com.runtest was still working.

Steps:

installed com.runtest to confirm it was working
uninstalled both apps from my devices
renamed com.runtest to com.test - in Eclipse (Android Tools...
Rename Application Package)
debugged this renamed app in Eclipse on my device - it worked
deleted this renamed "fake" com.test
debugged the original com.test app in Eclipse on my device - it
finally worked!

So for some reason, overwriting the broken app with a working app changed something, and fixed my device.


Q:

Bash script to ensure only one instance of a script running & others waiting

I have a bash script runner.sh which invokes another script.sh. script.sh is invoked only from runner.sh. I can have only one instance of script.sh executing at a time. If multiple invocations of runner.sh is made then runner.sh should make all the caller's wait if script.sh is already running. Once script.sh is completed then it will  allow one of the waiting callers to execute script.sh.
Can someone suggest some ways of achieving this?

A:

From man flock:

[ "${FLOCKER}" != "$0" ] && exec env FLOCKER="$0" flock -en "$0" "$0"
"$@" || :
This is useful boilerplate code for shell scripts. Put it at
the top of the shell script you want to lock and it'll automatically
lock itself on the first run. If the env var $FLOCKER is not set to
the shell script that is being run, then execute flock and grab an
exclusive non-blocking lock (using the script itself as the lock file)
before re-execing itself with the right arguments. It also sets the
FLOCKER env var to the right value so it doesn't run again.

Put this on top of ./script.sh (or on top of runner.sh) and your're good to go.


Q:

MLE of variance

$f(x) = \theta x^{-(1+\theta)}$ for $x>1$. What is the MLE of the population variance.
I am not sure how I'm supposed to approach this problem. What would be a first step for this?

A:

Consider the log likelihood function
$$\ell(\theta)=\sum_{i=1}^n \ln(\theta) - (1+\theta)\ln(x_i).$$
Then, computing the partial derivative,
$$\frac{\partial\ell(\theta)}{\partial \theta}= \frac{n}{\theta} - \sum_{i=1}^n \ln(x_i)=0.$$
Thus,
$$\hat{\theta}=\frac{1}{\frac{1}{n}\sum\limits_{i=1}^n\ln(x_i)},$$
which is, of course, one over the sample mean of the log sample.
Just compute the variance of the random variable with your given pdf $f(x)$ (compute the integrals $E[X]=\int_1^\infty xf(x)dx$ and $E[X^2]=\int_1^\infty x^2f(x)dx$) and then use the above estimator.


Q:

Get values from json in different format

This is my API response...
{
    "organizations": [
        {
            "id": 12345,
            "name": “products1",
            "parentId": null,
            "plantId": 28768,
            "type": 1
        },
        {
            "id": 76532,
            "name": “products2",
            "parentId": 4270947,
            "plantId": null,
            "type": 2
        }
    ]
}

Now since I have some issues with connectivity and so cannot call the API, get the response and parse, I have hard-coded the above response in my code like so..
var jsonObject = [String : [[String : Any?]]]()

jsonObject = [
    "organizations":[

    ["id": 12345, “name”: “products1”, “parentId”:”null”,"plantID”:28768,”type”:1],
    ["id": 76532, “name”: “products1”, “parentId”:”null”,"plantID”:28768,”type”:1]

    ]

]

And I parse this data and insert it into database like so...
let organizationLists = Organization()

guard let jsonArray = jsonObject as? [String : [[String : Any?]]] else { return }

for (_,value) in jsonArray {

    for object in value {

        organizationLists.id = object["id"] as? Int
        organizationLists.Name = object["name"] as? String
        organizationLists.parentID = object["parentID"] as? Int
        organizationLists.plantID = object["plantID"] as? Int
        organizationLists.loggedInUserId = object["type"] as? Int
        let isInserted = sharedInstance.saveOrganization_Lists(organizationLists)
    }
}

Now with the above code, I'm able to properly insert the data also into the database. But I feel that there might be a better way to directly parse based on the value rather than using a for loop inside a for loop like above..or maybe a totally different and better method altogether...
EDIT 1: Class for Codable
class OrganizationLists: Codable{
    var id: Int?
    var name: String?
    var parentID: Int?
    var plantID: Int?
    var type: Int?

    //Initialize as usual
    init(id: Int, name: String, parentID: Int, plantID: Int, type: Int) {
        self.id = id
        self.name = name
        self.parentID = parentID
        self.plantID = plantID
        self.type = type
    }
}

A:

Usually you receive the data from an API response as raw Data representing a JSON string.
let jsonString = """
{
    "organizations": [
        {
            "id": 12345,
            "name": "products1",
            "parentId": null,
            "plantId": 28768,
            "type": 1
        },
        {
            "id": 76532,
            "name": "products2",
            "parentId": 4270947,
            "plantId": null,
            "type": 2
        }
    ]
}
"""

let data = Data(jsonString.utf8)

Don't use a class unless you really need a class and declare only those properties as optional which can be nil. If you are not going to modify the values declare the properties even as constants (let).
Further you need an umbrella struct for the root object
struct Root : Decodable {
    let organizations : [Organization]
}

struct Organization : Decodable {
    let id: Int
    let name: String
    let parentID: Int?
    let plantID: Int?
    let type: Int
}

Now decode the data
do {
    let result = try JSONDecoder().decode(Root.self, from: data)
    print(result)
} catch {
    print(error)
}


Q:

Get First Element from Collection and delete it

I need to get the first element from a Firebase Collection and then delete it, but can't figure out how to do it. I need it for a cloud function.
await ref
      .doc(ref.limit(1).get().docs[0]);

A:

Bohkoval's overall logic, as presented in his/her answer is correct, however the answer is related to the Realtime Database, while the OP is working with Firestore (from the tags used in his question).
Making the assumption that you "have a timestamp property which [you] can sort by" as you said in the comment below, in a Cloud Function you would do as follows for Firestore:
return admin.firestore().collection("yourCollection")
.orderBy("yourTimestamp", "desc")
.limit(1)
.get()
.then(querySnapshot => {
    if (!querySnapshot.empty) {
        //We know there is one doc in the querySnapshot
        const queryDocumentSnapshot = querySnapshot.docs[0];
        return queryDocumentSnapshot.ref.delete();
    } else {
        console.log("No document corresponding to the query!");
        return null;
    }
});


Q:

Set size to icon in NavigationButton on Android

In a Nativescript/Angular app I have the avatar of the user on the left in the header. For Android, I have to use NavigationButton:
<NavigationButton #navigationButton *ngIf="isAndroid" [loaded]="navigationButtonLoaded()" [icon]="customImage" (tap)="toggleSideDrawer()">
</NavigationButton>

The customImage is a https resource; NavigationButton wants a local resource, so when the user signin I download the image, using the local resource. It works, but the image is big so it fills the whole header. I tried to simply ad a class con NavigationButton setting width and height but it doesn't work. So I added the loaded function, where I tried to set it manually, it doesn't give any error but it doesn't work:
....

@ViewChild('navigationButton') navigationButton: NavigationButton;
 ....

navigationButtonLoaded() {
    if (this.navigationButton) {
        this.navigationButton.effectiveWidth = 45;
        this.navigationButton.effectiveMinWidth = 45;
        this.navigationButton.effectiveHeight = 45;
        this.navigationButton.effectiveMinHeight = 45;
    }
}

A:

I don't think it's possible to adjust the size of NavigationButton alone. You must use a Custom Title View, place an Image and align it on the left side to mimic the NavigationButton.


Q:

Matlab Put Labels on Clusters

I have implemented an algorithm and here is a plot from my resource book:

I am new to Matlab. I have a xValues list, yValues list (I have divided my final matrix into x and y axis, I am not sure is that true, if you make a suggestion you are welcome) and a vector of labels.
I want to get an image as like in the above. How can I put some class labels (i.e. 0,1,2,3..) as like given image?
PS: I plot as like that: plot(xValues,yValues,'b.'); however my dots are like diamond, not point as like in the image.

A:

You can use text to plot text on the scene. (Matlab help:)
text(X,Y,'string') adds the text in the quotes to location (X,Y)
on the current axes, where (X,Y) is in units from the current
plot.

You will need to know where on the graph you want to plot your text but you can do this:
x = -pi:.1:pi;
y = sin(x);
p = plot(x,y)

text(-pi/4,sin(-pi/4),'7')
text(-pi/4+1,sin(-pi/4),sprintf('%d', 8))
text(-pi/4+2,sin(-pi/4),'9')

which will give you this:

You can add different text styles etc with the regular matlab annotation things. You can also automatic add the number you want for your cluster with the sprintf command as i have shown when i plot the 8.
Good luck.


Q:

require a new instance of Node module

A new instance of third-party module should be required in one of the modules.
// a
...
exports.thirdParty = require('third-party');

// b
...
exports.thirdParty = require('third-party');

// first-party
...
exports.thirdParty = requireFreshInstance('third-party');

// app.js
var assert = require('assert');
var a = require('a');
var firstParty = require('first-party');
var b = require('b');

assert(a.thirdParty === b.thirdParty);
assert(firstParty.thirdParty !== a.thirdParty);
assert(firstParty.thirdParty !== b.thirdParty);

All of the listed modules have similar package requirements,
dependencies: {
  "third-party": "^1"
}

And the requirement is that it should stay intact, no tricks like "third-party": "git://..." are allowed.
Let's say the user controls only first-party module and can't modify third-party module to have a new factory method that would return a new instance.
I'm aware of the fact  that third-party is cached once if the version is the same in all cases (technically it is full path to third-party that matters), most likely .thirdParty properties in all objects are equal.
How can this problem be solved in Node.js programmatically (not with package.json)?

A:

Here is one module require-new could meet your requirement.

require-new requires a new module object.
require-new does not affect the state or behavior of require
method.
require-new has been designed to be used for module testing.

Here are sample from this module.
require('./rand.js'); // 0.697190385311842
require('./rand.js'); // 0.697190385311842

Modules are cached in a require.cache object when they are required.
require-new deletes the key value from the require.cache object associated with the module you are requesting, making the module reload:
requireNew('./rand.js'); // 0.2123227424453944
requireNew('./rand.js'); // 0.5403654584661126


Q:

What is the correct URI for sending parameters via POST in WCF REST Services?

Let's say that I have specified the following WCF REST Service at the address "http://localhost/MyRESTService/MyRESTService.svc"
[ServiceContract]
public interface IMyRESTService
{
[OperationContract]
[WebInvoke(
  Method = "POST",
  UriTemplate = "/receive")]
string Receive(string text);

Now I can call my REST service in Fiddler using the address "http://localhost/MyRESTService/MyRESTService.svc/receive" and it works (I'll get a return value).
But what if I want to send parameters to my REST Service? Should I change my interface definition to look like this:
[ServiceContract]
public interface IMyRESTService
{
[OperationContract]
[WebInvoke(
  Method = "POST",
  UriTemplate = "/receive/{text}")]
string Receive(string text);

Now if I'll call the REST Service in Fiddler using the address "http://localhost/MyRESTService/MyRESTService.svc/receive/mytext" it works (it sends the parameter "mytext" and I'll get a return value). So is this the correct URI for sending parameters via POST?
What confuses me is that I don't know how to use this URI exactly in code at the same time when I'm sending parameters. I have this following code which is almost complete for sending POST data to a WCF REST Service but I'm in stuck with how to take parameters into account with URI.
Dictionary<string, string> postDataDictionary = new Dictionary<string, string>();
      postDataDictionary.Add("text", "mytext");

      string postData = "";
      foreach (KeyValuePair<string, string> kvp in postDataDictionary)
      {
        postData += string.Format("{0}={1}&", HttpUtility.UrlEncode(kvp.Key), HttpUtility.UrlEncode(kvp.Value));
      }
      postData = postData.Remove(postData.Length - 1);

      Uri uri = new Uri("http://localhost/MyRESTService/MyRESTService.svc/receive");
      HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
      req.Method = "POST";
      byte[] postArray = Encoding.UTF8.GetBytes(postData);
      req.ContentType = "application/x-www-form-urlencoded";
      req.ContentLength = postArray.Length;

      Stream dataStream = req.GetRequestStream();
      dataStream.Write(postArray, 0, postArray.Length);
      dataStream.Close();

      HttpWebResponse response = (HttpWebResponse)req.GetResponse();
      Stream responseStream = response.GetResponseStream();
      StreamReader reader = new StreamReader(responseStream);

      string responseString = reader.ReadToEnd();

      reader.Close();
      responseStream.Close();
      response.Close();

If I'll want to send parameters (e.g. "mytext") in code via POST should the URI code be either
this
Uri uri = new Uri("http://localhost/MyRESTService/MyRESTService.svc/receive");

or this (this works but it doesn't make any sense since parameters should be added other way and not directly to the URI address)
Uri uri = new Uri("http://localhost/MyRESTService/MyRESTService.svc/receive/mytext");

I'm glad if you can help me, it can't be so difficult with WCF REST Services.

A:

So if you want to send raw data such as XML to your WCF REST Service (and also return), here is how to do it. But I have to say that before I found this solution I spend a lot of time googling frustrated as all examples were just talking about sending parameters in the URI (come on, the common scenario is to send XML and you can't do that properly in the URI). And when finally I found the right code examples it came up that it wasn't enough in WCF as I got the error "400 Bad Request". This error was caused by the fact that WCF can't use my raw XML if I don't force it by overriding it with some custom code (come on, what were you thinking Microsoft?, fix this in the next version of .NET Framework). So I'm not satisfied at all if doing such a basic thing can be so hard and time consuming).
** IMyRESTService.cs (server-side code) **
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Bare)]
Stream Receive(Stream text);

** client-side code **
XmlDocument MyXmlDocument = new XmlDocument();
MyXmlDocument.Load(FilePath);
byte[] RequestBytes = Encoding.GetEncoding("iso-8859-1").GetBytes(MyXmlDocument.OuterXml);

Uri uri = new Uri("http://localhost/MyRESTService/MyRESTService.svc/Receive");

Request.ContentLength = RequestBytes.Length;

Request.Method = "POST";

Request.ContentType = "text/xml";

Stream RequestStream = Request.GetRequestStream();
RequestStream.Write(RequestBytes, 0, RequestBytes.Length);
RequestStream.Close();

HttpWebResponse response = (HttpWebResponse)Request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string ResponseMessage = reader.ReadToEnd();
response.Close();

** XmlContentTypeMapper.cs (server-side custom code which forces WCF to accept raw XML) **
public class XmlContentTypeMapper : WebContentTypeMapper
{
public override WebContentFormat GetMessageFormatForContentType(string contentType)
{
return WebContentFormat.Raw;
}
}

** Web.config (server-side configuration settings for utilizing the custom code)
<endpoint binding="customBinding" bindingConfiguration="XmlMapper" contract="MyRESTService.IMyRESTService"
           behaviorConfiguration="webHttp"    />

<bindings>
  <customBinding>
    <binding name="XmlMapper">
      <webMessageEncoding webContentTypeMapperType="MyRESTService.XmlContentTypeMapper, MyRESTService"/>
      <httpTransport manualAddressing="true"/>
    </binding>
  </customBinding>
</bindings>

Invoke a WCF Web Service with an HTTP POST
http://social.msdn.microsoft.com/forums/en-us/wcf/thread/4074F4C5-16CC-470C-9546-A6FB79C998FC


Q:

ASP code not reading SQL field correctly

I'm pulling a field from a table and doing different things depending on what the result is. Here's my code
<%stringA ="Select field From table Where something=1"
set response = connFW.Execute(stringA )
set result = response ("field")
If result ="y" Then
Response.Write("The field is: " & result )
End If%>

It outputs this:
The field is: y

Then, later, I have an If statement:
<% ElseIf result ="y"  or Session("customer_id") <> "" Then
Do Something
%>

But it never executes what's in the ElseIf statement! It says right at the top of the page that it gave the correct result! Am I missing something?
Note: To avoid confusion, this code is at the top of the page:
Set connFW = Server.CreateObject("ADODB.Connection")
connFW.ConnectionTimeout = Application("FW_ConnectionTimeout")
connFW.CommandTimeout = Application("FW_CommandTimeout")
connFW.Open Application("FW_ConnectionString")

A:

Without seeing your complete code, it's hard to see where the exact problem is, but I see two possibilities. Either you have an "ElseIf" on its own, in which case you should change ElseIf to just plain If:

If result ="y" or Session("customer_id") <> "" Then

...or you are placing your ElseIf after your previous one:
If result ="y" Then
    Response.Write("The field is: " & result )
ElseIf result ="y" or Session("customer_id") <> "" Then
    Do Something
End If

If it's the latter, then your ElseIf will not execute because the result = "y" condition has already been met in the previous If-statement.


Q:

How to get an URL parameter with value `/` (slash) - Magento

How to get an URL parameter with value / because I have a value
$encrypted = "Dwe/OAISUD";

www.test.com/test/test/index/encrypted/Dwe/OAISUD

then I want to get it with controller getParam('encrypted');
but in controller I get value
$encrypted = "Dwe";

How to fix that? On Magento way.

A:

$encrypted = urlencode("Dwe/OAISUD");


Q:

Buy X Get Y Free rule is not working in magento

I have create a rule under Shopping Cart Price Rules.
In Actions
Apply: Buy X Get Y Free(discount amount is Y)
Discount Amount: 1
Discount Qty step(Buy X): 2

And provide condition
If ALL  of these conditions are TRUE :
Category  is  5

Note: 5 is category Mobiles
The rule is created successfully. But in home page nothing is displayed about this rule and nothing happened for this rule while shopping. That means it showing the rule is not working. How can i make it working, and what is wrong with my approach. Need your help...
Note: magento version is 1.7.0.2

A:

In the admin panel, click on Promotions -> Shopping Cart Price Rules (because we are dealing with products in the cart)
In the Conditions tab,click the little plus symbol and select 'Product Attribute Combination'.
Select the new plus symbol and select category. Click on the '...' and select the category for the products you want to have in the basket for you to get the discount.
Now click on the Actions tab, in 'Apply' have 'Percent of product price discount'. In Discount Amount, enter 100 (for 100%). In the conditions at the bottom, click on the plus symbol and select Category. Click on the '...' to select the category for the products you want to apply the 100% discount to.
This will get you 100% off all products in cat b when you have >= 1 products from cat a in the cart.
NOTE: Test this functionality as many times you can.. Test it with adding multiple quantity of main product or by adding the multiple quantity of free product.


Q:

Fluentd + Elasticsearch = Connection refused

I'm trying to connect fluentd with elasticsearch and I'm getting this error when I start the td-agent service.
td-agent.log:
Could not communicate to Elasticsearch, resetting connection and trying again. Connection refused - connect(2) for 127.0.0.1:9092 (Errno::ECONNREFUSED)
td-agent.conf
<match docker.*>
  @type elasticsearch
  host localhost
  port 9092
  logstash_format true
</match>

My elasticsearch is running because I can check on http://localhost:9200/ and also the fluentd plugin
plugin 2020-05-21 12:57:55 -0300 [info]: gem 'fluent-plugin-elasticsearch' version '4.0.8'

A:

If you can access elasticsearch from localhost:9200 then the .conf will look like:
<match docker.*>
  @type elasticsearch
  host localhost
  port 9200
  logstash_format true
</match>


Q:

LineRenderer on Mesh surface

Goal: Render distance lines between two points on the surface of a mesh-based primitive (i.e. sphere, cube, etc).

Current Solution: Iteratively traverse distance line between two end points and "reverse" raycast through this point somehow. Since the distance line directly connects both vertices through the mesh, the according points on the mesh surface are required.
Ray ray = new Ray();
RaycastHit raycastHit;
ray.origin = posOnDistanceLine;
ray.direction = raycastNormal.normalized;
// Reverse ray since we can't raycast from inside the mesh
ray.origin = ray.GetPoint(1);
ray.direction = -ray.direction;

Lines are then drawn using Unity's LineRenderer which is being populated with positions of vertices whenever a change in normals (to previous raycast) is identified.
Issues:

Horrible performance (as 100 rays are cast whenever the end points move).
Solution doesn't always work and produces unexpected, jagged lines / points.

Question:
Is there a better approach to implement this?

A:

If you want to optimize the solution, you might need  to make a script for each primitive and utilize the primitive-specific math.
For example, instead of casting rays, you could simply get the radius of the mesh and put the line vertex at the radius * directionFromCenter.
Here is an example script:
[RequireComponent(typeof(LineRenderer))]
public class SurfaceLine : MonoBehaviour, IPointerClickHandler
{
    [SerializeField] private float pointsPerUnit;
    [SerializeField] private MeshFilter mesh;

    private Vector3 start;
    private Vector3 end;
    private LineRenderer lineRenderer;

    void Awake()
    {
        this.lineRenderer = this.GetComponent<LineRenderer>();
    }

    public void OnPointerClick(PointerEventData eventData)
    {
        if(eventData.button == PointerEventData.InputButton.Left)
        {
            this.start = this.transform.InverseTransformPoint(eventData.pointerCurrentRaycast.worldPosition);
            this.Render();
            return;
        }

        if(eventData.button == PointerEventData.InputButton.Right)
        {
            this.end = this.transform.InverseTransformPoint(eventData.pointerCurrentRaycast.worldPosition);
            this.Render();
        }
    }

    private void Render()
    {
        var distance = Vector3.Distance(this.end, this.start);

        var direction = (this.end - this.start).normalized;

        var numPoints = Mathf.FloorToInt(distance * this.pointsPerUnit);

        numPoints = Mathf.Max(numPoints, 2);

        this.lineRenderer.positionCount = numPoints;

        var positions = new Vector3[numPoints];

        var stepInDir = direction * (distance / (float)numPoints);

        for(int i = 0; i < numPoints; i++)
        {
            positions[i] = this.start + i * stepInDir;

            var dirFromCenter = positions[i] - this.mesh.mesh.bounds.center;

            positions[i] = this.mesh.mesh.bounds.center + dirFromCenter.normalized * (this.mesh.mesh.bounds.size.x / 2.0f);
        }

        positions[positions.Length - 1] = this.end;

        this.lineRenderer.SetPositions(positions);
    }
}

This seems to perform okay in an update loop too. The down side is of course that the solution is not generic. You will need a strategy per primitive.
Alternatively you can at least leverage the pointsPerUnit concept in the script to control the resolution of your line and stick with ray casting. I think the strange artefacts you are seeing is a result of too high point density. Making the points per unit of distance consistent may have better performance too.
Here is the result for the script above:


Q:

How to create a custom constant in a parameter section

For example, I would like to create a variable to store some directory in the [Files] section, like this: mydir=CustomDir; so I can reference it later when I'm importing my files
Source: "{mydir}\MyProg.exe"; DestDir: "{app}";
Source: "{mydir}\MyProg.chm"; DestDir: "{app}";

I want to do this because later on I can easily change the directory of my importing files, and for other customizations in other parts.
Is there something in Inno that allow me to do that?

A:

You can do this using the Inno Setup Preprocessor.
That is good for compile-time constants. If you wanted to set a variable at install-time, you could use Inno Setup's Pascal scripting.


Q:

Can we add non-AMP HTML inside AMP iframe?

Can I use normal HTML with "img" and "script" tags using amp-iframe by calling non-amp html file using src attribute of amp-iframe?

A:

Yes, but the iframe must be https and it will be loaded async.


Q:

Exception ORA-08103: object no longer exists on using setfetchsize of Hibernate

I'm using Hibernate. I need to fetch around 1000000 records and it will cause timeout exception. So I'm using setfetchsize for 6000 records, so that it will distribute the operation in multiple transactions each of 6000 records.
It will take around 21 hours to fetch all.
But meanwhile retrieving records if somebody deletes one of the record which was to be fetched then I get ORA-08103: object no longer exists.
Now I want to skip that object which is deleted while retrieving. How can I do this?

A:

Most likely that a cursor is opened based on a global temporary table(GTT), which had been created with ON COMMIT DELETE ROWS option. And the cause of the ORA-08103: object no longer exists error is commit statement that followed right after the delete statement. Here is a simple example:
 SQL> declare
  2    type t_recs is table of number;
  3    l_cur sys_refcursor;    -- our cursor
  4    l_rec t_recs;
  5
  6  begin
  7
  8    -- populating a global temporary table GTT1 with sample data
  9    insert into GTT1(col)
 10      select level
 11        from dual
 12     connect by level <= 1000;
 13
 14   open l_cur         -- open a cursor based on data from GTT1
 15    for select col
 16          from GTT1;
 17
 18    -- here goes delete statement
 19    -- and
 20    commit;  <-- cause of the error. After committing  all data from GTT1 will be
 21              -- deleted and when we try to fetch from the cursor
 22    loop      -- we'll face the ORA-08103 error
 23      fetch l_cur    -- attempt to fetch data which are long gone.
 24       bulk collect into l_rec;
 25      exit when l_cur%notfound;
 26    end loop;
 27
 28  end;
 29  /

ORA-08103: object no longer exists
ORA-06512: at line 24

Recreation of global temporary table with on commit preserve rows clause will allow to safely fetch data from a cursor that is based on that table without being afraid of facing  ORA-08103: error.


Q:

Click e segurar no ListView

Como programo para ao click e manter pressionado chame um método diferente de somente um click normal no ListView?
Gostaria de dicas, tutorias algo que possa me ajudar.
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(getActivity().getBaseContext(), inalcancaveis_tela.class);
            startActivity(intent);
}

chamo esse metodo no onCreateView
list.setOnItemClickListener(this);

OBS: to utilizando extends Fragment

A:

Faça sua classe implementar o evento para long clique implements OnItemLongClickListener
E utilize o método onItemLongClick como abaixo:
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
    Intent intent = new Intent(getActivity().getBaseContext(), inalcancaveis_tela.class);
    startActivity(intent);
}

no onCreate de sua classe agora você deve chamar esse método para registrar seu evento:
list.setOnItemLongClickListener(this);

Abs


Q:

regex search&replace a variable string including a regex statement

I want to use re.sub to replace a part of a string I know exactly what looks like. relevant part of code:
print "Regex statement: ", foundStatements[iterator]
print "string to replace with : \n", latexPreparedString
print "string to search&replace in: \n", fileAsString
processedString = re.sub(foundStatements[iterator], latexPreparedString, fileAsString)
print "processed string: \n", processedString

In my testing case, foundStatements[iterator] is "%@import script_example.py ( *out =(.|\n)*?return out)" But even though processedString contains foundStatements[iterator], processedString looks exactly like fileAsString, so it hasn't accomplished the re.sub task. What am I doing wrong?
EDIT: Ok, it definitely has something to do with the string I'm searching to replace containing regex code. Is there a way to make it just interpret it foundStatements[iterator] as a raw string to search for? The only solution I can think of is to create a function that replaces any regex symbols in a string with \regexsymbol (e.g. * -> \*), but it'd make sense for there to be a way to solve this with inbuilt functions. It'd also be a bit overkill since I'd have to make sure it works with every single regex symbol, of which there are quite a few :/
EDIT2: Well, just changing it to re.sub(re.escape(foundStatements[iterator]), latexPreparedString, fileAsString) seems to work. except when the regex statement doesn't hit anything in the original file. To explain, latexPreparedString is generated by using the regex-part of the foundStatements[iterator]. While it's logical that it shouldn't be able to set latexPreparedString to anything when the regex statement doesn't hit anything, I set latexPreparedString = "" by default, so in that case it should re.sub replace it with a blank string if it doesn't hit anything. Here's how to code looks at the moment: pastebin.com/wUedK3LN

A:

First, for replacing an exact match in a string, you should use [string.replace()][1]:
processedString = fileAsString(foundStatements[iterator], latexPreparedString)

However, this will still fail in your case, because foundStatements[iterator] has a newline character in it. To escape it, you need to use the r prefix when declaring foundStatements[iterator].
If you still want to use re.sub, you have to both prefix the string with r and use re.escape(foundStatements[iterator]) instead of foundStatements[iterator]. You can read more about re.escape here.


Q:

WatiN error ElementNotFoundException

When I am attempting to run the unit tests against my website, I suddenly started receiving the following error:
WatiN.Core.Exceptions.ElementNotFoundException was unhandled by user code
  Message=Could not find A element tag matching criteria: Attribute 'href' equals uri     'https://my.companyurl.com/client/clientupload.aspx' at     https://my.companyurl.com/account/default.aspx
  Source=WatiN.Core
  StackTrace:
       at WatiN.Core.Element.get_NativeElement()
       at WatiN.Core.Element.GetAttributeValueImpl(String attributeName)
       at WatiN.Core.Component.GetAttributeValue(String attributeName)
       at WatiN.Core.Element.get_Enabled()
       at WatiN.Core.Element.ClickImpl(Boolean waitforComplete)
       at WatiN.Core.Element.Click()
       at UnitTests.MyUploadFileClass.ClickNavigateToUploadFile() in     D:\DevProjects\MyWebApp\test\UnitTests\Tests\MyUploadFileClass.cs:line 40
       at UnitTests.MyUploadFileClassTest.UploadNewFileTest() in     D:\DevProjects\MyWebApp\test\UnitTests\Tests\MyUploadFileClassTest.cs:line 110
  InnerException:

Also receiving exceptions like this:
System.Runtime.InteropServices.COMException was unhandled by user code
  Message=The interface is unknown. (Exception from HRESULT: 0x800706B5)
  Source=Interop.SHDocVw
  ErrorCode=-2147023179
  StackTrace:
       at SHDocVw.InternetExplorerClass.set_Visible(Boolean pBool)
       at WatiN.Core.Native.InternetExplorer.IEBrowser.set_Visible(Boolean value)
       at WatiN.Core.IE.FinishInitialization(Uri uri)
       at WatiN.Core.IE.CreateNewIEAndGoToUri(Uri uri, IDialogHandler logonDialogHandler, Boolean createInNewProcess)
       at WatiN.Core.IE..ctor(String url)

The tests used to pass previously with no problem, so I'm not sure why this error started occuring.  Does anyone have any suggestions?  TIA.

A:

Actually resolved the problems by performing three steps: 1) Updated the URLs because my coworker had changed them. 2) Ran Visual Studio as administrator. 3) In IE9 went to Tools->Internet Options->Security tab->Local Intranet. Clicked on the sites button and removed the check box from "Automatically detect intranet network". Thanks for the feedback!


Q:

How to protect an SSL certificate (Apache/CentOS)

I currently use a server SSL certificate without a pass-phrase in order to allow Apache to start up unattended.
There are signs from customers to require us to protect the SSL certificate more securely. I'm not sure yet what they are aiming for, but for now I guess that they don't want an unprotected SSL certificate on the disk. I suppose I can't avoid having it in the clear inside Apache's memory but let's assume that's acceptable.
I came up with an elaborate system to keep the pass-phrase in the memory of a process on an internal server (i.e. not on the front-line web server) and hand it over to the front-line server using an Apache SSLPassPhraseDialog (http://httpd.apache.org/docs/2.2/mod/mod_ssl.html#sslpassphrasedialog). The internal server will have to have the pass-phrase typed in to it when it starts, and we'll have multiple such servers load-balanced for high availability.
My question is:

How do the "big boys" protect their SSL certificate? Do they just force their stuff to type the pass phrase on server restart or do they keep it unencrypted like the rest of us?
My experience with open source is that there is a very good chance that someone has already solved whatever problem I face - is such a system available already?
Would it be reasonable, from business level perspective, to just say that we keep the certificate unencrypted and just have rapid procedures to revoke it if stolen?

A:

I would say that the "big boys" do SSL offloading onto clustered front end load balancers, since that's what I do and I'm no where near a "big boy".
I found these instructions on httpd.apache.org on removing the passphrase dialog, which you have likely seen if you googled the problem, which I assume you have.
The problem with revocation is that you're at the mercy of the signing CA to hurry up and deal with your problem. If you pay a lot for your certs, I'm sure their service is very positive. I'm not certain how it would be for some of the smaller wholesalers. Maybe someone else could chime in.

A:

Lets review Public Key Infrastructure basics first in a hierarchical PKI model.

A public key is an encryptor/locker, and embedded into a certificate
created by a certificate authority.
A private key is a decryptor/unlocker used in conjunction with a public key.
Public keys, and certificates have no confidentiality requirements.
Private keys have confidentiality requirements

Therefore, your concern with Apache should be around the private key, not the public key.  The typical way a security engineer might protect a private key is to use a hardware security module.  A hardware security module (HSM) can come in many form factors including a smartcard, a PCIe card, a PCI card, a USB dongle, a USB stick, a network based HSM, or others.  Accordingly, these can cover a large amount of budgets and security capabilities.
There are some HSMs that have validated security implementations such as FIPS 140-2 in levels 1 (software generally) 2 physical (tamper resistance) 3 physical (tamper resistance & intrusion response) and 4 physical (tamper resistance, intrusion response and key zeroization).
To evaluate if your business should do something, I'd look at doing a cost benefit analysis &  a risk assessment that includes ALE, ARO, and SLE calculations.  However, if you are doing business over the web, it might be better to bring in a web security professional to evaluate all of your infrastructure and come up with a consolidated list of vulnerabilities and weaknesses, with a prioritized remediation plan that you can work with your management.


Q:

Should we discourage answers that say AI can't be smarter than its creator?

I'm seeing a lot of answers from people along the lines of "AI is just bits and bytes and ultimately cannot be smarter than its creator because its creator would have to use their brain to make something smarter than themselves, which isn't possible."
It's kind of baffling to me to see these answers, especially in regards to the singularity, on a forum dedicated to AI. There is already image recognition that can recognize objects more accurately than humans, IBM's Watson can diagnose lung cancer at a rate much more accurately than human physicians, and Google's Alpha Go beat the Go world champion, even while experts were predicting that AI wouldn't succeed at doing this for another 10 years.
At the same time, I am completely certain that any of the individual programmers of Alpha Go would not have succeeded in defeating the Go champion of the world. I'm also fairly certain that the Watson programmers would not do better than Watson or a human physician at identifying lung cancer. These are already cases of the AI being more intelligent than its programmer, albeit in domain-specific cases.
Therefore, it seems wholly lazy and uncreative for people to provide such answers that AI cannot be more intelligent than a single creator and therefore human-level AI and beyond is not possible. I think it does not contribute to the discussion.

A:

If an answer is wrong, it should be downvoted, plain and simple. Clearly we want to discourage wrong information, and downvotes are designed to point out incorrect, irrelevant, or otherwise poor content. You seem to have really good examples that show such answers are wrong, so please feel free to mention them in a comment when downvoting!


Q:

Using DataFrame.foreachPartition, processing partitions as data frames

I have a dataframe that's partitioned by col0; there are many rows in the DF per value of col0. I have a database from which I want to fetch batches of data using the values of col0 in each partition, but I can't for the life of me figure out how to use foreachPartition, since it returns a Iterator[Row].
Here's pseudocode for what I'm wanting to do:
var df = spark.read.parquet(...).repartition(numPartitions, "col0")
df.foreachPartition((part_df : DataFrame) => {
  val values = part_df.select("col0").distinct
  val sql = "select * from table0 where col0 in (${values})" // or some smarter method :)
  val db_df = spark.read.jdbc(..., table = sql)
  part_df.join(db_dv, "col0") // and/or whatever else
})

Any ideas?

A:

I wasn't able to find an elegant solution to this, but I was able to find an inelegant one.
When you write out to a filesystem, Spark will write a separate file for each partition. You can then use filesystem to list the files, then read in and operate on each one individually as a separate dataframe.


Q:

Should there be any PCB ground plane under a 16 MHz oscillator?

For a 2-layer PCB,
should there be a ground plane under a 16 MHz oscillator?
From this PDF document,
http://www.nxp.com/assets/documents/data/en/application-notes/AN2500.pdf,
it shows the following figure,

which suggests not to have any ground plane under the oscillator components.
whereas a response from here (When to use ground plane cutouts?)
says:

In fact, it is highly recommended to run your high-speed signals
  directly overtop of an unbroken ground plane;

So my questions are:

Would the lines for a 16 MHz oscillator be considered
"high-speed"?
Would it be correct to not have any ground or power planes under
16 MHz oscillator lines + related components?

A:

Choosing ground cutouts on the basis of the signal's speed is only part of the story. The oscillator, and the 'high speed signals' your link talks about, are different situations.
The oscillator is recommended to use a specific circuit layout. This is a very small circuit. Follow the data sheet. An adjacent ground plane would introduce much C to ground. It's likely that the oscillator requires certain ratios of capacitance, and maximum capacitance to function properly, hence their recommendation. At the frequencies involved, for the line lengths shown, it all works, don't sweat it, just follow the data sheet. The 'to minimise parasitics' statement confirms that it's the excess capacitance that they are concerned about. Even if it does not stop oscillation, excess C will increase power consumption, which could be an issue on lower power designs.
'High speed signals' crossing a ground plane from one IC to another should have a well-defined return current path close by. The simplest way to do this is with an unbroken ground plane underneath. There are other methods, if you know what you're doing, but the unbroken ground plane is easy to do and always works. If you introduce breaks or cutouts in the ground plane, then this disrupts the return current flow, which can cause all sorts of problems which can be quite difficult to diagnose.
It is important that when you've cleared a patch of ground plane under your oscillator that you don't then route a different high speed signal across that area, both for problems with that signal's integrity, and potential problems of interference to/from your oscillator.

A:

AFAIK general requirements for any passive XTAL circuit are same: XTAL branch must be isolated from the rest as much as possible since it is critical to avoid parasitics. Usually these are:

Components must be placed close as possible to IC, with short traces
No high speed traces passing nearby or under
Avoid crosstalk / coupling between traces
GND part must be isolated from "general" GND. If plane is used, it must be separated by gap (even from "general" GND plane)
Sometimes guard ring around is recommended - GND path with vias (check STM AN2867 for example)

Regarding various techniques, I think it is better to figure out why (requirements) and then decide what fits and what is not.


Q:

creating a new user in Mac will it reset everything?

I want to reset all my configurations trying to install MySQL & other development stuff through the Terminal on my MacBook and start fresh. Because it was my first time doing this and I think I made lots of wrong stuff.
So, do creating a new user will do this or I need to make a new "fresh" install for the OS?

A:

Creating a new user will trash all the configurations that are stored in the old user's home directory (i.e. /Users/old_username)
This does not affect configurations done in the system folders(e.g. /usr/, /etc/, /Libraries
So you need to figure out if you configured mysql in your home directory or in the system folders.
Typically if you had to use your administrator privileges to configure mysql then it's stored in system folders.


Q:

Vue.js: How to access "this" in methods definition

I define a plugin and use it like:
import * as d3 from "d3"
import Vue from "vue"

export default {
    install: function(){
        window.d3 = d3
        Vue.prototype.d3 = d3
    }
}

Then when I try to define a component methods using that plugin:
<script>
    export default {
        methods:{
            lineFunction: this.d3.line()
                             .x(function(d, i) { return i*10; })
                             .y(function(d) { return d*10; })
                             .curve(d3.curveMonotoneX)
            }
        }
    }
</script>

It keeps giving me

"Uncaught TypeError: Cannot read property 'line' of undefined"

it seems this.d3 is not ready, I tried use d3 rather than this.d3, both are not working, thoughts?

A:

lineFunction has to actually be declared as a function, with parenthesis and braces:
export default {
    methods: {
        lineFunction () {
             return this.d3.line()
                 .x((d, i) => i * 10)
                 .y(d => d * 10)
                 .curve(d3.curveMonotoneX);
        }
    }
}


Q:

WebStorm не принимает гит

Ошибка, когда пытаюсь подключить гит. Что делать?

A:

Решилась проблема сменой Windows и установкой наново всего


Q:

Floyd Warshall reconstruct path

I want to reconstruct the path from source to destination vertex in this graph problem.
How can I store the path, and how can I retrieve it after I have found the minimal cost from s to d?
Please help me to find a simple answer?
For example at the point,
adjmat[i][j] = Math.min(adjMat[i][j],adjMat[i][k]+adjMat[k][j]);

I need to add a path and I need to retrieve it.

A:

The Wikipedia article about the Floyd-Warshall algorithm provides an explanation and pseudocode for your problem.


Q:

Issue when submitting form data via JQuery UI Dialog to the server

I have an asp.net mvc app, using JQuery UI dialog. I'm trying to submit form data to the controler action method. I do hit the action method but my object has no data. Do you know why?
From Filter.cshtml
$("#selectUnits").dialog({
        autoOpen: false,
        title: 'Select Units',
        width: 400,
        modal: true,
        minHeight: 200,
        buttons: {

            "Cancel": function () {

                $(this).dialog("close");
            },

            "Submit": function () {

                $.post('/Data/SetUnitNumbers', $("#frmSelectedUnits").submit(), function (data) {

                    alert('This worked');
                });

            }

        }  // END OF BUTTONS

    });  //END OF DIALOG

From Controler...Action Method:
 public void SetUnitNumbers(object data)
    {
        int a = 5;
    }

From SelectUnits.cshtml where form 'frmSelectedUnits' lives. Essentially it is a bunch of checkboxes values that I'm trying to send back to the server:

<form id="frmSelectedUnits" action="/" >

             @Html.CheckBox("SelectAllUnitNumbers", false)Select/Unselect All Units

             @foreach (var item in Model)
                {

                            @Html.CheckBox("UnitNumbers", false)@item.unit_number.ToString().PadLeft(3, '0')

                }

</form>

A:

jQuery .post is:
$.post(url, data, success-callback-function);

where data is A map or string that is sent to the server with the request.
Calling $("#frmSelectedUnits").submit() probably won't work.
Try:
$.post('/Data/SetUnitNumbers', $("#frmSelectedUnits").serialize(), function (data) {
    alert('This worked');
});

jQuery docs on .serialize()


Q:

Differential Equations Complex Eigenvalue functions

Show that a function of the form
$x(t) = K_1 \cos\beta t + K_2 \sin\beta t$
Can be written as
$x(t) = K\cos(Bt-\phi)$
Where $K = \sqrt {K_1^2 + K_2^2}$
I know that linear systems with complex coefficients are sometimes expressed in this form, however I'm not sure if/how that would be useful to solve this problem.
Any suggestions on how to approach this would be greatly appreciated.

A:

$$x(t) = K\left( \frac{K_1}{K}\cos(\beta t) + \frac{K_2}{K}\sin(\beta t) \right)  $$
Since $K \geq K_1, K_2$ we get $\frac{K_1}{K}, \frac{K_2}{K} \leq 1$, and since $\left(\frac{K_1}{K}\right)^2 +\left(\frac{K_2}{K}\right)^2 =1$ I can choose an angle $\phi$ such that $\cos(\phi) = \frac{K_1}{K}$ and $\sin(\phi)= \frac{K_2}{K}$.  So then $$ x(t) = K (\cos(\phi)\cos(\beta t) + \sin(\phi)\sin(\beta t)) = K\cos(\beta t - \phi)$$
Where the last equality holds by the subtraction formula for cosine.


Q:

Make a Dropdown list sort by number

I made a dropdown menu and tried to list it.
But the list in the db doesn't start with "H01" so my dropdown starts with "H40"
How can I replace the code:
like 'H%'

Code and Frontend

A:

Please add order by your_column_name ASC in your query.


Q:

How can a sine function be transformed to have flat peaks?

I'm trying to create a sine function that will fit a geochron clocks day/night line. Right now I just started with a simple sine function, using map coordinates, which is this y=69sin(x-15)+2 but the peaks of the function should be flat which was not achieved with this function. Any advice on how to relatively easily transform the function to get this effect?
This is the online geochron clock that I was looking at http://www.fourmilab.ch/cgi-bin/Earth

A:

You could just use min and max to cut off the function at the top and bottom. If $\alpha$ is the minimum value and $\beta$ the maximum then try
$$
y(x) = \min(\max(A\cos(k(x-x_0))+c,\alpha ) , \beta)
$$
for appropriate values of $A$, $k$, $x_0$, $c$, $\alpha$, $\beta$, where
\begin{gather}
A>0
\\
k>0
\\
c-A<\alpha<\beta<c+A
\end{gather}
If you want the flat regions to all be the same length then you should have
$$
c=\frac{\alpha+\beta} {2}
$$
Note that I have used $\cos$ so that $x_0$ is solar noon.


Q:

Continuous Deployment not working

I need to continually build a create-react-app application and deploy it to Amazon S3 bucket.
I have written the following CircleCi config.yml:
version: 2
jobs:
  build:
    docker:
      - image: circleci/node:7.10
    steps:
      - checkout
      - run: npm install
      - run: npm run build
deployment:
  prod:
    branch: circle-config-test
    commands:
      - aws s3 sync build/ s3://http://www.typing-coacher.net.s3-website.eu-central-1.amazonaws.com/ --delete

What I think should happens:

I have a docker container, I install the application, build it and the files are resting ready in build folder.
I am running the command listed in CircleCi docs and the build files are moving from the docker machine to s3 bucket.

To deploy a project to S3, you can use the following command in the
  deployment section of circle.yml:
aws s3 sync <path-to-files> s3://<bucket-URL> --delete

What actually happens:
Application is being install and build files are being created, but nothing happen with deployment. it doesn't even appear on the builds console.
What Am i missing?

A:

disclaimer: CircleCI Developer Advocate
Everything from the deployment: line and down shouldn't be there. That's syntax for CircleCI 1.0 while the rest of your config file is CircleCI 2.0.
You can either:

Create a new step and check for the branch name with Bash. If it's circle-config-test, then run the deployment commands. You'll also need to install the AWS CLI in that build.
Using [CircleCI Workflows], create a deployment job with a branch filter for circle-config-test. You can use any image that contains the AWS CLI or install it yourself. The CI Builds: AWS Docker image contains this for you.


Q:

Gorm issue help

I have two classes
class Facebook {
   String fid
   String name
   User user
   static constraints = {
       user(nullable:false)
   }
}

and
class User {
   Facebook facebook
   String fullname
}

I make a Facebook object , then make a User object and when I try to save User it does not
allow me to . The error comes like
Trying to marshall a null id [id] for alias [User]

Please help

A:

You should check how to setup a one-to-one mapping with Grails GORM following this link:
http://grails.org/doc/latest/guide/5.%20Object%20Relational%20Mapping%20(GORM).html#5.2.1.1 Many-to-one and one-to-one
There is an example with Face and Nose similar to User/Facebook.