text:
Q: Javascript Array vs Php Array I have two versions of a identical code block in php and javascript. Output of them is slightly different. There are two "undefined" elements in Javascript output. I know that the Javascript Array indexes are incremental which starts from 0 and don't allows us to skip any index number.
Is there anyway to solve this so the Javascript Array output looks like the Php Array output?
Php Code:
$n = array();
$n[0] = 'Apple';
$n[3] = 'Apple';
echo "
";
print_r( $n );
echo "
";

Output:
Array
(
    [0] => Apple
    [3] => Apple
)

Javascript Code:
var n = new Array();
n[0] = 'Apple';
n[3] = 'Apple';
n;

Output:
[
    "Apple",
    undefined,
    undefined,
    "Apple"
]

Thanks!!

A: I think in your case more good to use object instead of array, such as in JS associative arrays the same objects. F.e.
var n = {};
n[0] = 'Apple';
n[3] = 'Apple';
console.log(n);

it will output
Object {0: "Apple", 3: "Apple"}

EDITED
You can get elements from object like in array:
n[0], n[3]

A: PHP Arrays are Hash Tables, Javascript Arrays are indexed lists
Short Answer
No. There is no way to make Javascript arrays behave like Php arrays without violating ECMA standards (which would mean it's technically no longer javascript).
Yes. But only by replacing the built-in Array prototype behaviors.
See ECMA-262 Section 15.4 Array Objects
What is an array anyway?
Arrays are ordered data and nothing more. While arrays do have an index, the concept of an array "index" shouldn't be conflated with the concept of labeled data storage. Array indices are always sequential, because it points to a position in the array, similar to positions of people in a line.
You couldn't make a line of people with one person first, and one person fourth, and no one else in line. n[0] = 'first'; n[3] = 'fourth;
This is how arrays are defined in nearly every programming language, because it is how the data is stored in memory.
Use Objects Instead
This is the same answer many others have already given to this question. Ultimately a javascript Array is just a predefined type of object, built to behave as outlined above. Thus, the behavior you are trying to change, is actually a behavior that has been carefully engineered.
So, instead of using the special "Array" object, use string keys (as object named properties) and your whole problem is simplified.
Note: this is essentially what the other 'Use an object' answers here are doing, with one notable exception.
n['0'] = 'Apple';
n['3'] = 'Apple';

// OR

n = {
    '0': 'Apple',
    '3': 'Apple',
};

// numeric keys are possible, IFF the var is first explicitly defined as an object.
n = {};
n[0] = 'Apple';
n[3] = 'Apple';

Object isn't enough, it must be an Array? Roll your own "Array" container object.
The drawback here is that you'll need to manually define all the method calls you would like to pass to the array object itself.
var PhpArray = function(ary){
    if (ary instanceof Array) {
        this.ary = ary;
    } else {
        this.ary = new Array(ary);
    }
};

PhpArray.prototype.forEach = function(f){
    for(i in this.ary){
        if (this.ary[i] !== undefined && this.ary[i] !== null) {
            f(i, this.ary[i]);
        }
    }
};

PhpArray.prototype.toString = function(){
    var strResult '';
    this.forEach(function(k, val){
        switch(typeof val) {
            case 'boolean':
            case 'string':
            case 'number':
                strResult += k + ': ' + val;
                break;
            default:
                if (val.toString) {
                    strResult += k + ': ' + val.toString();
                } else {
                    strResult += k + ': ' + typeof val;
                }
        }
    });
};

// Usage:
var n = Array();
n[0] = 'Apple';
n[3] = 'Apple';
var x = new PhpArray(n);
console.log('' + x);

x.ary[5] = 'Pear';

Still not good enough? "Change the Array Behavior!?" you say?
Want to access x[3] = 'Apple'; from the example above?
Or perhaps you really want to override the built-in Array prototype?
Well buckle your seatbelt Dorothy, because javascript is going bye-bye. That's right, we're going somewhere over the ECMA where you can do whatever you want. Sure, other developers will hate you, and third party tools (jQuery) won't work anymore, but at least you'll have your javascript Arrays that aren't arrays.
Unfortunately, I'm not going to help you do that.

A: As you mentioned JavaScript Arrays have index limitations.
The closest way you can get the output you are looking for is by using a JavaScript Object.
If you then use JavaScript JSON stringify to convert the object into well formatted text you will get an almost identical output with little effort.
You could write extra JavaScript to have the output exactly mirror the PHP output. But I will leave that up to you.

var n = new Object();
n[0] = 'Apple';
n[3] = 'Apple';

var output = JSON.stringify(n, null, 2);

// Output to a pre tag like the PHP example you gave.
document.getElementById("output").innerHTML = output;

// Simple output to the console.
console.log(output);

A: The reason that you are getting "undefined" values is that Javascript replaces any missing indexes/blanks in the list of array keys with the value of "undefined", i.e. index 1 and 2 in your case.
Rather than adding the element to your array by the key name, just push it onto the end of the array:
n.push("Apple");

Note! This will of course cause the indexes of the values in the Javascript to be different from your PHP script, as using push will always insert the value to the end of the array. That said, to make insert in exactly the same manner in both scripts, I would suggest that you use PHP's array_push method, which works the same way as Javascript's push method. Alternatively, you can use the same approach as you do now for the PHP script, but always insert at the end of the array, e.g:
$n[0] = 'Apple';
$n[1] = 'Apple';

A: It's worth noting that iterating over multidimensional variable in js is a little different than php.
PHP
$myArray = [0=>'here',1=>'we',2=>'go'];
for($i=0;$i<count($myArray);$i++){ echo $myArray[$i]; }
// or
foreach($myArray as $item){ echo $item; }

javaScript
There's ways to get the length of an object, but it can be tricky, so:
myObject = {0:'here',1:'we',2:'go'};
for(item in myObject){ console.log(myObject[item]) }

A: In your JS code do :
n = n.filter(function(n){ return n != undefined });
console.log(n);

This should eliminate the undefined elements.
 and outputs:
[
    "Apple",
    "Apple"
  ]

Note that in php if you do:
echo $n[1] ;

you will get:
Notice:  Undefined offset: 1 in .....

A: In Javascript Array it uses the index to find the value, so if it not find any value in that index it sets it as undefined or empty so to remove undefined we can use this function.
 Array.prototype.remove = function(deleteValue) {
      for (var i = 0; i < this.length; i++) {
        if (this[i] == deleteValue) {
          this.splice(i, 1);
          i--;
        }
      }
      return this;
    };

    var a = [];
    a[0] = 'zero';
    a[3] = 'three';
    a.remove(undefined);

A: As I can see, multiple answers are suggested. If you requirements just to show data only, not for production release. You can override toString method for demo purpose. Here below is the given snippet.
// Override toString
Array.prototype.toString = function () {
    return this.filter(x => x)
};

//How to use it
var n = new Array();
n[0] = 'Apple';
n[3] = 'Apple';
console.log(n.toString());

Why you should use toString in console.log.
Does console log invokes toString method of an object


text:
Q: JS timeout causes eval exception For some reason, one of my JS files is triggering an unsafe-eval Content Security Policy violation on my site. I thought this odd because there is no eval() anywhere in the file. The error happens on the following line:
setTimeout(callSpecific(), (lengthMF * (number.length + 2)));

The only thing I can see here is the arithmetic on the RHS that sets the timeout value. So, I tried:
setTimeout(callSpecific(), (parseInt(lengthMF) * (parseInt(number.length) + 2)));

Same thing. The variables themselves are not even strings - they are defined as:
var lengthMF = 150;
var number = ""; // yes, this is a string but number.length is not!

Why is this triggering a CSP violation? I have other setTimeout()s on the page and this seems to be the only problematic one. The weird thing is replacing the arithmetic expression temporarily with a constant (e.g. 50) does not cause the issue to go away.
If it's necessary, callSpecific() looks something like this:
function callSpecific() {
    if (number == 0) {
        operatorRing();
    } else if (number.length == 2 && number.charAt(1) == 0) {
        playReorder();
    } else if (number.length == 3) {
        //
    } else if (number.length <7 || number.length > 11) {
        //
    } else if (number.length == 11 && (number.charAt(4) == 1 || number.charAt(4) == 0)) {
        //
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: AngularJS md-autocomplete search for a string within a string How do you configure md-autocomplete so that if you search for a word, it searches for strings within strings. At the moment it only finds the first word.
As with the demo https://material.angularjs.org/latest/demo/autocomplete, if you type new, it finds New Jersey. But if you type jersey, it does not find anything.
This is my querySearch function
function querySearch(query) {
    var results = query ? vm.subjects.filter(createFilterFor(query)) : vm.subjects,
        deferred;
    return results;
}

This is my createFilterFor function
function createFilterFor(query) {
    var lowercaseQuery = angular.lowercase(query);
    return function filterFn(subject) {
        return (subject.Display.indexOf(lowercaseQuery) === 0);
    };
}

A: I solved it this way. Note there is an array with tags and and array without used for displaying.
            function querySearch(query) {

            var results = new Array();

            for (var i = 0, len = taggedSubjectArrray.length; i < len; i++) {
                var txtToCompare = taggedSubjectArrray[i].Display;

                if (txtToCompare.indexOf(query) != -1)
                {
                    // string was found
                    // Add to results
                    results.push(validationArrray[i]);
                }
            }

            return results;
        }

A: //This worked for me

function createFilterFor(query) {
        debugger;
        //var lowercaseQuery = angular.lowercase(query);

        return function filterFn(product) {
            var results = new Array();

            var lowercaseQuery = angular.lowercase(query);

            index = 0,
            res = [];
            res.push(-1);

            //Get starting index of each word in string & push in array
            while ((index = product.value.indexOf(' ', index + 1)) >= 0) {
                res.push(index);
            }

            for (var i = 0; i < res.length; i++) {
                var a = res[i] + 1;

                if (product.value.indexOf(lowercaseQuery) === a)
                {
                    return (product.value.indexOf(lowercaseQuery) === a);
                }
            }
        };
    }


text:
Q: Destroying child record destroys parent EDIT: I solved my problem. Instead of a type 'DELETE' AJAX call, I used a type 'POST' call with the {:method: 'DELETE'} as its data value. This seemed to do the trick.
I'm trying to allow deletion of a child element in Rails 4 via an AJAX request, and I'm having this issue. I have a Badge model which has many BadgeElements. The BadgeElements controller contains a destroy method which I know works because in my Show view, the elements are properly being deleted. It's when I try to delete them in my JavaScript file with AJAX that I'm having trouble. Here's my code:
function deleteElement(id) {
  var path_root = $('form').attr('action');
  var delete_path = path_root + "/badge_elements/" + id;
  $.ajax({
    url: delete_path,
    type: 'DELETE'
  });
  $('form').load(path_root + "/edit form");
}

The delete_path attribute evaluates to /badges/[badge_id]/badge_elements/[id], where [id] is the id of the specific element in question. When this function is executed, I get a 400 error at the path ending in /badges, which tells me the badge itself is being deleted. I can confirm this by reloading the page and getting the error "Could not find Badge with badge_id = 4", etc. For reference, here's the model and destroy method for BadgeElement:
badge_element.rb:
class BadgeElement < ActiveRecord::Base
  belongs_to :badge
  belongs_to :font
  scope :front, -> {where(side:"front")}
  scope :back, -> {where(side:"back")}
  validates :font_id, presence: true
end

in badge_elements_controller.rb:
def destroy
  badge = Badge.find(params[:badge_id])
  badge_element = BadgeElement.find(params[:id])
  badge_element.destroy
  redirect_to badge_path(badge)
end

Does anyone know what's going on? Thanks.

A: I've just had this problem.
If your controller has a redirect_to and no sensitivity to the format of the request it will redirect to badge_path(badge) as instructed but the method will still be DELETE, thereby deleting the parent as well as the child.
I think you'll just need a respond_to block like so
def destroy
  ...
  respond_to do |format|
    format.html { redirect_to badge_path(badge) }
    format.js { }
  end
end


text:
Q: JS/HTML5/Meteor How to change an input to a label? I have an input form in html, like this:
<input type = "text" id ="name" placeholder = "Name"/>

I can change the "placeholder" value with:
document.getElementById('name').placeholder = Session.get("username")

After setting the username to the initial input, but I want to actually change the input into a label (let's say a p tag with strong) with Session.get("username") as its value. How?

A: Use a combination of reactivity and templates to achieve what you need the Meteor way.
template_name.html
<template name="template_name">
    {{#if username}}

{{username}}

    {{else}}
        <form>
            <input type="text" name="username" placeholder="username" required />
            <button type="submit">Submit</button>
        </form>
    {{/if}}
</template>

template_name.js
Template.template_name.helpers({
    username:function(){
        return Session.get("username");
    }
});

Template.template_name.events({
    "submit form":function(event,template){
        event.preventDefault();
        var username=template.find("input[name='username']").value;
        Session.set("username",username);
    }
});

When your template will first render, the username helper will be undefined and the else branch will display the input.
When you later set the Session variable after validating user input, it will rerender and display it inside a label.

A: You can use replaceChild() and document.createElement():
var newP = document.createElement('p'),
    newStrong = document.createElement('strong'),
    text = document.createTextNode(Session.get('username')),
    input = document.getElementById('name');

newStrong.appendChild(text);
newP.appendChild(newP);
input.parentNode.replaceChild(newP, input);

References:

*

*Node.appendChild().

*Node.replaceChild().

A: You could use reactivity:
Your JS (client side)
Template.hello.placeholder = function() {
    return Session.get("username");
}

Your HTML
<template name="hello">
    <input type = "text" id ="name" placeholder = "{{placeholder}}"/>
</template>

As soon as you change it with Session.set("username",new value) the new value will be applied reactively.


text:
Q: Discord bot yields error Error[TOKEN_INVALID] An invalid token was provided I'm making a discord bot. After all code was done, I ran node index.js to start the bot. It returned this error:
PS F:\DISCORDBOTS\Ultron> node index.js
F:\DISCORDBOTS\Ultron\node_modules\discord.js\src\client\Client.js:206
    if (!token || typeof token !== 'string') throw new Error('TOKEN_INVALID');
                                                   ^

Error [TOKEN_INVALID]: An invalid token was provided.
    at Client.login (F:\DISCORDBOTS\Ultron\node_modules\discord.js\src\client\Client.js:206:52)
    at Object.<anonymous> (F:\DISCORDBOTS\Ultron\index.js:98:5)
    at Module._compile (node:internal/modules/cjs/loader:1092:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1121:10)
    at Module.load (node:internal/modules/cjs/loader:972:32)
    at Function.Module._load (node:internal/modules/cjs/loader:813:14)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
    at node:internal/main/run_main_module:17:47 {
  [Symbol(code)]: 'TOKEN_INVALID'
}

I am using .env for the Token for the bot. I even regenerated the token many times but it still returns the same error. I could use a config.json file but then the Token will be visible to all on repl.it. How do I resolve this error?

A: We have to provide the token in string format. In client code it is written like this (if (!token || typeof token !== 'string') throw new Error('TOKEN_INVALID');).So try this code.I also have the same error when i change to this code then my code running fine.
    const { Client, Intents } = require('discord.js');
    require("dotenv").config();
    const client = new Client({intents:[Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
    const mySecret = process.env['TOKEN'];
     client.on("ready", () => {
     console.log(`Logged is as ${client.user.tag}!`);
    });

   client.on("message", (msg) => {
    if(msg.content === "ping"){
    msg.reply("pong");
   }
   });

   client.login(mySecret);

A: const mySecret = `${process.env['TOKEN']}`;


text:
Q: SSD TRIM Garbage Collection and affect on MFT Meta Data (security) Does the way a SSD with trim and garbage collection handle deleted files make any changes to the deleted files MFT meta data entries for tiny files? What affect specifically do SSD's have on tiny files less than 1kb that are permanently resident in the MFT?
These are my findings from using conventional mechanical HDD:
I delete this folder and its sub dir and its file from root:
Music/Track/info.txt (400 bytes)
Then I run Recuva real quick and see the file is recoverable and try to erase it and get "file is resident in the MFT, delete failed" message.
I check the MFT and find the file is flagged but all data is still there. So I then have to wait for a new file to overwrite it which could take ages, or use a wiper tool to zero out the flagged MFT entries.
Does a SSD (trim enabled, GC) treat these small files any different? Does it attempt to zero out whats written in the text file so the MFT shows 0's or can't' it touch it because it is resident in the MFT just like with a conventional HDD?


text:
Q: Best way to handle a virtual method for copying a polymorphic object if its base class should not be abstract? I need to copy an object of a polymorphic class having a base pointer. I know that I can implement a virtual method for this. But what if the base class should not be abstract? Leaving the method without pure-specifier can lead to run-time bugs, if you forget reimplement it in the derived. It's uncomfortable. What is the best way to handle this?

A: There are good reasons why you should never want to instantiate a base class.
If you do need to make a empty final class use the following.
class IBase
{
    virtual void SharedCode()
    {
        1 + 1;
        /// code here
    };
    virtual void AbstractDecalration() = 0;
};

class Base final: IBase
{
     void AbstractDecalration() override;
};

Base b{};

All Future Derived classes will be able to use the SharedCode of IBase and you will have a Instantiated class of Base that is final. This is for future proofing your code base.
However I realize that is not the question you asked so here is a implementation were I use a simple check to the vtable pointer of the class to see if I have the correct class.
This is a runtime check and doesn't work across libraries use dynamic_assert if that is the case.
#include <memory>
#include <type_traits>
#include <assert.h>
class Base {
    public:
       auto clone() const
   {
      return std::unique_ptr<Base>(this->clone_impl());
   }
    private:
     virtual Base* clone_impl() const
     {
         Base b{};
         int* bVtablePtr = (int*)((int*)&b)[0];
         int* thisVtablePtr = (int*)((int*)this)[0];
         assert(bVtablePtr == thisVtablePtr);
        return new Base(*this);
    }
};

class Derived : public Base
{
       auto clone() const
   {
      return std::unique_ptr<Derived>(this->clone_impl());
   }
    virtual Derived* clone_impl() const
    {
        return new Derived();
    }
};
class Falty : public Base{};

    int  main(){
        std::unique_ptr<Derived> good(new Derived());
        std::unique_ptr<Falty> falty(new Falty());
        good->clone(); // oke
        falty->clone(); // this function asserts at runtime

}

Note the private clone_impl and public unique_ptr retuning clone method.
Very usefull to prevent memory leaks in your code

A: You can achieve what you want by introducing another abstract base class plus using CRPT for clone function. Then, clone will be automatically implemented in all derived classes "for free" (without manual retyping). Example:
struct Abstract
{
  virtual ~Abstract() {}
  virtual Abstract* clone() const = 0;
  virtual void say() const = 0;
};

template <typename B, typename D>
struct AbstractCloneable : B
{
  virtual B* clone() const override
  {
    return new D(static_cast<const D&>(*this));
  }
};

// original base class
struct Base : AbstractCloneable<Abstract, Base>
{
  virtual void say() const override
  {
    std::cout << "Base" << std::endl;
  }
};

// original derived class #1
struct Derived1 : AbstractCloneable<Base, Derived1>
{
  virtual void say() const override
  {
    std::cout << "Derived1" << std::endl;
  }
};

And a test program:
int main()
{
  std::unique_ptr<Abstract> ptr1 = std::make_unique<Base>();
  ptr1->say();
  std::unique_ptr<Abstract> ptr1_copy{ ptr1->clone() };
  ptr1_copy->say();

  std::unique_ptr<Abstract> ptr2 = std::make_unique<Derived1>();
  ptr2->say();
  std::unique_ptr<Abstract> ptr2_copy{ ptr2->clone() };
  ptr2_copy->say();
}

Which outputs:
Base
Base
Derived1
Derived1

Live demo: https://godbolt.org/z/3FeSTd

See this article for more details and explanations: C++: Polymorphic cloning and the CRTP (Curiously Recurring Template Pattern).


text:
Q: adding attachment from form while sending mail from gmail via php i am trying to add atatchment while sending mail from gmail using php. But it shows error...it says Could not access file: hai.jpg
follwing is the code i use
gmail.php
 <!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>PHPMailer - GMail SMTP test</title>

<?php
 access to that
date_default_timezone_set('Etc/UTC');

require '../Mail/class.phpmailer.php';

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug  = 2;
$mail->Debugoutput = 'html';
$mail->Host       = 'smtp.gmail.com';
$mail->Port       = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth   = true;
$mail->Username   = "name@gmail.com";
//Password to use for SMTP authentication
$mail->Password   = "passwrd";
$mail->SetFrom($_POST['from'], $_POST['from_name']);
$mail->AddReplyTo($_POST['from'],$_POST['from_name']);
$mail->AddAddress($_POST['to'],$_POST['to_name']);
$mail->Subject = 'PHPMailer GMail SMTP test';
$mail->MsgHTML($_POST['message']);
$mail->AltBody = 'This is a plain-text message body';
$mail->AddAttachment($_POST['attachment'],'application/octet-stream');
if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!";
}
?>

index.html
<form action="gmail.php" method="POST">

        From Name:<input type="text" name="from_name" />
        From:<input type="text" name="from" />

        To Name:<input type="text" name="to_name" />
        To:<input type="text" name="to" />

        Message:<textarea  name="message"></textarea>

        Attachment:<input type="file" name="attachment" />

    <input type="submit" value ="Submit"/>
</form>

I dont know what if i am doing the right way here.Can anyone please guide me through this?

A: I've notice the absence of two itens in your code:

*

*The use of the php $_FILES variable, which stores information about the uploaded files

*The use of enctype attribute in your form element, which is required to upload files along with the form.

So, your code must treat this two itens.
Your form will look like this:
<form action="gmail.php" method="POST" enctype="multipart/form-data">

        From Name:<input type="text" name="from_name" />
        From:<input type="text" name="from" />

        To Name:<input type="text" name="to_name" />
        To:<input type="text" name="to" />

        Message:<textarea  name="message"></textarea>

        Attachment:<input type="file" name="attachment" />

    <input type="submit" value ="Submit"/>
</form>

And your code may treat the $_FILES variable:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>PHPMailer - GMail SMTP test</title>

<?php
 //access to that
date_default_timezone_set('Etc/UTC');

require '../Mail/class.phpmailer.php';

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug  = 2;
$mail->Debugoutput = 'html';
$mail->Host       = 'smtp.gmail.com';
$mail->Port       = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth   = true;
$mail->Username   = "name@gmail.com";
//Password to use for SMTP authentication
$mail->Password   = "passwrd";
$mail->SetFrom($_POST['from'], $_POST['from_name']);
$mail->AddReplyTo($_POST['from'],$_POST['from_name']);
$mail->AddAddress($_POST['to'],$_POST['to_name']);
$mail->Subject = 'PHPMailer GMail SMTP test';
$mail->MsgHTML($_POST['message']);
$mail->AltBody = 'This is a plain-text message body';
//Attachs the file only if it was uploaded by http post
if (is_uploaded_file ($_FILES['attachment']['tmp_name'])) {
  $mail->AddAttachment($_FILES['attachment']['tmp_name'],$_FILES['attachment']['name'], 'base64',$_FILES['attachment']['type']);
}
if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!";
}
?>

A: Its not quite that straight forward uploading a file from the client browser to the server.
Here's a simple tutorial


text:
Q: python regex to get numbers placed in different position of a string These are the possible cases of text I have,
4 bedrooms 2 bathrooms 3 carparks
3 bedroom house
Bedrooms 2,
beds 5,
Bedrooms 1,
2 bedrooms, 1 bathroom,
Four bedrooms home, double garage
Four bedrooms home
Three double bedrooms home, garage
Three bedrooms home,
2 bedroom home unit with single carport.
Garage car spaces: 2, Bathrooms: 4, Bedrooms: 7,

I am trying to get the number of bedrooms out of this text. I managed to write the below ones,
  def get_bedroom_num(s):
    if ':' in s:
        out = re.search(r'(?:Bedrooms:|Bedroom:)(.*)', s,re.I).group(1)
    elif ',' in s:
        out = re.search(r'(?:bedrooms|bedroom|beds)(.*)', s,re.I).group(1)
    else:
        out = re.search(r'(.*)(?:bedrooms|bedroom).*', s,re.I).group(1)
    out = filter(lambda x: x.isdigit(), out)
    return out

But it is not capturing all the possible cases. The key here is the word 'bedroom', text will always have the text bedroom either in the front or back of the number. Any better approach to handle this? If not through regex, may be Named Entity Recognition in NLP?
Thanks.
EDIT : -
For case 7 to 10, I managed to convert the word numbers to integer using the below function,
#Convert word to number
def text2int (textnum, numwords={}):
    if not numwords:
        units = [
        "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
        "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
        "sixteen", "seventeen", "eighteen", "nineteen",
        ]

        tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]

        scales = ["hundred", "thousand", "million", "billion", "trillion"]

        numwords["and"] = (1, 0)
        for idx, word in enumerate(units):  numwords[word] = (1, idx)
        for idx, word in enumerate(tens):       numwords[word] = (1, idx * 10)
        for idx, word in enumerate(scales): numwords[word] = (10 ** (idx * 3 or 2), 0)

    ordinal_words = {'first':1, 'second':2, 'third':3, 'fifth':5, 'eighth':8, 'ninth':9, 'twelfth':12}
    ordinal_endings = [('ieth', 'y'), ('th', '')]

    textnum = textnum.replace('-', ' ')

    current = result = 0
    curstring = ""
    onnumber = False
    for word in textnum.split():
        if word in ordinal_words:
            scale, increment = (1, ordinal_words[word])
            current = current * scale + increment
            if scale > 100:
                result += current
                current = 0
            onnumber = True
        else:
            for ending, replacement in ordinal_endings:
                if word.endswith(ending):
                    word = "%s%s" % (word[:-len(ending)], replacement)

            if word not in numwords:
                if onnumber:
                    curstring += repr(result + current) + " "
                curstring += word + " "
                result = current = 0
                onnumber = False
            else:
                scale, increment = numwords[word]

                current = current * scale + increment
                if scale > 100:
                    result += current
                    current = 0
                onnumber = True

    if onnumber:
        curstring += repr(result + current)

    return curstring

so, 'Four bedrooms home, double garage' can be converted to '4 bedrooms home, double garage' with this function before doing any regex to get the number.

A: You can use following regex to find all different combinations and extract the bedroom number info,
(\w+\+?) *(?:double +)?bed(?:room)?s?|bed(?:room)?s?:? *(\d+\+?)

To precisely list only words form of number, you can change (\w+) to \b(?:one|two|Three|Four|five|six|seven|eight|nine|ten|\d+)\b
Online Demo
Since the regex has alternation groups, where the captured information may be available in either group1 or group2, this Python code shows how you can extract the data from appropriately captured group in the regex,
import re

def getRoomInfo(s):
 numRooms = re.search(r'(\w+\+?) *(?:double +)?bed(?:room)?s?|bed(?:room)?s?:? *(\d+\+?)', s, re.IGNORECASE)
 if (numRooms):
  if (numRooms.group(1) is not None):
   return numRooms.group(1)
  elif (numRooms.group(2) is not None):
   return numRooms.group(2)

arr = ['4 bedrooms 2 bathrooms 3 carparks','3 bedroom house','Bedrooms 2, ','beds 5,','Bedrooms 1, ','2 bedrooms, 1 bathroom, ','Four bedrooms home, double garage','Four bedrooms home','Three double bedrooms home, garage','Three bedrooms home,','2 bedroom home unit with single carport.','Garage car spaces: 2, Bathrooms: 4, Bedrooms: 7,\\\\', 'Three bedroom bungalow with conservatory and", "One bedroom unit","4+ bedroom(s), 2 bathroom(s), 2 garage(s)']

for s in arr:
 print(s, ' --> ', getRoomInfo(s))

Prints following,
4 bedrooms 2 bathrooms 3 carparks  -->  4
3 bedroom house  -->  3
Bedrooms 2,   -->  2
beds 5,  -->  5
Bedrooms 1,   -->  1
2 bedrooms, 1 bathroom,   -->  2
Four bedrooms home, double garage  -->  Four
Four bedrooms home  -->  Four
Three double bedrooms home, garage  -->  Three
Three bedrooms home,  -->  Three
2 bedroom home unit with single carport.  -->  2
Garage car spaces: 2, Bathrooms: 4, Bedrooms: 7,\\  -->  7
Three bedroom bungalow with conservatory and", "One bedroom unit","4+ bedroom(s), 2 bathroom(s), 2 garage(s)  -->  Three

Edit2: Another version of Python code where it captures all the matches in string and returns the result as a list
import re

def getRoomInfoAll(s):
 matches = []
 pattern = re.compile(r'(\w+\+?) *(?:double +)?bed(?:room)?s?|bed(?:room)?s?:? *(\d+\+?)', re.IGNORECASE)
 for numRooms in pattern.finditer(s):
  if (numRooms.group(1) is not None and len(numRooms.group(1)) > 0):
   matches.append(numRooms.group(1))
  elif (numRooms.group(2) is not None and len(numRooms.group(2)) > 0):
   matches.append(numRooms.group(2))
 return matches

arr = ['4 bedrooms 2 bathrooms 3 carparks','3 bedroom house','Bedrooms 2, ','beds 5,','Bedrooms 1, ','2 bedrooms, 1 bathroom, ','Four bedrooms home, double garage','Four bedrooms home','Three double bedrooms home, garage','Three bedrooms home,','2 bedroom home unit with single carport.','Garage car spaces: 2, Bathrooms: 4, Bedrooms: 7,\\\\', 'Three bedroom bungalow with conservatory and", "One bedroom unit","4+ bedroom(s), 2 bathroom(s), 2 garage(s)']

for s in arr:
 print(s, ' --------> ', getRoomInfoAll(s))

Here it prints all the matches found in the string.
4 bedrooms 2 bathrooms 3 carparks  -------->  ['4']
3 bedroom house  -------->  ['3']
Bedrooms 2,   -------->  ['2']
beds 5,  -------->  ['5']
Bedrooms 1,   -------->  ['1']
2 bedrooms, 1 bathroom,   -------->  ['2']
Four bedrooms home, double garage  -------->  ['Four']
Four bedrooms home  -------->  ['Four']
Three double bedrooms home, garage  -------->  ['Three']
Three bedrooms home,  -------->  ['Three']
2 bedroom home unit with single carport.  -------->  ['2']
Garage car spaces: 2, Bathrooms: 4, Bedrooms: 7,\\  -------->  ['7']
Three bedroom bungalow with conservatory and", "One bedroom unit","4+ bedroom(s), 2 bathroom(s), 2 garage(s)  -------->  ['Three', 'One', '4+']


text:
Q: In implements method, addmarker do not work / GoogleMap, Android CODE
public class BlueFragment2 extends Fragment implements OnMapReadyCallback, GoogleMap.OnMyLocationButtonClickListener {

    private GoogleMap googleMap;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_blue, container, false);
        MapView mapview = (MapView) view.findViewById(R.id.map_blue);
        mapview.onCreate(savedInstanceState);
        mapview.onResume();
        mapview.getMapAsync(this);

        return view;
    }

    @Override
    public void onMapReady(final GoogleMap googleMap) {
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        googleMap.setMyLocationEnabled(true);
    }

    @Override
    public boolean onMyLocationButtonClick() {
        LatLng point = new LatLng(googleMap.getMyLocation().getLatitude(), googleMap.getMyLocation().getLongitude());
        MarkerOptions marker = new MarkerOptions()
                .position(point).title("ok");
        googleMap.clear();
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(point, 14));
        googleMap.addMarker(marker);
        return true;
    }
}

I wanted that OnMyLocationButton click will addmarker on the google map.
But it doesn't work.
If i wrote on public void onMapReady like
@Override
public void onMapReady(final GoogleMap googleMap) {
    if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    googleMap.setMyLocationEnabled(true);

    googleMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
        @Override
        public boolean onMyLocationButtonClick() {
            LatLng point = new LatLng(googleMap.getMyLocation().getLatitude(), googleMap.getMyLocation().getLongitude());
            MarkerOptions marker = new MarkerOptions()
                    .position(point).title("ok");
            googleMap.clear();
            googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(point, 14));
            googleMap.addMarker(marker);
            return true;
        }
    });
}

It works well.
Why this do not work?
Would you help me?
Question :
Is there any other way except writing on public void onMapReady?
Is there my fault in using implements googleMap.OnMyLocationButtonClickListener?


text:
Q: Generate multiple Visio files from a database I have an Access database containing information about multiple clients.
I can put these datas into one table (1 row = 1 client).
I want to create vsd files from this table. I want to draw a Template and associate forms with fields.
I'm new in Visio, but I succeed in mapping a table to a draw, but I don't know how to ask Visio to generate a file per row. I'll appreciate any help.

A: I don't think it's possible, so I wrote a PowerShell script to do the job.
For each row, it open and edit the Template and save it Under a new name.


text:
Q: jquery-steps : disable submit button when form are submited I'm using jquery-steps.js ,
I want to disable submit button when some one click on submit, and never activate it until the the form is submitted.
The reason way is that if some one click on submit many time the I receive many mails!
Note : my HTML file does not include submit button , it is only show from the js file that I include bellow
and my js file look like this.
$(function() {
    $("#smart-form").steps( {
        bodyTag:"fieldset", headerTag:"h2", bodyTag:"fieldset", transitionEffect:"slideLeft", titleTemplate:"#index# #title#", labels: {
            finish: "Send søknad", next: "Neste", previous: "Tilbake", loading: "Laster..."
        }
        , onStepChanging:function(event, currentIndex, newIndex) {
            if(currentIndex>newIndex) {
                return true;
            }
            var form=$(this);
            if(currentIndex<newIndex) {}
            return form.valid();
        }
        , onStepChanged:function(event, currentIndex, priorIndex) {}
        , onFinishing:function(event, currentIndex) {
            var form=$(this);
            form.validate().settings.ignore=":disabled";
            return form.valid();
        }
        , onFinished:function(event, currentIndex) {
            var form=$(this);
            $(form).ajaxSubmit( {
                target:'.result', beforeSubmit:function() {}
                , error:function() {}
                , success:function() {
                    $('.alert-success').show().delay(7000).fadeOut();
                    $('.field').removeClass("state-error, state-success");
                    if($('.alert-error').length==0) {
                        $('#smart-form').resetForm();
                        reloadCaptcha();
                    }
                }
            }
            );
        }
    }

A: This might be a bit generic (and I haven't tested it) but that can get you started
$(document).find('input[type="submit"').prop('disabled', 'disabled');

A: After the first line $(function() {, add :
var isFinishing = false;

In the onFinished event change this line :
var form=$(this);

for :
if (isFinishing) return;

isFinishing = true;
var form=$(this);

If the success event of the AJAX call isn't reloading the page, you shall consider adding this line within this function :
isFinishing = false;


text:
Q: Interpreting SQL Server table statistics I write queries and procedures, I have no experience as a DB Admin and I am not in a position to be such. I work with hundreds of tables and certain older tables are difficult to work with. I suspect that statistics are a problem but the DBA states that isn't the case.
I don't know how to interpret statistics or even which ones I should look at. As an example, I am currently JOINing 2 tables, it is a simple JOIN that uses an index.
It returns just under 500 rows in 4 columns. It runs very quickly but not when in production with thousands of runs a day. My estimated and actual rows on this JOIN are off by 462%.
I have distilled this stored procedure down to a lot of very basic temp tables to locate the problem areas and it appears to be 2 tables, this example is one of them.

What I want is to know is which commands to run and what statistics to look at to take to the DBA to discuss the specific problem at hand. I do not want to be confrontational but informational. I have a very good professional relationship with this DBA but he is very black and white with his policies so I may not get anywhere with it in the end, but then I can also take that to my lead if I get stonewalled.
I ran a DBCC SHOW_STATISTICS on the table's index. I am not sure if this is the data I need or what I am really looking at. I would really like to know where to start with this. I have googled but all the pages I read are very geared towards DBAs and assume prior knowledge in areas I don't have.

Below is a sample of my JOIN obfuscated - my JOIN is on a temp table the first 2 conditions are needed for the Index, the date conditions when removed make the JOIN actually much worse with 10x the reads:
SELECT
    x.UniqueID,
    x.ChargeCode,
    x.dtDate,
    x.uniqueForeignID
INTO
    #AnotherTempTable
FROM
    Billing.dbo.Charges x
JOIN
    #temptable y ON x.uniqueForeignID = y.uniqueID
                 AND x.ChargeCode = y.ChargeCode
                 AND @PostMonthStart <= x.dtDate
                 AND x.dtDate < @PostMonthEnd

The JOIN above is part of a new plan where I have been dissecting all the data needed into temp tables to determine the root cause of the problem in high CPU and reads in production.  Below is a list of all the statements that are executing, sorted by the number of reads.  The second row is this example query but there are others with similar issues.

Below is the execution plan operations for the plan prior to my updates.

While the new plan has better run time and closer estimates, I worry that I am still going to run into issues if the statistics are off.  If I am completely off-base, please tell me and point me in the right direction, I will gladly bark up a different tree if I am making incorrect assumptions.

A: The first table returned shows some general information.  You can see the statistics on this index were last updated 12/25/2019 at 10:19 PM.  As of the writing of this answer, that is yesterday evening, so stats were updated recently.  That is likely to be some kind of evening maintenance, but it could also be a threshold of data modifications that triggered an automatic statistics update.
There were 222,596,063 rows in the table at the time the statistics were sampled.  The statistics update sampled 626,452 of these rows, so the sample rate is 0.2%.  This sample size was likely the default sample rate used by a simple update statistics MyTable command.
A sample rate of 0.2% is fast to calculate but can lead to very bad estimates-- especially if an index is being used to support a foreign key.  For example, a parent/child relationship may have a ParentKey column on the child table.  A low statistics sample rate will result in very high estimates per parent row which can lead to strange decisions in query plans.
Look at the third table (the histogram).  The RANGE_HI_KEY corresponds to a specific key value of the first column in this index.  The EQ_ROWS column is the histogram's estimate of the number of rows that correspond to this key.  If you get a count of the rows in this table by one of these keys in the RANGE_HI_KEY column, does the number in the EQ_ROWS column look like an accurate estimate?  If not, a higher sample rate may yield better query plans.
For example, take the value 1475616.  Is the count of rows for this key close to the EQ_ROWS value of 3893?
select count(*) from MyTable where FirstIndexColumn = 1475616

If the estimate is very bad, the DBA may need to increase the sample size on this table:
update statistics MyTable with sample 5 percent

If the DBA uses Ola Hallengren's plan (an excellent choice, in my opinion), this can be done by passing the @StatisticsSample parameter to the IndexOptimize procedure.


text:
Q: UISegmentedControl deselected is not recognised in code although it is visually I have a 5 segment segmentedControl which I've subclassed using the code from this post:
How to deselect a segment in Segmented control button permanently till its clicked again
to allow the controller to be deselected when the selected segment is touched for a second time.
This works visually but when trying to assign a UserDefault it's just recognised as the segment that was touched twice.
I can't figure out what I can add to either the subclass code, or the viewController code to make this work.
Any help would be appreciated.
SUBCLASS CODE:
class mySegmentedControl: UISegmentedControl {
    @IBInspectable var allowReselection: Bool = true

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        let previousSelectedSegmentIndex = self.selectedSegmentIndex
        super.touchesEnded(touches, with: event)
        if allowReselection && previousSelectedSegmentIndex == self.selectedSegmentIndex {
            if let touch = touches.first {
                let touchLocation = touch.location(in: self)

                if bounds.contains(touchLocation) {
                    self.sendActions(for: .valueChanged)
                    self.selectedSegmentIndex = UISegmentedControlNoSegment
                }
            }
        }
    }

}
VIEWCONTROLLER CODE:
@IBOutlet weak var METDome_L: UISegmentedControl!
let key_METDome_L = "METDome_L"
var METD_L: String!

@IBAction func METDome_Lselect(_ sender: Any) {
    if METDome_L.selectedSegmentIndex == 0{
        METD_L = "1"
        UserDefaults.standard.set(METD_L, forKey: key_METDome_L)
    }
    else if METDome_L.selectedSegmentIndex == 1{
        METD_L = "2"
        UserDefaults.standard.set(METD_L, forKey: key_METDome_L)
    }
    else if METDome_L.selectedSegmentIndex == 2{
        METD_L = "3"
        UserDefaults.standard.set(METD_L, forKey: key_METDome_L)
    }
    else if METDome_L.selectedSegmentIndex == 3{
        METD_L = "4"
        UserDefaults.standard.set(METD_L, forKey: key_METDome_L)
    }
    else if METDome_L.selectedSegmentIndex == 4{
        METD_L = "5"
        UserDefaults.standard.set(METD_L, forKey: key_METDome_L)
    }
    else{
        METD_L = "NONE"
        UserDefaults.standard.set(METD_L, forKey: key_METDome_L)
    }
}

A: First of all if you are subclassing the control you have to use that type to get the enhanced functionality.
@IBOutlet weak var METDome_L: MySegmentedControl! // class names start with a capital letter

Add a property selectionKey and save the state UISegmentedControlNoSegment (as Int) in UserDefaults when the control is deselected. A fatal error is thrown if the property is empty (it has to be set in the view controllers which use the subclass).
class MySegmentedControl: UISegmentedControl {
    @IBInspectable var allowReselection: Bool = true

    var selectionKey = ""

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        let previousSelectedSegmentIndex = self.selectedSegmentIndex
        super.touchesEnded(touches, with: event)
        if allowReselection && previousSelectedSegmentIndex == self.selectedSegmentIndex {
            if let touch = touches.first {
                let touchLocation = touch.location(in: self)

                if bounds.contains(touchLocation) {
                    self.sendActions(for: .valueChanged)
                    self.selectedSegmentIndex = UISegmentedControlNoSegment
                    guard !selectionKey.isEmpty else { fatalError("selectionKey must not be empty")
                    UserDefaults.standard.set(UISegmentedControlNoSegment, forKey: selectionKey)
                }
            }
        }
    }
}

In your view controller set the property selectionKey in viewDidLoad to the custom key and save the selected state of the control to UserDefaults in the IBAction. Do not any math. The first segment is segment 0 with index 0. Get used to zero-based indices. That makes it more convenient to restore the selected state.
@IBOutlet weak var METDome_L: MySegmentedControl!
let key_METDome_L = "METDome_L"

override func viewDidLoad()
{
    super.viewDidLoad()
    METDome_L.selectionKey = key_METDome_L
}

@IBAction func METDome_Lselect(_ sender: UISegmentedControl) {
    UserDefaults.standard.set(sender.selectedSegmentIndex, forKey: key_METDome_L)
}


text:
Q: Bulk convert Doc to Docx using c# I have legacy folder with mix of all kinds of files numbering around 55,000 over the network drive. I have to convert all doc format to .docx format file, there are around 40,000 files in doc format. So far, I have tried following approach
1) MS Office Migration Planning Manager and MS Office Compatibility Pack as suggested at these two links1  and Link2 .
 Both of theses approach are same. In this case each file Conversion takes almost 25 seconds because it also processes other format file like .xls in addition to conversion. That means whole conversion will take 4-5 days even if I use multiple machines with distributed folders.
2) Third Party Tools like ASPOS and NPOI: NPOI doesn't have docx support yet. I am using trial version of ASPOS, Although it takes two seconds/ file but it truncates all pages but first and adds its copyright message at header. Since conversion of folder is only one time effort so buying a licensed version is not feasible.
3) MS office interop library or Word 14.0 Object Library: it takes more than 30 seconds / file over network. So not considering it at all.
My conversion target is less than 5 seconds/file. Because we'll not get more that one day to access the secured n/w drive.


text:
Q: How to get original IP address of a client in java? We can get client IP address from Request object as follows:
 String ipAddress = request.getRemoteAddr();

But, if the user is behind a proxy server or access your web server through a load balancer, the above code will get the IP address of the proxy server or load balancer server, not the original IP address of a client.

A: If we are talking about HTTP requests, you may try the following:
String strForwardedFor = httpServletRequest.getHeader("X-Forwarded-For");

If the proxy sets this header, it should look like:
client-ip,proxy1-ip,proxy2-ip,...


text:
Q: Implementing a Mealy Machine in Verilog I have a piece of code that I don't understand:
always_ff @(posedge CLK)
state <= RST || ~A[0]===1'bx || ~A[1]===1'bx ? 0 : nextstate;

A is the input. What is this piece of code exactly doing? What is ~A[0]===1'bx or ~A[1]===1'bx?
My guess is that this code is checking if either one of the inputs aren't valid (1'bx). If one of the inputs aren't valid, we jump back to the starting state 0.
But why the negation in ~A[0]===1'bx?

A: I assume this is a shortcut for:
A[0]===1'bx || A[0]===1'bz

If A[0] is 1'bx ~A[0] will still be 1'bx.
If A[0] is 1'bz ~A[0] will make it 1'bx.
I have to assume this is in a test bench because that code can not be synthesized.


text:
Q: Switching JPanel in JFrame from inside the JPanel I'm trying to build a dynamic application based on buttons that switch the main Panel of a JFrame (which is the top content of my application) from inside the created panel.
The question is more related to a design question rather than a development question. I'm not sure of my design, but i'll try to explain it.
I have A JFrame representing my application which contains a JTabbedPane (and multiples Tabs in it). Each tab contains a default JPanel, and inside that JPanel, i'm calling a controller which is rendering my View (I'm trying to use a MVC Pattern).
But from the so called View, I have buttons which have to switch the content of the JPanel (Jpanel contained in the JTabbedPane). And I'm searching the best way to switch the View, without breaking the standard rules of OOP.
Schematically :
JFrame
    JTabbedPane
        JPanel
            View1
                Button (pointing somehow to View2)
        JPanel
            View3
                 Button (pointing somehow to View4)

When I click on the button from view 1, I would like to have this :
JFrame
    JTabbedPane
        JPanel
            View2
                ...
        JPanel
            View3
                 Button (pointing somehow to View4)

And, once the View 2 is loaded, if I go to the View3 through the JTabbedPane and click the View3.button, I would like to have something like this  :
JFrame
    JTabbedPane
        JPanel
            View2
                ...
        JPanel
            View4
                 ...

As I said it's more a design problem. Is my "design" good enough to not have to give to each component a reference of the JFrame ? How can I perform that ?
I hope there are not so much errors in my text, English is not my native language. Moreover, any corrections on my writing skills in english are welcome.
Thank you.

A: I'd say your JTabbedPane is the class interested in panels - as it's the JTabbedPane which will get it's contents switched.
So I'd say extend JTabbedPane to ?TabbedPane (where ? stands for 'My' or whatever the naming convention in your project is), and make it extend ActionListener, like this:
public class MyTabbedPane extends JTabbedPane implements ActionListener {
    ...
    public void actionPerformed(ActionEvent aev) {
        // replace panels
        revalidate();
        repaint();
    }
}

Then register the tabbed pane as an action listener where needed (the buttons, probably).
If there's more than one panel to switch to, you'll need some more code to pass the state.
You could write your own listener:
public class PanelSwitchActionListener {
    public void panelSwitchRequested(...);
}

Then pass Enum denoting which panel to switch to, or maybe even the panel itself in the (...) part of panelSwitchRequested() method. Then add an Action(Listener) to the buttons and make them fire panelSwitchRequested() against registered PanelSwitchActionListener (which will hopefully be your JTabbedPane).

A: I'd try and fall back on a model.  The model would maintain a list of views and a means by which, given a view reference, it could return the next view (ie model.getNextView(view)).
This model could be passed to your controller (in this I'd say a custom JTabbedPane as mention by pafau) that could construct all the tabs as required.  This way you decouple of the navigation mechanism from the view and delegate the logic to the model instead.

A: Personally, I would reconsider a design that uses both tabbed panes and switches between Views. Usually tis either/or with tabbed panes being preferred.
However, if you still need it that way, try to think about your views differently. I think the JPanels are actually the Views. If you attach a Controller to each View and a Model to each Controller, you'll be able to switch between them without putting too much logic in your Views or your Controllers, but still decoupling your Views from your Models. I put a rough example together that uses CardLayout and a Null Object, but is otherwise fairly straightforward. And of course, all the classes should be renamed to something that fits your project.
View.java
public class View extends JPanel {

    private CardLayout layout;

    public View(Controller controller, JComponent... subviews) {
        layout = new CardLayout();
        setLayout(layout);

        for (int index = 0; index < subviews.length; ++index) {
            JButton changeButton = new JButton("Change");
            changeButton.addActionListener(controller);
            subviews[index].add(changeButton);
            add(subviews[index], "View" + index);
        }
    }

    public void setSubview(int index) {
        layout.show(this, "View" + index);
    }

}

NullView.java
public class NullView extends View {

    public NullView() {
        super(null);
    }

    @Override
    public void setSubview(int index) {
        // do nothing
    }

}

Controller.java
public class Controller implements ActionListener {

    private Model model;

    private View view;

    public Controller(Model model) {
        this.model = model;
        this.view = new NullView();
    }

    public void setView(View view) {
        this.view = view;
    }

    public void actionPerformed(ActionEvent e) {
        model.nextIndex();
        view.setSubview(model.getCurIndex());
    }

}

Model.java
public class Model {

    private int nViews;

    private int curIndex;

    public Model(int nViews) {
        if (nViews <= 0) nViews = 1;
        this.nViews = nViews;
    }

    public void nextIndex() {
        curIndex = (curIndex + 1) % nViews;
    }

    public int getCurIndex() {
        return curIndex;
    }

 }

In your content pane:
 Controller controller1 = new Controller(new Model(2));

 View view1 = new View(controller1, subview1, subview2);
 controller1.setView(view1);

 Controller controller2 = new Controller(new Model(3));

 View view2 = new View(controller2, subview3, subview4, subview5);
 controller2.setView(view2);

 JTabbedPane tabbedPane = new JTabbedPane();
 tabbedPane.addTab("Tab1", view1);
 tabbedPane.addTab("Tab2", view2);


text:
Q: How to make image to fit inside the container with padding and margin set? I have the css code below which defines the body-content wrapper class, and I need images to fit inside the wrapper, but they are extending out of it.
I tried setting overflow on the wrapper to be auto but that doesn't work either.

body {
    background-color:#231f20;
}
.body-content {
    padding-left:50px;
    padding-right:50px;
    margin-left:50px;
    margin-right:50px;

}

div.logoimg{
   background-image: url( https://i.stack.imgur.com/z3XY6.png);
   width:291px;
   height:65px;

   max-width: 100%;
   max-height: 100%;
   float: left;
   overflow: auto;

}
.largeimg{

   background-image: url(https://i.stack.imgur.com/3B2Un.jpg);
   width:1460px;
   height:369px;
   max-width: 100%;
   max-height: 100%;
   background-size: 100%;
   background-repeat: no-repeat;

   z-index: -1;
   overflow: auto;/*hidden;*/
   position: relative;
   display: block;
}
    .menu{
    padding-top:20px;
    padding-bottom: 9px;
    padding-left:20px;
    background-color: #231f20;
    float:left;
    width: auto;
    overflow: hidden;

}

.menu ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;

}

.menu ul li {
    float: left;

}
.menu ul li  a {
    display: block;
    padding: 8px;
    background-color:#231f20;
    color:  #ffd41b;
}
.menu ul li a:hover{
     display: block;
     background-color: #ffd41b;
     color:  #231f20;
}
.menu ul li.icon {
    display: none;
}

@Html.ActionLink("Home", "Index", "Home")

@Html.ActionLink("About Us", "Index", "About")

@Html.ActionLink("Contact", "Contact", "Home")

☰

This resulting page looks like this:
I need images to be responsive and to fit inside the container with paddings and margins like this:

I tried was searching the internet for a solution but I found only the overflow suggestion which didn't work.
How do I get the images to stay inside the container?


text:
Q: customer debt report laravel 5.3 I have laravel project with vouchers table
this is the structure of the vouchers table
      Schema::create('vouchers', function (Blueprint $table) {
        $table->increments('id');
        $table->string('voucher_number',25)->unique();
        $table->integer('voucher_dealer');
        $table->date('voucher_date');
        $table->integer('voucher_customer_id');
        $table->double('voucher_amount');
        $table->text('voucher_note');
        $table->integer('voucher_type');
        $table->integer('voucher_inserter');
        $table->timestamps();
        $table->softDeletes();
    });

And the model name is Voucher
Now when i need to get customer voucher i use this relation
public function CustomerReportGet(Request $request)
{
    $full = Voucher::where('voucher_customer_id','=',$request->customer_id)->sum('voucher_amount');
    if($request->from_date == '' and $request->to_date == '')
        $data = Voucher::where('voucher_customer_id','=',$request->customer_id)->get();
    elseif($request->from_date <> '' or $request->to_date <> '')
    {
        $data = Voucher::where('voucher_customer_id','=',$request->customer_id)->
                whereBetween('created_at',array($request->from_date,$request->to_date));
    }
    return array($full,$data);
}

And i have them as ajax request in the blade page
now my problem is that when i create the report
its should be like this ..
customer id
voucher date
voucher amount
customer balance till the voucher date
how can i let laravel always sum the voucher_amount till every voucher_date in the blade
thanks

A: Try the following:
public function CustomerReportGet(Request $request)
{
    $full = Voucher::where('voucher_customer_id','=',$request->customer_id);
    if($request->from_date == '' and $request->to_date == '')
        $full->sum('voucher_amount')->get();
    elseif($request->from_date <> '' or $request->to_date <> '')
    {
                $full->whereBetween('created_at',array($request->from_date,$request->to_date))->sum('voucher_amount')->get();
    }

    return array($full,$data);
}


text:
Q: SAS concatenating multiple variables with various formats I have a data set where I need to combine multiple variables into a record_id.
However some of these variables are formatted in such a way that Variable A = 1 because 1st/ 26 and for variable C Feb = 2 because it is the second month.
    a b   c   d e f g   PersonalID

    O S Feb   1 1 0 1   151921101
    S A MAR   0 0 0 0   19130000
    B E JUN   1 3 1 1   2561311

    data test;
    set Redcap;
    PersonalID=cats(a,b,c,d,e,f,g);
    keep PersonalID a b c d e f g;
    run;

How do I change it so that it comes out not with the numeric format, but with the character format?
So that it appears as
    PersonalID
    OSFeb1101
    SAMar0000
    BEJun1311

A: cats is doing the default conversion (best12., probably).  If you want the variable's formatted value, you want to use vvalue to get that.
personalID = cats(vvalue(a),vvalue(b),...)


text:
Q: Headset Microphone is not detected on Ubuntu 20.04 on Dell Inspiron 15 5000 series A Bluetooth Headset Speaker is working fine but microphone is not shown in the input list in sound setting. By default it used built-in laptop microphone.
I have tried a lots of AskUbuntu answers but nothing worked for me.


text:
Q: Choices are shown for each flags in argParser python argParser.add_argument(
            "--operation",
            "-o",
            action="store",
            required=True,
            choices=["VIEW","ADD","EDIT","DELETE"],
            type=str.upper
        )

Actual Output:
root$ myArg -h
required arguments:
  --operation {VIEW,ADD,EDIT,DELETE,INFO}, -o {VIEW,ADD,EDIT,DELETE,INFO}

Required Output:
root$ myArg -h
required arguments:
  --operation/-o {VIEW,ADD,EDIT,DELETE,INFO}

Thanks in advance

A: The short answer to your question is: your requirements are contrary to what the module does.
Consider argparse.py:652 (version 1.1; Anaconda3, python 3.7.6)
    # if the Optional takes a value, format is:
    #    -s ARGS, --long ARGS
    else:
        default = self._get_default_metavar_for_optional(action)
        args_string = self._format_args(action, default)
        for option_string in action.option_strings:
            parts.append('%s %s' % (option_string, args_string))

What you see is the explicitly intended behavior.
I don't see any obvious parameters that would alter this behavior. The only option I see (after, admittedly, 3 minutes of looking) is to create a custom formatter that is exactly like the default one with the offending method (_format_action_invocation) overridden so that you can do something different than the shipped behavior.
Here's an example of something that at least has the trait of doing what you want. I copied the code from argparse.py and changed the offending code to do what you'd prefer.
import argparse

class CustomFormatter(argparse.HelpFormatter):
    def _format_action_invocation(self, action):
        if action.option_strings and action.nargs != 0:
            # This is the code path that we don't like.
            default = self._get_default_metavar_for_optional(action)
            args_string = self._format_args(action, default)
            return '%s %s' % ('/'.join(action.option_strings), args_string)

        # For everything else, use the default behavior.
        return super()._format_action_invocation(action)

argParser = argparse.ArgumentParser( formatter_class = CustomFormatter )
argParser.add_argument(
            "--operation",
            "-o",
            action="store",
            required=True,
            choices=["VIEW","ADD","EDIT","DELETE"],
            type=str.upper
        )

argParser.parse_args()

Here's the output:
# python soln.py --help
usage: soln.py [-h] --operation {VIEW,ADD,EDIT,DELETE}

optional arguments:
  -h, --help            show this help message and exit
  --operation/-o {VIEW,ADD,EDIT,DELETE}


text:
Q: DNAT to 127.0.0.1 with iptables / Destination access control for transparent SOCKS proxy I have a server running on my local network that acts as a router for the computers in my network. I want to achieve now that outgoing TCP requests to certain IP addresses are tunnelled through an SSH connection, without giving the people from my network the possibility to use that SSH tunnel to connect to arbitrary hosts.
The approach I had in mind until now was to have an instance of redsocks listening on localhost and to redirect all outgoing requests to the IP addresses I want to divert to that redsocks instance. I added the following iptables rule:
iptables -t nat -A PREROUTING -p tcp -d 1.2.3.4 -j DNAT --to-destination 127.0.0.1:12345

Apparently, the Linux kernel considers packets coming from a non-127.0.0.0/8 address to an 127.0.0.0/8 address as "Martian packets" and drops them. What worked, though, was to have redsocks listen on eth0 instead of lo and then have iptables DNAT the packets to the eth0 address instead (or using a REDIRECT rule). The problem about this is that then every computer on my network can use the redsocks instance to connect to every host on the internet, but I want to limit its usage to a certain set of IP addresses only.
Is there any way to make iptables DNAT packets to 127.0.0.1? Otherwise, does anyone have an idea how I could achieve my goal without opening up the tunnel to everyone?
Update: I have also tried to change the source of the packets, without any success:
iptables -t nat -A POSTROUTING -p tcp -s 192.168.1.0/24 -d 1.2.3.4 -j SNAT --to-source 127.0.0.1
iptables -t nat -A POSTROUTING -p tcp -s 192.168.1.0/24 -d 127.0.0.1 -j SNAT --to-source 127.0.0.1

A: You cannot do this trick with 127/8 network as it is treaded specially inside linux kernel. But you can create dummy network interface, assign ip address to it, bind your service to this address and do NAT.
root@vm8583:~# ip link add bogus type dummy
root@vm8583:~# sysctl net.ipv4.conf.eth0.arp_ignore=3
root@vm8583:~# ip addr add 10.0.0.1/32 bogus scope host
root@vm8583:~# ip link set bogus up
root@vm8583:~# ip link show bogus
4: bogus: <BROADCAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN mode DEFAULT
    link/ether 5e:8b:38:f3:46:ce brd ff:ff:ff:ff:ff:ff

Note, you may need to set net.ipv4.conf.eth0.arp_ignore=3 so your server won't answer to ARP requests for 10.0.0.1 incoming via eth0:
arp_ignore - INTEGER
    Define different modes for sending replies in response to
    received ARP requests that resolve local target IP addresses:
. . .
    3 - do not reply for local addresses configured with scope host,
    only resolutions for global and link addresses are replied
    4-7 - reserved

A: I found the solution to my dnat to 127.0.0.1(loopback) failing, got the answer on the netfilter irc channel.
There is a sysctl setting allowing dnat to loopback.
To allow it
sysctl -w net.ipv4.conf.eth0.route_localnet=1

and to check the setting
cat /proc/sys/net/ipv4/conf/eth0/route_localnet

A: You could try disabling reverse path filtering instead (which AFAICT is what is meant by the term "martian"). You can do this with echo 0 > /proc/sys/net/ipv4/conf/all/rp_filter as root. (You may be able to only disable it on the lo interface, but I would try disabling it completely at first.)


text:
Q: Rename columns in a pandas.DataFrame via lookup from a Series I have a DataFrame with columns like:
>>> df.columns
['A_ugly_column_name', 'B_ugly_column_name', ...]

and a Series, series_column_names, with nice column names like:
>>> series_column_names = pd.Series(
    data=["A_ugly_column_name", "B_ugly_column_name"],
    index=["A", "B"],
)
>>> print(series_column_names)
A         A_ugly_column_name
B         B_ugly_column_name
...
Name: column_names, dtype: object

Is there a nice way to rename the columns in df according to series_column_names? More specifically, I'd like to rename the columns in df to the index in column_names where value in the series is the old column name in df.
Some context - I have several DataFrames with columns for the same thing, but they're all named slightly differently. I have a DataFrame where, like here, the index is a standardized name and the columns contain the column names used by the various DataFrames. I want to use this "name mapping" DataFrame to rename the columns in the several DataFrames to the same thing.
a solution i have...
So far, the best solution I have is:
>>> df.rename(columns=lambda old: series_column_names.index[series_column_names == old][0])

which works but I'm wondering if there's a better, more pandas-native way to do this.

A: first create a dictionary out of your series by using .str.split
cols = {y : x for x,y in series_column_names.str.split('\s+').tolist()}

print(cols)

Edit.
If your series has your target column names as the index and the values as the series you can still create a dictionary by inversing the keys and values.
cols = {y : x for x,y in series_column_names.to_dict().items()}

or
cols = dict(zip(series_column_names.tolist(), series_column_names.index))

print(cols)
{'B_ugly_column_name': 'B_nice_column_name',
 'C_ugly_column_name': 'C_nice_column_name',
 'A_ugly_column_name': 'A_nice_column_name'}

then assign your column names.
df.columns = df.columns.map(cols)

print(df)

   A_nice_column_name  B_nice_column_name
0                   0                   0

A: Just inverse the index/values in series_column_names and use it to rename. It doesn't matter if there are extra names.
series_column_names = pd.Series(
    data=["A_ugly", "B_ugly", "C_ugly"],
    index=["A", "B", "C"],
)
df.rename(columns=pd.Series(series_column_names.index.values, index=series_column_names))

A: Wouldn't it be as simple as this?
series_column_names = pd.Series(['A_nice_column_name', 'B_nice_column_name'])

df.columns = series_column_names


text:
Q: Flash 2D engine to use to make a Flash Angry Birds clone (to run on mobile) There are several different physics engines available for Flash. What would be one you'd recommend to build a catapult (with slingshot) Angry Birds clone -- that will run well on mobile, once packaged via Air?
Has anyone used the World Builder Alchemy port of Box2D vs Box2d For Flash?

A: Worked on an annoyingly hard slingshot game some time ago(before Angry Birds) called StuntmanJoe and haven't used Box2D, just basic vector maths.
Also, a couple of year ago, did a basic Box2D game called BlockStock. Used the pure as3 port (not the Alchemy one) and for the simple game it worked well.
The World Construction Kit makes it a lot easier to get started with though.
Lee Brimelow has a nice little started tutorial.
What I would recommend though is understanding a few basic Box2D concepts like:

*

*Coordinate system (is different from flash)

*Box2D Body Definitions (b2BodyDef) and Polygon Definitions(b2PolygonDef)

*forces, impulses, joints

With the world construction kit, you can still whip out a demo without knowing much about these, but it will be really useful to understand how Box2D runs a little bit.
The Alchemy port should be slightly(~5/10 frames per second faster, depending on context),
but I'm afraid I haven't tried it on mobile yet.
At Flash Camp London I've seen a very basic angry birds like flash demo running on an Android phone and the framerate was above 20fps, which was encouraging.
I imagine you should keep in mind the kind of content that runs well on mobiles and a few tricks that should improve the framerate a bit (like cacheAsBitmap and cacheAsMatrix, where possible).
For Android, you can have a look at this LFPUG presentation and get some tips/advices/gotchas.
For iPhone, I wouldn't consider Flash for a responsive Box2D game. I would rather recommend Cocos2D for iPhone than Flash.
HTH

A: Angry Birds actually uses Box2D as it's physics engine. There's many different versions available - including a native version for mobile development. For the most responsive times, you're probably looking at native.
I've used it myself and not had any problems with it, but if you're looking to package it with AIR for mobile, any framerate issues you're going to encounter are probably to do with Flash itself on the mobile rather than Box2D

A: Just use Box2D flash
http://box2dflash.sourceforge.net/
It's a good port of original Box2D.
Plus you can use Quick Box2D to make some routine connected with box2d easier:
http://code.google.com/p/quickb2/


text:
Q: Manually removing sql server 2008 I am not able to remove sql server 2008 from my machine.
I installed it in the past as a part of the installation of an application, this installed the runtime of sql server 2008 SP0. But now I cannot uninstall.
I tried to use the setup of SP0 and even of SP2 but it was not able to uninstall, by giving fatal errors when it does the preliminary checks.
This means that the only option I have is format my machine?
I cannot even intall a new instance, something is really corrupted.
Is it a way to remove it manually?

A: I fixed a similar issue by using Microsoft fixit tool
http://support.microsoft.com/mats/Program_Install_and_Uninstall/

A: I tried to uninstall 3 times and the third time it was succesful, anyway I was not able to install due to fatal errors in the installer.
By trial and error I found that the problem was a list of non existing files in the following registry key (Windows Vista):
HKLM\SYSTEM\CurrentControlSet\Control\SessionManager\PendingFileRenameOperations
So i simply deleted The key PendingFileRenameOperations and tried to install, it installed succesfully.
Anyway thinkinf of automatizing this is crazy, the best way to reinstall is to isntall on a new machine (I mean for customers).

A: This is part of my job which I've been doing for a few years now. I've probably uninstalled it about 200 / 300 times and find it difficult sometimes.

*

*What errors are you getting?

Have you manually deleted it from

C:\Program Files\Microsoft SQL Server

If you can, do so (or just rename) and then try to add-remove. You most likely won't be able to so the next course of action will be to manually strip it from the registry or use CC Cleaner to strip it out.
Let me know if that doesn't work and i'll offer another suggestion. I believe MS has a tool to force removing programs from the list if the MSI isn't available.

Good Luck it's not the nicest thing to do!


text:
Q: Angular: difference when using template or templateUrl I'm running into a strange issue when using the template attribute instead of the templateUrl one.
In case of the latter, I can define multiple directives with isolated scope or the transclude option on a single element. This works as expected and I don't get any errors.
However when simply copying the template and setting it to template in the directive, Angular suddenly starts complaining about multiple directives requesting isolated scope or transclusion on the same element.
See this plunkr of mine. It throws an error in the console. However, if you would replace (in scripts.js)
template: "<ul kendo-menu k-orientation=\"'vertical'\" k-direction=\"'right'\"></ul>",

with
templateUrl: 'menu.html'

the directive works (try right clicking on the text). The content of the HTML file is exactly the same as in the string.
Has anyone got the slightest clue why this inconsistency occurs?
Edit: to avoid confusion, I need the transclude option to be there as I'd like to reuse this element and be able to configure what elements to shown on each place it is used separately.

A: I am unable to reproduce the issue, but the problem here actually is replace: true in the definition of the menu directive.
This means that both kendo and the menu directive are trying to replace the element in turn. Preserving the menu wrapper fixes the problem: http://plnkr.co/edit/vGhEVNfz35elCtxXSMxO?p=preview

A: The problem came from transclude: true and you also forgot to add your <li> elements in your template. If replace: true is defined, it will replace the orginal element with its children.
It's working for me, whether using template or templateUrl : Updated Plunker
EDIT:
There's an open issue about this: https://github.com/angular/angular.js/issues/4357

A: Apparently this inconsistency has been fixed in the newer versions of Angular.
We're using 1.0.8 and the correct behaviour (throwing the error when multiple directives require transclusion on the same element) only occurs when using the template option. When using the templateUrl option, the error is not thrown and the directive works as expected (which still boggles my mind)
Edit: fixed it using the compile function and removing the replace option. Working example  here.


text:
Q: Delete a row from other UIViewController with a UIButton I have a question, I have aUITableViewController which have a list with something, When I push on a row it send me to anotherUIViewController.
I implemented this with prepareForSegue method  also I put
- (void)tableView:(UITableView *)tableView commitEditingStyle:

when I swipe a row is deleting. Everything is working perfect.
Now, my question is, I put a UIButton inUIViewController, and I want when I push on that to delete the row fromUITableViewController, how to do this?

A: You can use delegates, as you want to communicate between two view controllers.
Create a protocol in DetailViewController. While you initially segue from TableViewController to DetailViewController set "idx" as the selected indexPath.row or array index.
When you delete it from DetailViewController, delegate will send the index to the TableViewController and you can remove it from your main array there.
DetailViewController.h file
    #import <UIKit/UIKit.h>

  @protocol DetailViewControllerDelegate <NSObject>

  @optional
  -(void) removeElementAt:(int )index;
  @end

  @interface DetailViewController : UIViewController{

        IBOutlet UIButton *bttn;
        id <DetailViewControllerDelegate> delegate;

    }

    @property (retain) int idx;

    @property (retain) id delegate;

    -(IBAction)bttnclicked;
    -(IBAction)back:(id)sender;

    @end

In DetailViewController.m file
 #import "DetailViewController.h"
    #import "TAbleViewController.h"

    @interface DetailViewController ()

    @end

    @implementation DetailViewController

    @synthesize idx,delegate;

    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
    {
        self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
        if (self) {
            // Custom initialization
        }
        return self;
    }

          - (void)viewDidLoad
            {
                [super viewDidLoad];
                // Do any additional setup after loading the view from its nib.
            }

            - (void)didReceiveMemoryWarning
            {
                [super didReceiveMemoryWarning];
                // Dispose of any resources that can be recreated.
            }

            -(IBAction)bttnclicked{
               [[self delegate] removeElementAt:idx];
            }

            -(IBAction)back:(id)sender{
                [self dismissViewControllerAnimated:YES completion:NULL];
            }

            @end

For TableViewContoller.h file
 #import <UIKit/UIKit.h>
   #import "DetailViewController.h"

    @interface TableViewContoller : UIViewController <DetailViewControllerDelegate>
    {
        DetailViewController *secondview;

    }

    @end

In TableViewController.m file,
   #import "TableViewController.h"
   #import "DetailViewController.h"

   @interface TableViewController ()

                @end

                @implementation TableViewController

                - (void)viewDidLoad
                {
                    [super viewDidLoad];
                    // Do any additional setup after loading the view, typically from a nib.
                }

                - (void)didReceiveMemoryWarning
                {
                    [super didReceiveMemoryWarning];
                    // Dispose of any resources that can be recreated.
                }
                  -(void) removeElementAt:(int )index
            {
                NSLog(@"Before object : %@",self.objects);

                [self.objects removeObjectAtIndex:index];
                //reload table at your convinience
                NSLog(@"Removed object : %@",self.objects);

                [self.tableView reloadData];
            }

       - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
        if ([[segue identifier] isEqualToString:@"showDetail"]) {
            NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
            DetailViewController *dc=[segue destinationViewController];
            dc.idx = (int) indexPath.row;
            dc.delegate = self;

        }
    }

A: The commitEditingStyle: adjusts the core data source of what you're viewing. The delete button should adjust the core data the same way.
Look at Apple's Documentation for creating and deleting managed objects.
If you're deleting the data the row is represented by and still viewing the row when you push back to the UITableViewController, then you need to refresh the data.


text:
Q: Firebase did not receive the pushnotification in android I am trying to migrate to GCM to FCM, but previously it's worked perfectly with GCM. but after I changed it to FCM it is not working for me.
my code is
 @Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    L.d(TAG, "From: " + remoteMessage.getFrom());

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        L.d(TAG, "Message data payload: " + remoteMessage.getData());

        if (remoteMessage.getNotification() != null) {
            String msg = remoteMessage.getNotification().getBody();
            L.d(TAG, "Message Notification Body: " + msg);
            if (!TextUtils.isEmpty(msg)) {
                sendNotification(remoteMessage.getData(), msg);
            }
        }
    }

    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.
}
// [END receive_message]

private void sendNotification(Map<String, String> data, String messageBody) {

    Intent intent = null;
    if (LocalRepository.getInstance().isAuthenticated()) {
        intent = new Intent(this, DashboardActivity.class);

        String referenceKey = data.get("ReferenceKey");
        String referenceValue = data.get("ReferenceValue");
        L.d(TAG, "referenceKey:" + referenceKey + ", ReferenceValue:" + referenceValue);

        if (!TextUtils.isEmpty(referenceKey)) {
            PromotionData promotionData = new PromotionData();//item id

            boolean hasPromotionId = false;
            if (!TextUtils.isEmpty(referenceValue) && TextUtils.isDigitsOnly(referenceValue)) {
                promotionData.promotionId = Integer.parseInt(referenceValue);
                hasPromotionId = true;

            } else {
                intent.putExtra("key", referenceKey);//add this to DashboardActivity intent
            }

            switch (referenceKey) {
                case Repository.ModuleCode.BRAND:
                    intent = new Intent(this, WebViewActivity.class);
                    intent.putExtra("url", referenceValue);
                    intent.putExtra("browser", false);
                    break;

                case Repository.ModuleCode.PROMOTION:
                    if (hasPromotionId) {
                        intent = new Intent(this, PromotionDetailActivity.class);
                    }
                    break;

            }
            intent.putExtra("data", promotionData);
        }
    }

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle(getString(R.string.app_name))
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

}
My manifest is
 <service
        android:name=".fcm.MyFirebaseMessagingService"
        android:enabled="true"
        android:exported="true">

        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

    <service android:name=".fcm.MyFirebaseInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>

</application>

also I have added these in the build.gradle
apply plugin: 'com.google.gms.google-services'

also I have added this in the project gradle
 dependencies {
    classpath 'com.android.tools.build:gradle:2.2.2'
    classpath 'com.google.gms:google-services:3.0.0'
}

I have checked the already exist link and do the changes but it's not receiving the notification in my app.
these the link I checked
Firebase cloud messaging notification not received by device
please suggest the solution for this. thanks in advance.


text:
Q: Multiselect vba Below is my code for opening multiple files and then taking some actions on them. I  am only mentioning the part where i need help.
Sub Sample()
Dim myFile As Variant
Dim i As Integer

myFile = Application.GetOpenFilename(MultiSelect:=True)

If IsArray(myFile) Then
    For i = LBound(myFile) To UBound(myFile)
    Set mywkbook= Workbooks.Open(myFile(i))
    Next i
End If
End Sub

This works good.
But I want "mywkbook" variable to have different value for different workbook so that I can work on them.
Please help

A: One scalar variable cannot have different values at the same time, so you will have to use an array. You could do this by modifying your code like that:
Sub Sample()

  Dim myFile As Variant
  Dim i As Integer
  Dim mywkbooks() as Workbook

  myFile = Application.GetOpenFilename(MultiSelect:=True)

  If IsArray(myFile) Then

    For i = LBound(myFile) To UBound(myFile)
    Set mywkbooks(i) = Workbooks.Open(myFile(i))
    Next i

  End If

End Sub

A: Hopefully this comes through ok, this is my first Answer on this forum.
Sub tryThis()

Dim myFile As Variant
Dim i As Integer
Dim workbookNames() As String ' define a empty string array variable to hold the file names

myFile = Application.GetOpenFilename(MultiSelect:=True)

If IsArray(myFile) Then
    For i = LBound(myFile) To UBound(myFile)
        Workbooks.Open (myFile(i))   ' Just open the workbook here
        ReDim Preserve workbookNames(i) ' ReDim redefines your array to 'i' number of elements.  Preserve ensures you don't lose the previous values held in the Array
        workbookNames(i) = ActiveWorkbook.Name ' Assign the Name of the Workbook to the Array
            MsgBox workbookNames(i) ' you don't need this, I just used it to demonstrate that you now have the file name and can work with it
    Next i
End If

End Sub

Edit: I was tying this at the same time as 'Binarus'.  I like their approach of declaring a Workbook Array but you will need to add the following line before 'Set mywkbooks(i)' otherwise you will get a Subscript out of range error as the Array is empty and cannot hold any values yet.
ReDim Preserve mywkbooks(i)

A: I made it work somewhat like this :
Dim paths(), wbs() As Workbook
Dim x As Integer

paths = Application.GetOpenFilename(FileFilter:="Excel Files
(*.XLSX),*.XLSX", MultiSelect:=True)

  For x = 1 To UBound(paths)
  ReDim wbs(UBound(paths))
 Set wbs(x) = Workbooks.Open(paths(x))

   With wbs(x).Sheets("Sheet1")

  lastrow = .Range("A" & .Rows.Count).End(xlUp).Row

.Range("A2:X" & lastrow).Copy newexcel.Sheets("RawData").Range("A" &
newexcel.Sheets("RawData").Rows.Count).End(xlUp).Offset(1)

 End With
 Next x

Posting my answer so that it can help someone in future :)


text:
Q: Static UITableViewCell returns nil on CellForRowAtIndexPath, but only for certain sections I have defined a table view controller using static cells in a Storyboard scene.
The table view itself contains six sections, each of which contains one or two cells.
I write data to the cells from this method in my view controller:
- (void)setUpAllCells
{
    //Charge Name
    NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:0];
    TableViewCellTextField *currentTextField = (TableViewCellTextField *)[[self tableView] cellForRowAtIndexPath:path];
    [currentTextField.textField setDelegate:self];

    //Charge Description
    path = [NSIndexPath indexPathForRow:1 inSection:0];
    currentTextField = (TableViewCellTextField *)[[self tableView] cellForRowAtIndexPath:path];
    [currentTextField.textField setDelegate:self];

    ...

    path = [NSIndexPath indexPathForRow:0 inSection:5];
    TableViewCellControl *currentControl = (TableViewCellControl *)[[self tableView] cellForRowAtIndexPath:path];
    [currentControl setValue:m_data->trailBurnTime];
}

Which is called from:
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setUpAllCells];
}

When I run the application, each cell responds as I expect except for the last section.
The last section's cells are not connected to my controller and retain their default values from the storyboard scene.  I set a breakpoint in setUpAllCells and found that cellForRowAtIndexPath is returning nil for that last section.
I've used this format for five other view controllers, and have not had this happen.
Here's what I've tried so far:

*

*I tested this with my own custom TableViewCells and, when those didn't work, standard UITableViewCells.  The last section always returns nil.

*I rearranged the sections and cells. The last section always returns nil.

*I removed that section completely. The other sections still work normally without it.

*I added more sections. Anything from section 5 on returns nil at CellForRowAtIndexPath.
I'm at a loss here.  I can't figure out what could be causing this.
Suggestions?

A: I don't know why you get the results you do -- when I tried it, and logged the cells, I only got valid cells for the first 3 sections. Anything past section 2 was null. Frankly, I'm not sure why it works at all, since this isn't the way Apple says to populate a static table view. You're supposed to create IBOutlets in your table view controller to the UI elements in your cells. In this regard, a static table view acts more like a scroll view with subviews, than it does like a table view. You can also make IBOutlets to the cells themselves instead of the individual UI elements, and then use dot notation to address any of the properties in your custom cell, or the standard ones like textLabel and detailTextLabel.

A: The funny story about your question is that when you call the function cellForRowAtIndexPath on your tableview, I believe it in turn calls the delegate callback function you are supposed to implement as a UITableViewDelegate that provides the TableView with the cellForRowAtIndexPath.
Once you implement that function you will get the cell back.  I think the function you are looking for is:
– dequeueReusableCellWithIdentifier:forIndexPath:
– dequeueReusableCellWithIdentifier:

Look here: http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableView_Class/Reference/Reference.html
I know thats not likely the answer you were looking for but its the truth :).