text:
Q: how to format code to avoid warnings - Vue I'm working on my first Vue project in the company that I work. I have noticed when I run the project I get warnings that they have be fixed using --fix all the warnings are related with indentation, spaces, new lines and things like that. Is there a formatter for Vue? I was using the default VS Code format on save but didn't help with the warnings.

A: As of this writing, the gold standard for linting JavaScript is eslint. For Vue, you can use eslint-plugin-vue.
The user guide will walk you through how to install and configure, and how to integrate it into your editor.


text:
Q: Resolve Function Address with PE Export Table Can anyone explain me how to properly obtain a function address from a PE image and then call that function with a delegate?
I found a good piece code googling around that loads exports from a DLL library, but it only get function names out of it... so I modified it as follows:
[DllImport("ImageHlp", CallingConvention = CallingConvention.Winapi), SuppressUnmanagedCodeSecurity]
public static extern bool MapAndLoad(string imageName, string dllPath, out LOADED_IMAGE loadedImage, bool dotDll, bool readOnly);

public static IntPtr CustomGetProcAddress(string modulePath, string moduleProc)
{
    LOADED_IMAGE loadedImage;

    if (MapAndLoad(modulePath, null, out loadedImage, true, true))
        return GetAddr(loadedImage, moduleProc);
    else
        return IntPtr.Zero;
}

private static IntPtr GetAddr(LOADED_IMAGE loadedImage, string moduleProc)
{
    var hMod = (void*)loadedImage.MappedAddress;

    if (hMod != null)
    {
        uint size;
        var pExportDir = (IMAGE_EXPORT_DIRECTORY*)ImageDirectoryEntryToData(
            (void*)loadedImage.MappedAddress,
            false,
            IMAGE_DIRECTORY_ENTRY_EXPORT,
            out size);

        uint* pFuncNames = (uint*)RvaToVa(loadedImage, pExportDir->AddressOfNames);
        ushort* pFuncOrdinals = (ushort*)RvaToVa(loadedImage, pExportDir->AddressOfNameOrdinals);
        uint* pFuncAddr = (uint*)RvaToVa(loadedImage, pExportDir->AddressOfFunctions);

        for (uint i = 0; i < pExportDir->NumberOfNames; i++)
        {
            uint funcNameRva = pFuncNames[i];

            if (funcNameRva != 0)
            {
                char* funcName = (char*)RvaToVa(loadedImage, funcNameRva);
                string name = Marshal.PtrToStringAnsi((IntPtr)funcName);
                _exports.Add(name);

                if (name == wantedFunction)
                    return addr = new IntPtr(*(uint*)(pFuncAddr + (*pFuncOrdinals * 4)));
            }
        }
    }

    return IntPtr.Zero;
}

I'm sure I'm quote close to the solution... but I always get AccessViolationException (when I use wrong pointers) or InvalidFunctionPointerInDelegate and PInvokeStackImbalance (when I try to cast the pointer to a delegate using Marshal.GetDelegateForFunctionPointer and then execute it).
I tried everything but I can't make it work (I already pulled out the correct address of the function I'm looking for using LoadLibrary and GetProcAddress... so I can compare the results, but I don't want to use those functions).
[EDIT] I found another example, but I'm not sure it can do what I'm looking for:
http://www.rohitab.com/discuss/topic/39366-c-loadlibary-from-byte/page_k_bb2fe024f8a71424996db6d9af08c1fc_settingNewSkin_19

A: You can't do that.  The MapAndLoad and function from the ImageHlp library only loads a PE file into memory as a data file so it can be examined.  It does not run through all of the logic of the Windows loader does when it loads a DLL to make it executable (RVA fixups, etc.).
If you want to load a DLL, find a function by name, and get an callable pointer to it, you use LoadLibrary and GetProcAddress.  Those functions where designed to do exactly what you are looking trying to do.

A: As has been said previously, the MapAndLoad function is just loading the file as data - the memory page it's loaded into will non-executable, and so trying to jump to a location within this memory will almost certainly not work. You're going to need a significantly more complex method if you want to get around using LoadLibrary - but the first step will be ensuring that  the executable sections of the PE file are loaded into executable memory (followed by implementing all of the other functionality of the Windows Loader!) I've never attempted this, but from what I can see on a brief search there are numerous issues associated with getting around issues such as Windows DEP (data execution prevention).

redpajama_set_name: RedPajamaStackExchange


text:
Q: bash not able to execute command in a variable cdm="home/nmsadm/tngVersion/iconTestNetworkGenerator.sh -input /home/nmsadm/ipr/ipr_files/IP_1.xml -templateDir /home/nmsadm/Try_K/1 -nocs -erbsstart 1 -subnetwork 25 -iprstart 11"

#above statment is in a single line

$cdm

I stored one command in a variable called cdm, now I want to run this command so I used $cdm. But I'm getting an error

home/nmsadm/tngVersion/iconTestNetworkGenerator.sh: No such file or directory

I'm pretty sure that there is file in that specified directory.
How should I fix this?

A: It is apparently trying to execute the command. The error quotes the command name from the variable. But the command is wrong. Did you by any chance forget initial /?

A: Since you specified the name of a command along with a directory the command is supposed to be in, there is no PATH lookup performed. Apparently you are not in a directory where the pathname
  home/nmsadm/tngVersion/iconTestNetworkGenerator.sh

refers to an existing file. Fix this either by using an absolute path, probably
  /home/nmsadm/tngVersion/iconTestNetworkGenerator.sh

or by cd'ing to the proper directory first, probably
  cd /
  $cmd


text:
Q: Create a table with every month since given date Is it possible to create a table with only one column that holds every month since a given date?
For instance with the given date 2016-01-01 I would like the following table:


text:
Q: Using command python -m http.server and make server reachable by public ip? How can i use the command:
/python -m http.server and make the server reachable through my public ip? I know this is NOT safe, but I just wanna try some things out.

A: Use it as you normally do.
You'd connect to it by its external IP address. You might need to setup your router to allow that. Read up on port forwarding, for example.


text:
Q: Regex - At least one occurence of 'F' in a 14 character string but not at 7th position I have to check many strings which are 14 characters long.
There should be at least one occurrence of 'F' in a 14 character string but not at 7th position.
Currently, I'm doing this in 2 steps.
First, check if 'F' is not present at position 7 and save them.
^.{6}[^F].{7}$
Then check if there is at least one occurrence of 'F' in the saved strings.
^[F]+$
Is there a better way to do this?

A: If supported, you can make use of lookarounds asserting an F and not match it on the 7th position:
^(?=[^F\n]*F)(?:.{6}[^F].{7})$

Regex demo

A: Just as an alternative:
^(?!.{6}F|[^F]+$).{14}$

See an online demo

*

*^ - Start-line anchor;

*(?!.{6}F|[^F]+$) - Negative lookahead with alternation to avoid a line with an 'F' at index 7 or a line with no 'F' at all;

*.{14}$ - 14 Characters other than newline upto end-line anchor.


text:
Q: how to apply DISTINCT on an inner joined table I have the following entity, basically it says a picture has a shop
class InstagramShopPicture
{

   /**
     * @Exclude()
     * @ORM\ManyToOne(targetEntity="InstagramShop", inversedBy="userPictures")
     * @ORM\JoinColumn(name="shop_id", referencedColumnName="id", nullable=false, onDelete="CASCADE")
     */
    protected $shop;

}

how do I query 10 pictures, each from a unique store in DQL?
So far I have the following:
 $query = $em->createQueryBuilder()->select('picture')
               ->from("ShopiousMainBundle:InstagramShopPicture", 'picture')
               ->innerJoin('picture.shop', 'shop')
               ->setMaxResults(10);
                    ;

in other words I just wanted DISTINCT shop, but I am finding it hard to transalate DISTINCT into DQL
UPDATE:
$query = $em->createQueryBuilder()
                    ->select('pictures')
                    ->from("AppMainBundle:InstagramShop", 'shop')
                    ->innerJoin('shop.userPictures', 'pictures')
                    ->innerJoin('pictures.category', 'category')
                    ->innerJoin('category.pictureFirstLevelCategory', 'firstLevelCategory')
                    ->distinct()
                    ;

        $query->andWhere('firstLevelCategory = :firstLevelCategory');
        $query->andWhere('shop.isLocked = false');
        $query->andWhere('shop.expirydate IS NOT NULL');
        $query->andWhere('shop.id != :shopId');
        $query->andWhere('shop.expirydate >= :currentDate');

        $parameter["currentDate"] = new \DateTime('now');
        $parameter["shopId"] = $shopId;
        $parameter["firstLevelCategory"] = $picture->getCategory()->getPicturefirstlevelcategory()();

I tried doing the above and it gives me this error:
Error: Cannot select entity through identification variables without choosing at least one root entity alias.

UPDATE:
SELECT DISTINCT pictures FROM AppMainBundle:InstagramShop shop INNER JOIN shop.userPictures pictures INNER JOIN pictures.category category INNER JOIN category.pictureFirstLevelCategory firstLevelCategory WHERE firstLevelCategory = :firstLevelCategory AND shop.isLocked = false AND shop.expirydate IS NOT NULL AND shop.id != :shopId AND shop.expirydate >= :currentDate


text:
Q: Ошибка с преобразованием При вызове этой функции компилятор выдает ошибку
(не существует подходящего конструктора для преобразования из point(*)[20] в point).
int amount_of_alive_neighbours(point playground[_HEIGHT_][_WIDTH_], int x, int y)
{
    int count = 0;
    int neighbours[8][2];
    int _x, _y;

    neighbours_coordinates(neighbours, x, y);

    for (int i = 0; i < 8; i++)
    {
        _x = neighbours[i][0];
        _y = neighbours[i][1];

        if (_x < 0 || _y < 0)
            continue;
        if (_x >= _WIDTH_ || _y >= _HEIGHT_)
            continue;

        if (playground[_x][_y].alive)
            count++;
    }

    return count;
}

Вызываю так:
alive_neighbours = amount_of_alive_neighbours(previous_playground, i, j);

point - структура
struct point
{
bool alive:true;
}

Откуда вызываю функцию:
void next_playground(point new_playground[_WIDTH_][_HEIGHT_], point previous_playground[_WIDTH_][_HEIGHT_])
{
    int alive_neighbours;
    point pg;

    for (int i = 0; i < _WIDTH_; i++)
        for (int j = 0; j < _HEIGHT_; j++)
        {
            pg = previous_playground[i][j];
            alive_neighbours = amount_of_alive_neighbours(previous_playground, i, j);
        }
}

Ниже краткий пример законченного кода
    #include "stdafx.h"
#define _HEIGHT_ 20
#define _WIDTH_ 20

struct point
{
    bool alive : true;
};

int amount_of_alive_neighbours(point playground[_HEIGHT_][_WIDTH_], int x, int y)
{
    return 1;
}

void next_playground(point new_playground[_WIDTH_][_HEIGHT_], point previous_playground[_WIDTH_][_HEIGHT_])
{
    int alive_neighbours;
    point pg;

    for (int i = 0; i < _WIDTH_; i++)
        for (int j = 0; j < _HEIGHT_; j++)
        {
            pg = previous_playground[i][j];
            alive_neighbours = amount_of_alive_neighbours(previous_playground, i, j); //ERROR
        }
    }

int main()
{
    point pg1[_WIDTH_][_HEIGHT_];
    point pg2[_WIDTH_][_HEIGHT_];
    next_playground(pg1, pg2);
}

A: Массивы с фиксированным размером в c++ передаются только по ссылке:
int foo(int (& array)[2][4]){
   return sizeof(array);
}

int bar(){
    int array[2][4];
    return foo(array);
}

Или можно преобразовать в двойной указатель и передавать размер отдельно.
Лучше использовать std::array для таких массивов.


text:
Q: Referential Integrity - how to configure SQLAlchemy? Can someone help me get the big picture when it comes to configuring SQLAlchemy models, so referential integrity is ensured at all levels?
Going by the idea that referential integrity should be expressed and enforced by the DB, I have created a schema (currently in Postgresql) with all the constraints I think I need, thus giving me a database I trust will enforce referential integrity.
I then begin to build an app on top of this DB, using SQLAlchemy (0.7) in declarative mode.
Having searched and read a bit, I have learned that I can configure:

*

*onupdate/ondelete rules on my Column() definitions.

*cascade options on my relationship() definitions,
and that these seem to operate on the session level in SQLAlchemy.

*passive_deletes and passive_updates options for my relationship() definitions.

And that all these options have defaults.
But I am left confused as to how much I actually need to do with my SQLAlchemy models, to make sure SQLAlchemy doesn't get out of sync with the DB and its constraints during a session.
What exactly am I achieving, if I configure 'onupdate' etc. on my Columns() definitions in SQLAlchemy?
And for the cascade and passive_delete/passive_update rules I can configure on a relationship(). What do I need here, and why?
Or to rephrase my question: To what extend will SQLAlchemy be aware of the constraints configured in the DB schema, and to what extend (and how) do I have to repeat them in my models?
And are the anything else I should be aware of? :)

A: SQLAlchemy doesn't fundamentally need to know anything about the constraints your database has.    If your database has the constraints you want configured, you're essentially done - your application is disallowed by the database from doing anything it's not supposed to.
A key theme of SQLAlchemy is that it is really only doing what you tell it to.  So if you were to try persisting an object, SubWidget(), which in the database needs to have a reference to a parent Widget(), at the point at which SQLAlchemy flushes the data (i.e. emits INSERT statements), the operation would fail with a constraint violation, emitted by the database, and the transaction is rolled back.
So assuming an FK on "subwidget" referencing "widget", your application needs to ensure the data is in the correct structure.   There are two ways to do this; one is that you hand-maintain those columns which contain foreign key references, and ensure they have the appropriate value at the point of INSERT or UPDATE.   The other is that you'd use relationship() to manage the foreign key attribute, and you'd instead ensure that the creation of a SubWidget() object is accompanied by the operation of associating it with a parent Widget() object which you've created and/or acquired separately.
Regarding cascades, it's a great idea, though not required, to have ON DELETE CASCADE on those foreign keys where it applies.   On the SQLAlchemy side, when using relationship() you usually want to give the ORM a hint that the database will cascade deletes via the passive_deletes flag ( http://www.sqlalchemy.org/docs/orm/collections.html?highlight=passive_deletes#using-passive-deletes ), however this is usually a performance enhancement; SQLAlchemy otherwise ensures that all objects represented on the dependent side of the relationship() are loaded into memory, and handled appropriately, which means one of either setting the foreign key attribute to NULL (the default), or marking the dependent object for deletion (which occurs by setting "cascade" to "all, delete-orphan", see http://www.sqlalchemy.org/docs/orm/session.html#cascades).
ON UPDATE cascade is less common as natural primary keys are not a common practice these days, since they don't actually perform as well as plain integer primary keys and can also be cumbersome in other ways.   SQLAlchemy does support these as well however and they will generally take care of themselves, as SQLA assumes by default that update cascades are in place when a PK mutation takes place, see http://www.sqlalchemy.org/docs/orm/relationships.html#mutable-primary-keys-update-cascades for a detailed description of that.
Perhaps this is all easier to grok with a little experimentation, the basic idea is that SQLAlchemy is only emitting the SQL you're telling it to, even though many of its SQL behaviors are automated once configured up front.   relationship() should be configured with details on how you'd like it to behave when data is persisted, modified, or deleted with respect to the constraints present in the database.

A: So, building on zzzeeks answer, and my own studying/tinkering after my initial question...
To make SQLAlchemy actively prevent that an in-session view of the DB state can divert from what the DB will allow when you flush/commit, you must mirror all the constraints found in the DB schema in your SQLAlchemy models.
And this is done via the Column definitions in the form of:
ForeignKey(..., onupdate='', ondelete='')
primary_key=True
unique=True

and so on, with the possible inclusion of __table_args__, like:
__table_args__ = (
        ForeignKeyConstraint(['id'], ['remote_table.id']),
        UniqueConstraint('foo'),
        )

For cases where the constraint spans multiple columns.
Whereas:
relationship()

and its related arguments, like:
cascade
cascade_backrefs
foreign_keys
passive_deletes
passive_updates

and so on, are a (important) convenience feature that allows you to work with your models with as little effort as possible, but ultimate aren't meant to be what prevents breaching referential integrity.
The relationship() feature can not express all the typical constraints in a database, while the Column() (and __table_args__) feature can.
On the other hand, configuring the relationship() with some of the arguments listed above (or going by default values where that makes most sense), will let SQLAlchemy perform tasks automatically, that ultimately can be said to be referential integerity related. And would otherwise normally have to be expressed by logic in the surrounding code.
Optimal configuration of relationship() will also in some cases avoid unnecessary SQL statements to be issued by SQLAlchemy.
Hope this summation is somewhat accurate...


text:
Q: Writing updates to OLAP cube What is the easiest way to write user entered measure values (sales forcast) to the SQL Server Analysis Services OLAP cube from a .Net client application?
I'm aware that underlying fact table can be updated with DML statements and that cube can be reprocessed but I'm looking for alternatives.
Regards,
Aleksandar

A: We use pivot table Ranet OLAP for editing  cube data.
View sample Simple PivotTable Widget - PivotTaple with Updateable
Writing updates to OLAP cube.

A: I nearly got into a project like this once. It did not go ahead, which I was very grateful for, after looking into the work involved. My advice to you is to run away!!!
You do not have to update actual cube data, or reprocess though - depending on how complex your user-entered data is going to be. I believe this is covered in Microsoft's standard MDX course, the notes of which you may be able to find online (sorry, I've since disposed of my copy). This depends on whether you want to learn MDX though, which is not easy.

A: I think you can use ADOMD .Net to do Writeback. You can ADOMDCommand to wrap UPDATE CUBE Statements.
ADOMD .Net
http://msdn.microsoft.com/en-us/library/ms123483(v=SQL.100).aspx
Link below talks about some of the issues in this approach, if you are doing too many updates together.
http://www.developmentnow.com/g/112_2006_1_0_0_677198/writeback-in-ADOMD-NET.htm


text:
Q: nested routing angular 6 doesn't fire Hi everybody I have module with components I want to  add component inside one of them as I have admin and this module has children page and it is routing is
const routes: Routes = [
  {
    path: '',
    component: AdminComponent,
    children: [
      { path : 'Dashboard' , component: DashboardComponent},
      // { path: 'User', component: UserComponent },
      { path: 'User', loadChildren: './user/user.module#UserModule'},
      { path: '', redirectTo: 'Dashboard', pathMatch: 'full' },
    ],
  },
  { path: '**', component: SystemErrorComponent }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class AdminRoutingModule { }

under user, I have added multi-component like add and details and I have routing for it it is
const routes: Routes = [

  {
    path: '',
    component: UserComponent,
    children: [
      { path: 'userlist', component: UserlistComponent },
      { path : 'adduser' , component: AdduserComponent},
      { path: ':id/Userdetails', component: UserdetailsComponent },
      { path: '', redirectTo: 'userlist', pathMatch: 'full' },
    ],
  }

];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class UserRoutingModule { }

I also add  in admin HTML and user HTML
when I click user link  I got error Error: Component UserComponent is not part of any NgModule or the module has not been imported into your module.
 and not open what is the error in my routing?

A: The error simply states that the UserComponent isn't available for loading.
So first check if the UserComponent is in the declarations array of UserModule.
If this doesn't help, then you might need to post the AdminModule and UserModule source.

A: I have added all component into declarations and remove user declarations of the user from admin then it works


text:
Q: What permissions or local security policy settings are needed for a AD account to run .NET application on IIS I have a Windows Server 2003 running IIS.  I have created an application pool specifically for a web service application.  The identity of that application pool is a domain account.  The domain account is needed for SQL Server access via windows authentication.
When I run the application in the Default Application Pool with the NETWORK SERVICE account it work fine as long as I do not execute any function that accesses the SQL Server.  SQL Server access fails as expected becasue the NETWORK SERVICE account does not have permissions on any of the SQL Server machines.
When change the application to use the application pool that is running under a domain account I get "Service Unavailable" when I attempt to run any web service.  If I make that domain account a domain administrator the it does work.  For obvious reasons, making the account an administrator is not a viable solution.  Specifically, what permissions or local security policy settings are needed on a domain account to run a .NET application in IIS?
Thanks,
Jim

A: The identity under which an application pool runs need obviously read access to every file it'll need to process (your ASP.NET web site/app); it also need read and/or write access to whatever resources it might need; so, if f.e. your ASPX pages saves files uploaded from users to some path, the service account will need write access to that path.
If you get a "service unavailable" error, this means the application pool servicing your web site/app has stopped. You should investigate why this happened; this is usually due to repeated critical errors, of which you'll find evidence in Windows' Application event log.


text:
Q: Trying to understand the flow of packets going from one VLAN to another I am trying to understand the flow of the packets from one computer to the other in the same VLAN but on a different subnet as explained here. And a case shown is:

Suppose the same sending computer (179.58.10.102) wants to send a
  message to a computer on a different subnet in the same VLAN (e.g.,
  179.58.7.30 on the same switch or 179.58.11.20 on switch 3)

The original computer will pack the frame with the destination Ethernet address of its router, and then later it states:

The router creates a new Ethernet frame and sets the destination
  Ethernet address to the destination computer

How can the router know the address of the destination computer if initially, the frame was packed with only the router's address? Am I missing something?

A: The Ethernet address on the frame is the MAC address of the router (layer 2). The payload of the ethernet frame, like an IP packet (layer 3) still contains the original destination IP address. The router will create a new frame frame with the MAC address of the destination computer containing the original payload.


text:
Q: SQL round trip network latency If I'm making a call to my SQL Server 2008 database from a C# client how does the basic network latency contribute to the round trip to the database?  I guess what I'm after is how many round trips are required to actually get the data given that there must be round trips that are related to opening/closing the connection, maybe data integrity checks etc.
For instance, if I ping my database server and get
Reply from XXX.XXX.XX.XX: bytes=32 time=100ms TTL=121
What can I expect my total round trip time to be?  Let's assume for argument's sake that my query is SELECT 1234 and that I'm running the same query 100 times using the same connection.  I'm only interested in the contribution of the network latency and not of the query performance - hence the simple query.
So, in summary, assuming a latency of 100ms, what's the cost in terms of latency alone

*

*Of opening and maintaining the connection

*Per call once the connection is open

*Closing the connection


text:
Q: RabbitMQ publish to multiple queues via an exchange publishes to only the first queue only I want to publish to Several queues bound to an exchange (fan out will not work here as I want to publish to only selective queues and not all the queues)
The code goes like this:
public int pushDataOverRabbitMQ(String[] deviceIDs, String msg) throws IOException {
        int retrunVal=0;
        String EXCHANGE_NAME="DUSHTEST";
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "direct",true);

        for(int i=0;i<deviceIDs.length;i++){

            try{
                channel.queueDeclare(deviceIDs[i],true,false,false,null).getQueue();

                channel.queueBind(deviceIDs[i], EXCHANGE_NAME, deviceIDs[i]);
//routing key and queue have the same value

                channel.basicPublish(EXCHANGE_NAME, deviceIDs[i],  new AMQP.BasicProperties.Builder()
                .contentType("text/plain").deliveryMode(1)
                .priority(1).userId("guest")
                .build(),
                msg.getBytes());

                System.out.println(" [x] Sent '" + msg+ "'");

                retrunVal= Constants.PUB_STATUS_SUCCESS;
            }catch(Exception e){
                e.printStackTrace();
                retrunVal= Constants.PUB_STATUS_FAIL;
            }
        }
        channel.close();
        connection.close();
        return retrunVal;

    }

**deviceIDs** contains two Strings Dush-Micromax and MyDesktop
I am unable to upload images due to low points, but on the server side there are three queues created.
The code above binds the created queues to the exchange.
I had earlier created two consumers as below:
import java.io.IOException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class RabbitSubscriptionModel {

    /**
     * @param args
     */
    private final static String QUEUE_NAME = "MyDesktop";
    //  private final static String QUEUE_NAME = "Dush-Micromax";
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        final Channel channel = connection.createChannel();
        try{
            channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        }catch (Exception e) {
            e.printStackTrace();
        }

        channel.basicConsume(QUEUE_NAME, false,"My-Consumer-Trial1", new GenericConsumer(channel));
//      channel.basicConsume(QUEUE_NAME, false,"My-Consumer-Trial2", new GenericConsumer(channel));

    }

}

I have two Consumers namely My-Consumer-Trial1 and My-Consumer-Trial2
However, I receive data only in the first consumer ie: My-Consumer-Trial1.
After carefully analyzing the rabbitMQ Admin Console it seems that instead of publishing to the queue that the consumers is hooked onto the second publish happens on a new Queue. So in total we have  three queues of which two are bound to the EXCHANGE and one under default EXCHANGE.

A: You are missing a lot here in your code.  For reference check out this tutorial on direct exchanges http://www.rabbitmq.com/tutorials/tutorial-four-java.html.
You are not connecting to the exchange in the consumer
You are doing queueDeclare queueBind in the producer and not the consumer.
You have no while loop to read the messages


text:
Q: Disable Save As In A Batch Of Excel Files I've been researching how to disable "Save As" in Excel and it seems possible. I have a macro that loops through a bunch of Excel files making changes. In that macro I would like to disable "Save As" for all of the files. Is this possible?

A: Using application object. You just add this lines to the code that loops in every file or workbook so it disable "save as" for each one :
Application.CommandBars("Worksheet Menu Bar").Controls("File").Controls("Save As...").Enabled = False
Application.CommandBars("Worksheet Menu Bar").Controls("File").Controls("Save").Enabled = False

Tell me how it goes.

A: Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

    MsgBox "You can't save this workbook!"
    Cancel = True

End Sub


text:
Q: In React, is there a way to have a toggle switch, onChange or onClick, switch to either the first function (thirtyDays) or the second function (year)? I am trying to allow the user to select what will display via a toggle switch.  For example, I have two functions:  thirtyDays & year.  Either onChange or onClick, I would like for the user to be able to switch which function is called. Is there a way to do this?  Here is my code for the ToggleButton component:
thirtyDays = (props) => {
    console.log("the past 30 days of transactions");
    var now = new Date();
    now.setDate(now.getDate() - 30);
  }

  year = (props) => {
    console.log("year of transactions");
   var now = new Date();
   now.setDate(now.getDate() - 365);
  }

  render() {

    return (

        {
          <>
            {" "}
            <input type="checkbox" id="togBtn" />

              Year
              30 Days

          </>
        }

    );
  }
}

Here is my css:
.switch {
  position: relative;
  display: inline-block;
  width: 175px;
  height: 50px;
}

.switch input {display:none;}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: forestgreen;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 50px;
  width:50px;
  left: 10px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2ab934;
}

input:focus + .slider {
  box-shadow: 0 0 1px rgb(2, 61, 2);
}

input:checked + .slider:before {
  -webkit-transform: translateX(100px);
  -ms-transform: translateX(100px);
  transform: translateX(100px);
}

/*------ ADDED CSS ---------*/
 .on
{
  display: none;
}

.off, .on
{
  color: white;
  position: absolute;
  transform: translate(-50%,-50%);
  top: 50%;
  left: 50%;
  font-size: 10px;
  font-family: Verdana, sans-serif;
  font-size: 15px;
}

input:checked+ .slider .on
{display: block;}

input:checked + .slider .off
{display: none;}

/*--------- END --------*/

/* Rounded sliders */
.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;}

Here is my codesandbox:  https://codesandbox.io/s/ancient-rgb-y62rm?file=/src/App.js

A: You can decide about function which you call checking state of your checkbox inside another function. Example:
  const changePeriod = (e) => {
    if ( console.log( e.target.checked ) ) {
      year( /* your params */ )
    } else {
      thirtyDays( /* your params */ )
    }
  }

  return (

      <input type="checkbox" onChange={ changePeriod }/>

  );

A: You would have to maintain the toggle state in your component. Or, if you're willing to use a plugin, you could try react-switch.
Here's a working example - https://codesandbox.io/s/frosty-water-l4pr6


text:
Q: python annoy library import error in GAE project I am working on GAE using python jinja2 framework, while importing third party library "annoy" I am getting import error.
I am following the GAE Installing a third-party library method.
My project structure like
*projectfolder/
   *lib/
      *annoy/
   main.py
   app.yaml
   appengine_config.py

Here is my main.py code
import os
import jinja2
from google.appengine.api import users
import webapp2
import csv
from jinja2 import Template
import ann_utils

JINJA_ENVIRONMENT = jinja2.Environment(
    # TODO: to add other directories here that contains the templates.
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)

class Sent2Vec(webapp2.RequestHandler):
    """docstring for ."""
    def get(self):
        template = JINJA_ENVIRONMENT.get_template('sent2vec.html')
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(template.render()

ann_utils.py library
 from annoy import AnnoyIndex
import random

f = 40
t = AnnoyIndex(f)
for i in xrange(1000):
    v = [random.gauss(0, 1) for z in xrange(f)]
    t.add_item(i, v)

t.build(10)
t.save('test.ann')

u = AnnoyIndex(f)
u.load('test.ann')
print(u.get_nns_by_item(0, 1000))

app.yaml
runtime: python27
threadsafe: ture

libraries:
- name: webapp2
  version: latest
- name: jinja2
  version: latest
- name: annoy
  version: latest

handlers:
- url: /.*
  script: main.app

appengine_config.py
from google.appengine.ext import vendor
vendor.add('lib')

Here is the tracetrack:
INFO     2017-01-24 08:33:27,378 devappserver2.py:769] Skipping SDK update check.
INFO     2017-01-24 08:33:27,435 api_server.py:205] Starting API server at: http://localhost:60106
INFO     2017-01-24 08:33:27,451 dispatcher.py:197] Starting module "default" running at: http://localhost:8080
INFO     2017-01-24 08:33:27,451 admin_server.py:116] Starting admin server at: http://localhost:8000
ERROR    2017-01-24 08:34:53,286 wsgi.py:263]
Traceback (most recent call last):
  File "/home/affine/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 240, in Handle
    handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "/home/affine/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
    handler, path, err = LoadObject(self._handler)
  File "/home/affine/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject
    obj = __import__(path[0])
  File "/home/affine/ML-Visualization/main.py", line 8, in <module>
    from ann_utils import create_tree
  File "/home/affine/ML-Visualization/ann_utils.py", line 1, in <module>
    from annoy import AnnoyIndex
  File "/home/affine/ML-Visualization/lib/annoy/__init__.py", line 15, in <module>
    from annoylib import *
  File "/home/affine/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/sandbox.py", line 963, in load_module
    raise ImportError('No module named %s' % fullname)
ImportError: No module named annoy.annoylib
INFO     2017-01-24 08:34:53,290 module.py:788] default: "GET / HTTP/1.1" 500 -


text:
Q: WSO2 checking attribute value inside of a JSON with XSLT I have a JSON payload which contains attributes inside of it like:
{
  "test": "test",
  "test1": "1111",
  "test2": "2222",
  "@test": "3333",
  "test3": [
    {
      "A": "aaaa",
      "@B": "bbbb",
      "c": "cccc"
    }
  ]
}

Using XSLT, I need to check the value of the attibute @test or @B. Here is my sample transformation for check the attibute @test vaue:
<xsl:choose>
    <xsl:when test="//jsonObject/@test='3333'">
      ---- operation ----
    </xsl:when>
    <xsl:otherwise>
      ---- operation ----
    </xsl:otherwise>
</xsl:choose>

The problem is here the layer of attributes in my JSON payload. When I move @B attribute at the top of its JSON element or @test attibute at the top of the JSON element like:
{
  "@test": "3333",
  "test": "test",
  "test1": "1111",
  "test2": "2222",
  "test3": [
    {
      "@B": "bbbb",
      "A": "aaaa",
      "c": "cccc"
    }
  ]
}

I can check the attibute values easily. So, is there a way to do that in XSLT instead of using javascript in sequence?
I'm using WSO2 EI 6.4.0
and XSLT 2.0
Best regards.


text:
Q: How best to partially validate a phone number using Java I need to validate the beginning of a phone number, by this I mean I need to make sure that a country code was provided. The phone number should start with a plus sign followed by a minimum of 1 number and a maximum of 3 numbers followed by a hyphen.
Example of valid numbers...
+1-555-5555
+12-5555555
+123-(555) 555-5555
Examples of an invalid phone number
+1(555) 555-5555
5555555555
+5555555555
This is what I have so far. What I'm doing is stripping all non-digits to verify that I have a minimum of 10 numbers. I then verify that I have a country code of a minimum of 3 numbers. After that, if the phone number doesn't begin with a "+", I prepend one.
private boolean isPhoneNumberValid(String phoneNumber) {
  if (!isPhoneNumberLengthValid(phoneNumber) || !isCountryCodeLenghtValid(phoneNumber)) {
    return false;
  }

  if (!phoneNumber.startsWith("+")) {
    request.getDestination().setMobilePhoneNumber("+" + phoneNumber);
  }

  return true;
}

private boolean isPhoneNumberLengthValid(String phoneNumber) {
  return phoneNumber.replaceAll("\\D+","").length() < 10;
}

private boolean isCountryCodeLenghtValid(String phoneNumber) {
  String countryCode = StringUtils.left(phoneNumber, phoneNumber.indexOf("-")).replaceAll("\\D+","");

  return countryCode.length() >= 1 && countryCode.length() <= 3;
}

What is the best way of validating the country code?

A: First of all I have to say that it's usually a bad idea to require phone numbers to fit a specific format and length as you'll invalidate plenty of valid numbers this way, but I don't know your use case.
Despite the joke I'd use regular expressions:
\+\d{1,3}-[()\d\s-]+

This regular expressions matches strings that have

*

*a literal plus,

*followed by 1-3 digits

*then a hyphen

*then one or more characters in the set of brackets, digits, spaces, or hyphens

The last category could be altered to fit your exact specifications.

import java.util.regex.Pattern;

class PhoneNumber {
  protected static void checkNumber(String number) {
    System.out.println(number + " : " + (
      Pattern.matches("\\+\\d{1,3}[-][()\\d\\s-]+", number)
        ? "valid" : "invalid"
      )
    );
  }

  public static void main(String[] args) {
    String number;
    checkNumber("+1-555-5555");
    checkNumber("+12-5555555");
    checkNumber("+123-(555) 555-5555");
    checkNumber("+1(555) 555-5555");
    checkNumber("5555555555");
    checkNumber("+5555555555");
  }
}

This produces:
+1-555-5555 : valid
+12-5555555 : valid
+123-(555) 555-5555 : valid
+1(555) 555-5555 : invalid
5555555555 : invalid
+5555555555 : invalid

A: Try this.

*

*starts with a +

*then 1-3 digits.

*then a -

*followed by anything.

    String[] tel = { "+1-555-5555",
                "+12-5555555",
                "+123-(555) 555-5555",
                "+1- 555-5555",
                "(555)555-5555",
                "+1 (555) 555-5555",
                "+12-(555) 555-555"};

        String pat =
                "\\+\\d{1,3}-.*";
        for (String s : tel) {
           System.out.printf("%20s -> %s%n", s, s.matches(pat) ? "good" : "bad");
        }

A: For your example phone numbers, you might pattern with an optional group to match the digits between parenthesis and make the hyphen optional.
^\+\d{1,3}-(?:\(\d{3}\)\h*)?\d{3}-?\d{4}$

Explanation

*

*^ Start of string

*\+\d{1,3}-

*(?: Non capture group

*

*\(\d{3}\)\h* Match (, 3 digits, ) and 0+ horizontal whitespace chars

*)? close group and make it optional

*\d{3}-?\d{4} Match 3 digits, an optional - and 4 digits

*$ End of string

Regex demo | Java demo
In Java
String regex = "^\\+\\d{1,3}-(?:\\(\\d{3}\\)\\h*)?\\d{3}-?\\d{4}$";

For example
String strs[] = {
        "+1-555-5555",
        "+12-5555555",
        "+123-(555) 555-5555",
        "+1(555) 555-5555",
        "5555555555",
        "+5555555555",
        "+123-)(----"
    };
String regex = "\\+\\d{1,3}-(?:\\(\\d{3}\\)\\h*)?\\d{3}-?\\d{4}";
for (String s : strs)
    System.out.printf("%s --> %s%n", s, s.matches(regex) ? "Match" : "No match");

Output
+1-555-5555 --> Match
+12-5555555 --> Match
+123-(555) 555-5555 --> Match
+1(555) 555-5555 --> No match
5555555555 --> No match
+5555555555 --> No match
+123-)(---- --> No match

A: You can use the regex mentioned in the solution given below:
public class Main {
    public static void main(String[] args) {
        String[] phoneNumbers = { "+1-555-5555", "+12-5555555", "+123-(555) 555-5555", "+1(555) 555-5555", "5555555555",
                "+5555555555" };
        for (String phoneNumber : phoneNumbers) {
            if (phoneNumber.matches("^[+][0-9]{1,3}[-][[(]{0,1}[0-9]+[-)\\s]{0,1}]*[0-9]{4}$")) {
                System.out.println(phoneNumber + " passed validation");
            } else {
                System.out.println(phoneNumber + " failed validation");
            }
        }
    }
}

Output:
+1-555-5555 passed validation
+12-5555555 passed validation
+123-(555) 555-5555 passed validation
+1(555) 555-5555 failed validation
5555555555 failed validation
+5555555555 failed validation


text:
Q: What differentiates syntax analysis and semantic analysis? To my understanding, Parser is composed of three stages of lexical, syntactic and semantic analysis.

*

*Lexical: It will split my input into tokens. Example: 123+100-0 -> 123 + 100 - 0

*Syntactic: It will look into the tokens and check if they make sense with each other.
The problem i am having is understanding the final phase "semantic parsing" and how it differentiates to the second stage "syntactic analysis". To my understanding the final stage "semantic parsing" also validates the tokens that has been validated by "syntactic analysis" and then prints out the output.

A: Generally speaking, the goal of syntax analysis is to turn a stream of tokens (generated by lexical analysis) into some sort of structured representation of what the program "means." For example, in syntax analysis, you'd expect the tokens a, /, and b to be converted into something that says "the quotient of a and b." Typically, the output of syntax analysis is an abstract syntax tree, which is a tree structure encoding the structure of the program.
The job of semantic analysis is to make sure that the representation generated by the syntax analysis step actually "makes sense." For example, suppose that the syntax analyzer has converted a, /, and b into "the quotient of a and b." At the time the syntax analyzer did this, it probably had no conception of what the types of a and b were; more likely, the syntax analyzer simply saw that this could be interpreted as a mathematical expression and left things at that. However, it's entirely possible that this is not a well-defined operation. For example, if a is a string and b is a boolean, then a / b is a nonsense operation and the compiler should report an error.
For a more elaborate example, suppose you're implementing a Java compiler and you see the tokens public, class, A, extends, B, {, }. You could interpret this to be a class definition during syntax analysis, since it's a syntactically-valid class. But what if B, which is defined later in the file, isn't a class? Or what if B isn't defined at all? In that case, the code is incorrect. It's syntactically valid in the sense that it conceivably could be legitimate code, but it's semantically incorrect in that there isn't a class B to be found. The syntax analyzer would therefore produce a totally valid AST, while the semantic analyzer would then reject the code after it found that B didn't exist.
There's no fundamental reason why we have to keep these two steps separated, and in fact some compilers meld the two together. The main reason for doing this is practical - we have some great tools for building syntax analyzers (LR parsers, LL parsers, etc.), and they work by interpreting sequences of tokens without thinking too much about what they mean. The compiler author can then specify the general syntax of the language, then write a semantic analyzer as a second pass that looks over the AST and determines whether it's valid. This makes the separation between what the parser generators can do automatically and what the programmer needs to write code for cleaner.
Hope this helps!

A: Theoretically, syntactic analysis determines whether or not an instance of the language is "well formed" and analyzes its grammatical structure, while semantic analysis analyzes its meaning and whether or not it "makes sense".
Basically, syntactic analysis may depend on the types of words, but not their meaning.  Semantic analysis depends on the meanings.  "I like green tomatoes" and "I fill wiggly thougts" have the same syntactic structure and are both well-formed, but the latter makes no sense semantically.
This theoretical distinction is actually a little blurry, because separating a word's "type" from its "meaning" involves some arbitrary choices.
In the practice of compiler development, however, the distinction is clear:  Syntactic analysis is performed by the parser, driven by the grammar, depending on the types of the tokens.  Semantic analysis starts with the actions, written in code, attached to the rules in the grammar.  Basically anything that needs to look up an actual identifier or evaluate the actual value of a literal value, is semantic analysis.
Some languages require the results of semantic analysis to be fed back into the parser to help with syntactic analysis.  This ruins the theoretical distinction between syntactic and semantic analysis, but practically we just recognize this as a bit of a cheat and continue to refer to the parsing code as syntactic.


text:
Q: Python regex match two string at two different order? I want to match aaa bbb and bbb aaa in the following string:
aaa  bbb   bbb    aaa

using
match = re.search("^(?=.*(aaa))(?=.*?(bbb)).*$", subject, re.DOTALL | re.IGNORECASE)

see https://www.regex101.com/r/vA0nB0/2
But it only match aaa bbb.
How can I match bbb aaa too?

A: If Python supports conditionals:
For out of order stuff, just use a conditional.
Note - change the quantifier in the group to reflect how many items
are required to match. Below shows {2} which requires both items somewhere.
You could change it to {1,} - at least 1, or + - same thing.
(?:.*?(?:((?(1)(?!))aaa.*?bbb)|((?(2)(?!))bbb.*?aaa))){2}
Formatted:
 (?:
      .*?
      (?:
           (                        # (1)
                (?(1)
                     (?!)
                )
                aaa .*? bbb
           )
        |  (                        # (2)
                (?(2)
                     (?!)
                )
                bbb .*? aaa
           )
      )
 ){2}

Output:
 **  Grp 0 -  ( pos 0 , len 21 )
aaa  bbb   bbb    aaa
 **  Grp 1 -  ( pos 0 , len 8 )
aaa  bbb
 **  Grp 2 -  ( pos 11 , len 10 )
bbb    aaa

A: You could try the below simple regex.
>>> import re
>>> s = 'aaa  bbb   bbb    aaa'
>>> re.findall(r'aaa.*?bbb|bbb.*?aaa', s)
['aaa  bbb', 'bbb    aaa']

A: How about something like this, if you know that its always going to be aaa or bbb?
>>> a = 'aaa  bbb   bbb    aaa'
>>> match = re.findall("(aaa|bbb).+?(aaa|bbb)", a, re.DOTALL | re.IGNORECASE)
>>> match
[('aaa', 'bbb'), ('bbb', 'aaa')]

Here is the regex101 link : https://www.regex101.com/r/qO3uD3/1


text:
Q: Material-UI's TextField validation and onChange event handler don't seem to work as expected I'm using React and Material-UI's TextField with type='number' but as I saw the validation is rather simple, it just allows any character that could represent part of a number [0-9\.eE-]*, allowing inputs like this: eee---...e---0.-1, I decided to implement my own validation. (not sure if that trivial validation is Material-UI's or HTML native, but doesn't matter anyway)
So I wrote this regular expression for validation, but as soon as I enter a character that doesn't match my regular expression, my onChange event handler doesn't get called at all and it seems the component takes control and applies its basic validation. My event handler doesn't get called again until I correct the input and make it match with my regular expression.
Can I prevent the component from doing this somehow?
onValueChange = (ev) => {
    if( /^-?(\d+)?(\.\d*)?$/.test(ev.target.value)) {
        this.setState({ value: ev.target.value });
    }

Complete code: https://codepen.io/anon/pen/eoZOaE?editors=1000

A:
(not sure if that trivial validation is Material-UI's or HTML native, but doesn't matter anyway)

This trivial validation is native, since Material-UI InputBase component only transmits type='number' to the native <input /> and doesn't define any additional validations.
And seems like onchange event that doesn't get fired on every input - is also the behavior of native input. You can check it in this example: https://codesandbox.io/s/20z5qrnqq0?fontsize=14 - as you can see - onChange event is also getting fired only for the 'valid' characters.
I tried to find some other solutions, with oninput HTML5 event, as it was suggested here, but it doesn't work either. So in this case I think that you do the right decision with using the type='text' input to control all possible inputs.


text:
Q: Pivot table in CakePHP 3 A product is available in many shops and each shop has a different price for that product.
+----------------------------------+
|         SHOP_PRODUCT             |
+----------------------------------+
| product_id (PK + FK) e.g. 9      |
| shop_id    (PK + FK) e.g. 5      |
| url                  e.g. ggl.com|
| price                e.g. 20.00  |
+----------------------------------+

I want to be able to go in the product add template and add shops and price for the product.
How do I make these kind of associations in CakePHP 3?

A: The easiest way to do that is to stablish a different entity as an intermediate table, in that case I would suggest product_prices or a more complete solution would be to make an product_stocks and that product_stock may have another table with the historic prices.
Another option is to add a surrogate key to the intermediate table that you were using initially, the reference information for that is here:
https://book.cakephp.org/3.0/en/orm/associations.html#using-the-through-option
Also by convention the name of the table should be products_stores as stated here:
https://book.cakephp.org/3.0/en/intro/conventions.html#database-conventions


text:
Q: Error: Compile Error: Comparison arguments must be compatible types: Schema.SObjectField, Boolean at line 221 column 63 Below is the code. What deoes this error mean.
 if((salesRepMapping.Account_Owner__c == true) && (Account.KRM_Program__c == false)){
                a.OwnerId = salesRepMapping.Sales_Rep__c;
            }

A: Either the Account_Owner__c field or KRM_Program__c is not of type boolean, yet you're trying to compare it against a boolean value (true/false). Double check the types of those fields and compare against a value of an appropriate type.


text:
Q: Using JAVA array or list to fill text boxes on a page designed by Selenium Page Object Model package com.objects;
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
import com.tests.BaseClass;

public class LinkedInHomePage extends BaseClass {

public LinkedInHomePage(WebDriver driver) {
    PageFactory.initElements(driver, this);
}

@FindBy(how = How.ID, using = "firstName-coldRegistrationForm")
public WebElement newFirstNameTexthBox;

@FindBy(how = How.NAME, using = "lastName")
public WebElement newLastNameTexthBox;

@FindBy(how = How.ID, using = "email-coldRegistrationForm")
public WebElement newEmailTexthBox;

@FindBy(how = How.ID, using = "password-coldRegistrationForm")
public WebElement newPasswordTexthBox;

@FindBy(how = How.ID, using = "btn-submit")
public WebElement signUpButton;

public void EnterNewFirstName(String inComingNewFirstName) {
    newFirstNameTexthBox.clear();
    newFirstNameTexthBox.sendKeys(inComingNewFirstName);
}

public void EnterNewLastName(String inComingNewLastName) {
    newLastNameTexthBox.clear();
    newLastNameTexthBox.sendKeys(inComingNewLastName);
}

public void EnterNewEmail(String inComingNewEmail) {
    newEmailTexthBox.clear();
    newEmailTexthBox.sendKeys(inComingNewEmail);
}

public void EnterNewPassword(String inComingNewPassword) {
    newPasswordTexthBox.clear();
    newPasswordTexthBox.sendKeys(inComingNewPassword);
}

public void ClickSignUp() {
    signUpButton.click();
}

public void JoinNow(String FName, String LName, String Email,
        String Password) {
    EnterNewFirstName(FName);
    EnterNewLastName(LName);
    EnterNewEmail(Email);
    EnterNewPassword(Password);
    ClickSignUp();
}

}
The JoinNow() function above as you can see takes multiple parameters and it works perfectly fine. I would like use array or list to reduce
the number of arguments and then use loop to fill the text boxes. I want to accomplish something similar as below, but since I am using Page Object Model Design, can't use findElement.
@SuppressWarnings("unchecked")
protected void JoinNow(String... var) {
    List<MyElements> inputElements = new ArrayList<MyElements>();
    inputElements.add((MyElements) driver.findElement(By
            .id("firstName-coldRegistrationForm")));
    inputElements.add((MyElements) driver.findElement(By.id("lastName")));
    inputElements.add((MyElements) driver.findElement(By
            .id("email-coldRegistrationForm")));
    inputElements.add((MyElements) driver.findElement(By
            .id("password-coldRegistrationForm")));

    for (int i = 0; i < var.length; i++) {
        ((WebElement) inputElements.get(i)).sendKeys(var[i]);
    }
}

A: There are couple of items you need to consider while doing page object model. Based on how you have done it (by using @FindBy), sometimes you will end up with stale data. For better results you should be defining your ids like below and use them to get you Webelemment. This is how i would design it. Define all your By.id and put it into a list and use the function below to simplify it.
Definition of by:
static final By FNAME_REGFORM_BY_ID = By.id("firstName-coldRegistrationForm");
public void fillTextBoxes(List<By> bys, List<String> valuesToPopulate) {
    List<WebElement> webelements = new ChromeDriver().findElements(By.cssSelector("input[type=text]"));
    for (int i = 0; i < bys.size(); i++) {
        new ChromeDriver().findElement(bys.get(i)).sendKeys(valuesToPopulate.get(i));
    }
}

Edit: For better understanding, fillTextBoxes was equivalent of joinNow.
List<String> values=new LiskedList<String>();
Values.add("emailid");
values.add("firstname");

List<By> bys=new LinkedList<By>();
bys.add(FNAME_REGFORM_BY_ID);
bys.add(EMAIL_ID_By_ID);

public void joinNow(List<By> bys, List<String> values) {
    List<WebElement> webelements = new ChromeDriver().findElements(By.cssSelector("input[type=text]"));
    for (int i = 0; i < bys.size(); i++) {
        new ChromeDriver().findElement(bys.get(i)).sendKeys(valuesToPopulate.get(i));
    }
}

Don't use Annotated @FindBy(how = How.ID, using = "email-coldRegistrationForm") etc, as this slow down execution as well as gives you stale data. FindBy tends to slow down as the entire page object becomes completely initialized only after all elements are available. Try using Static By like i mentioned. We ran into perf issues and started switching from annotated Findby.
Based on request, here is a sample implementation. You might have to tweak based on your project requirements, but this should get started.
Your Page Class (renamed as SO for my sake).
public class SO {

    WebDriver driver;

    static final By FNAME_REGFORM_BY_ID = By.id("firstName-coldRegistrationForm");
    static final By LNAME_REGFORM_BY_NAME = By.className("lastName");
    static final By EMAIL_REGFORM_BY_ID = By.id("email-coldRegistrationForm");
    static final By PWD_REGFORM_BY_ID = By.id("password-coldRegistrationForm");
    static final By SUBMIT_REGFORM_BY_ID = By.id("btn-submit");

    public SO(WebDriver driver) {
        this.driver = driver;
    }

    public List<By> getAllInput() {
        List<By> bys = new LinkedList<By>();
        bys.add(FNAME_REGFORM_BY_ID);
        bys.add(LNAME_REGFORM_BY_NAME);
        bys.add(LNAME_REGFORM_BY_NAME);
        bys.add(LNAME_REGFORM_BY_NAME);
        bys.add(LNAME_REGFORM_BY_NAME);
        return bys;
    }

    public void joinNow(List<String> values) {
        PageFactory.initElements(this.driver, HotelDetailsPage.class);
        List<By> bys = this.getAllInput();
        List<WebElement> webElements = this.driver.findElements(By.cssSelector("input[type=text]"));
        for (int i = 0; i < bys.size(); i++) {
            new ChromeDriver().findElement(bys.get(i)).sendKeys(values.get(i));
        }
    }

    public SO open(final String url) {
        this.driver.get(url);
        return this;
    }
}

Test Method:
   @Test
public void testForm() {
    WebDriver driver = new FirefoxDriver();
    SO so = new SO(driver);
    SO soPage = so.open("your app url");

    List<String> values = new LinkedList<String>();
    values.add("firstname");
    values.add("lastName");
    values.add("emailId");
    values.add("password");
    values.add("id");
    soPage.joinNow(values);
}

A: Why not send a Map to JoinNow method. I suggest you keep your PageObject pattern as is. I believe this is more readable and more maintainable long term
Map<String,String> data  = new HashMap<String,String>();
data.put("firstname", "George");
data.put("lastname", "Clooney");
data.put("email", "George@xyz.com");
data.put("password", "Dontguess");
JoinNow(data);

protected void JoinNow(Map<String,String> data) {
    firstNameElement.sendKeys(data.get("firstname"));
    lastNameElement.sendKeys(data.get("lastname"));
    emailElement.sendKeys(data.get("email"));
    passwordElement.sendKeys(data.get("password"));
}

A: Following is the another way:
HashMap<WebElement, String> d = new HashMap<WebElement, String>();
d.put(newFirstNameTexthBox, "Michael");
d.put(newLastNameTexthBox, "Johnson");
d.put(newEmailTexthBox, "a@b.com");
d.put(newPasswordTexthBox, "Michael123$");
joinNow(d);

protected void JoinNow(Map<WebElement,String> data) {
    for (Entry<WebElement, String> objValue : data.entrySet())
        objValue.getKey().sendKeys(objValue.getValue());
}


text:
Q: Changing a Property into a Method - any side effects? I have a class that has some properties. And I want something that calculates a Score out of these properties. Since this is a trivial task (some additions and divisions, but nothing spectacular).
So naturally, the question is: "When to use a Property with some code in the getter, and when to use a function?", and that question was already answered.
Now, I wonder about one thing though: If - against all expectations - I ever needed to make this Getter so complicated that it should be a function (for example, because I need to put data in or because it can throw an exception or whatever), is it easy to change a Property into a Method?
Of course, it seems really trivial, just changing
public double Score {
    get {
        return Math.Round(A + B / C * D,3);
    }
}

to
public double Score(){
    return Math.Round(A + B / C * D,3);
}

But I wonder: Are there any side effects? Is anything going to break when changing stuff around like this? I can only ever see this as a possible problem when Reflection is involved, but what in situations where I have 2 Assemblies - one that defines the class and one that uses the class - and only change the one that contains the class without recompiling the consumer assembly. Is that a possible source of "weird bugs that are nearly impossible to track" or is it completely safe to change Properties to Methods?

A: Pull up reflector, you'll see that your properties already are methods :)

A: No. There are no side affects to this at all.

Pull up reflector, you'll see that
  your properties already are methods

Under the hood the get and set accessors in a property are simply converted to get_MyPropertyName() and set_MyPropertyName() methods. This is also why you can (but typically shouldn't) add parameters to a property.
The only "gotcha" is that in C# you will need to add "()" to any existing calls.
Also

according to the coding guidelines, a
  property name usually is noun (i.e.
  Score), but methods should describe
  actions (verb), so more proper name is
  GetScore() or CalculateScore()

A: If you are going to change from property to method and allow the compiler to show you where to add the parethesis, you could get subtle bugs  as object ting = thing.score ting would be a boxed double for the property version of score but a delegate for a method version of score therefore different code path would result where:
public void erm(double param){ //stuff here}
public void erm(func<double> param) {// different stuff here}

when you call with
erm(thing.score)

with the property versus method version of score.

A: One side affects is breaking all the calling code to this property.  You will have update all callers to us the method signature rather then property

A: As others already pointed out - nothing to worry. I just post to clarify that according to the coding guidelines, a property name usually is noun (i.e. Score), but methods should describe actions (verb), so more proper name is GetScore() or CalculateScore() :)
Grammar Nazi in action :)


text:
Q: Having problems Reading a file in C I am trying to solve a problem which requires me to read a file and generate another file which has the same contents as the original but every fourth byte removed.I tried it doing this way ...
int main()
{
  FILE *p;
  FILE *q;
  int i=0,k=0;
  char c;

  p = fopen("C:\\Users\\Teja\\Desktop\\Beethoven.raw","rw");
  q = fopen("C:\\Users\\Teja\\Desktop\\Beethoven_new.raw","w+");

  printf("%x is the EOF character \n",EOF);
  while((c=fgetc(p))!=EOF)
  {

     if(i==3){
      i=0;
      printf("Removing %x %d \n",c,k++);
     }
     else{
      printf("Putting %x %d \n",c,k++);
      fputc(c,q);
      i++;
     }
  }
  fclose(p);
  fclose(q);

  return 0;
}

The file that i was trying to read is a .raw file and it is around 10-15 MB. I notice that the above code stops reading the file after typically 88 bytes. Is there any way to read large files or am i doing anything wrong ?

A: In addition to what has already been pointed out, a note on opening files: It sounds like your file in a binary file, which means you must add a b to the mode string. Additionally, rw is not a mode, since you only read from p you want rb, and since you only write to q you want wb or wb+.
By the way, the reason why you need fgetc to return an int is because fgetc must return 257 unique values: all the possible values of char, that is 0x00 thru 0xFF as well as something unique to signify EOF, usually -1

A: Change
char c;

to
int c;

as the return type of fetgetc() is an int and not char.


text:
Q: Display plugin-generated content to override a placeholder page I am building a plugin, but despite several search parameters, I cannot figure out how to replace a page's content with custom content generated by my plugin.
I have already written several shortcodes and widgets, but I'd like to replace the whole page.
The best example I have is CiviCRM. When the plugin gets installed, it generates a placeholder page which is replaced by custom content, I believe based on the query string.
I assume there's an add_action or similar add_ function I need to call for the plugin function to be called when the page loads.


text:
Q: How to see the Steps number in an algorithm In below algorithm I have used the package
\usepackage[linesnumbered,ruled,vlined]{algorithm2e}

1) How do I see steps number after step 2?
2) Is there any command apart from
\renewcommand{\labelenumi}{(\Roman{enumi})}

to get the item number as in roman font?
\begin{algorithm}
\DontPrintSemicolon % Some LaTeX compilers require you to use \dontprintsemicolon    instead
\KwIn{a,b,c,d}
\KwOut{e,r}
Calculate $x$, and $y$\\
Check,
\renewcommand{\labelenumi}{(\Roman{enumi})}
\begin{enumerate}[noitemsep,nolistsep]
\item If  $k \geq n$, then the  $m_{2}$.
\item If  $h \geq j$, then  $m_{1}$.
\end{enumerate}
Otherwise,\\
Initialisation: \textit{$g(0)=nj$}\\
$i=0$\\
Compute $n_{2}$,
\[
n(i)=\frac {a}{b(i)\sqrt{3v}}
\]\\
Update $b$,
\[
b(i+1)=( -\frac{1}{2(g(i)/D}+1)
\]\\
$i=i+1$,\\
Repeat \textit{Steps 3 to 6}, till $|a(i+1)-a(i) |<\epsilon$
\caption{algo of g}
\label{algo:b}
\end{algorithm}

A: Some changes and the numbers appear:
\documentclass{article}
\usepackage[linesnumbered,ruled,vlined]{algorithm2e}

\begin{document}

\begin{algorithm}
%\DontPrintSemicolon % Some LaTeX compilers require you to use \dontprintsemicolon    instead
\KwIn{a,b,c,d}
\KwOut{e,r}
Calculate $x$, and $y$\\
Check, \linebreak
%\renewcommand{\labelenumi}{(\Roman{enumi})}
%\begin{enumerate}[noitemsep,nolistsep]
%\item
 (I) If  $k \geq n$, then the  $m_{2}$.
\linebreak
%\item
(II) If  $h \geq j$, then  $m_{1}$.\\
%\end{enumerate}
Otherwise,\\
Initialisation: \textit{$g(0)=nj$}\\
$i=0$\\
Compute $n_{2}$,
\[
n(i)=\frac {a}{b(i)\sqrt{3v}}
\]\\
Update $b$,
\[
b(i+1)=( -\frac{1}{2(g(i)/D}+1)
\]\\
$i=i+1$,\\
Repeat \textit{Steps 3 to 6}, till $|a(i+1)-a(i) |<\epsilon$
\caption{algo of g}
\label{algo:b}
\end{algorithm}

\end{document}

I am not sure, which lines should be numbered, but the general idea is clear now, I hope.

A: Here's an approach that uses the functionality provided by algorithm2e to form conditional and repetition structures. Of course, since you're calling the package with vlined, the output also includes this.

\documentclass{article}
\usepackage[linesnumbered,ruled,vlined]{algorithm2e}% http://ctan.org/pkg/algorithm2e
\DontPrintSemicolon
\begin{document}

\begin{algorithm}
  \KwIn{$a$, $b$, $c$, $d$}
  \KwOut{$e$, $r$}
  Calculate~$x$ and~$y$\;
  \lIf{$k \geq n$}{$m_2$}\;
  \lIf{$h \geq j$}{$m_1$}\;
  \Else{%
    \Repeat{$|a(i+1)-a(i)| < \epsilon$}{%
      Initialisation: $g(0) = nj$\;\label{stepA}
      $i=0$\;
      Compute~$n_2$
      \[
        n(i) = \frac{a}{b(i)\sqrt{3v}}
      \]
      \nl Update~$b$
      \[
        b(i+1) = (-\frac{1}{2(g(i)/D} + 1)
      \]
      \nl $i = i + 1$\;
    }
  }
  \caption{My algorithm}
  \label{algo:b}
\end{algorithm}

\end{document}

Note that, instead of manually referencing steps, you can use a regular \label and \ref it later.

A: I just ran into this problem myself. My solution was to put "{" and "}" before and after enumitem, i.e.
{
\begin{enumerate}[noitemsep,nolistsep]
\item If  $k \geq n$, then the  $m_{2}$.
\item If  $h \geq j$, then  $m_{1}$.
\end{enumerate}
}

I hope this solution works for you too (if you still need it).


text:
Q: EasySNMP: Different output converting OCTETSTR to Hex When I use the function encode to convert OCTET to Hex, some characters are add when it shouldn't.
Example:
Linux:
snmpwalk -t 5 -v2c -c public 192.168.10.150 iso.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1
SNMPWALK output: iso.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1.144 = Hex-STRING: AC 84 C6 5F 95 EF B0 4E 26 8B 1C C5 C0 4A 00 AE
Code:
session = Session(hostname='192.168.10.150', community='public', version=2)
description = session.walk('iso.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1')

for item in description:
    print '{oid}.{oid_index} {snmp_type} = {value}'.format(
         oid=item.oid,
         oid_index=item.oid_index,
         snmp_type=item.snmp_type,
         value=item.value.encode("hex"))

EasySNMP output: iso.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1.144. OCTETSTR = c2acc284c3865fc295c3afc2b04e26c28b1cc385c3804a00c2ae59c293c2b04e26c28b4ec2ad
Some OIDs are used, but the output is different from what I expected. Is it the correct the way to use easysnmp?
Packet Capture
SNMPWalk (Linux):
    192.168.10.214  192.168.10.150  get-next-request 1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1 Value(NULL)
Simple Network Management Protocol
    version: v2c (1)
    community: public
    data: get-next-request (1)
        get-next-request
            request-id: 686772965
            error-status: noError (0)
            error-index: 0
            variable-bindings: 1 item
                1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1: Value (Null)
                    Object Name: 1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1 (iso.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1)
                    Value (Null)

    192.168.10.150  192.168.10.214  get-response 1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1.51
Value(00:02:18:a6:f7:65:88:f5:18:a6:f7:65:18:a6:f7:65:88:f5:b0:4e:26:8a:e3:cb:50:c7:bf:f2:db:95:b0:4e:26:ed:8d:c5:98:de:d0:76:e3:01:00:02:98:de:d0:76)
Simple Network Management Protocol
    version: v2c (1)
    community: public
    data: get-response (2)
        get-response
            request-id: 686772965
            error-status: noError (0)
            error-index: 0
            variable-bindings: 1 item
                1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1.5: 000218a6f76588f518a6f76518a6f76588f5b04e268ae3cb...
                    Object Name: 1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1.5 (iso.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1.5)
                    Value (OctetString): 000218a6f76588f518a6f76518a6f76588f5b04e268ae3cb...

    192.168.10.214  192.168.10.150  get-next-request 1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1.5 Value(NULL)
Simple Network Management Protocol
    version: v2c (1)
    community: public
    data: get-next-request (1)
        get-next-request
            request-id: 686772966
            error-status: noError (0)
            error-index: 0
            variable-bindings: 1 item
                1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1.5: Value (Null)
                    Object Name: 1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1.5 (iso.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1.5)
                    Value (Null)

    192.168.10.150  192.168.10.214  get-response 1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.2.48 Value(70:4f:57:4d:cc:cf:b0:4e:26:8b:45:11:ac:84:c6:1d:0e:c5:70:4f:57:3a:dd:5b:70:4f:57:4c:92:8f:b0:4e:26:8a:ef:99)
Simple Network Management Protocol
    version: v2c (1)
    community: public
    data: get-response (2)
        get-response
            request-id: 686772966
            error-status: noError (0)
            error-index: 0
            variable-bindings: 1 item
                1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.2.48: 704f574dcccfb04e268b4511ac84c61d0ec5704f573add5b...
                    Object Name: 1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.2.48 (iso.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.2.48)
                    Value (OctetString): 704f574dcccfb04e268b4511ac84c61d0ec5704f573add5b...

EasySNMP:
    192.168.10.214  192.168.10.150  get-next-request 1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1 Value(NULL)
Simple Network Management Protocol
    version: v2c (1)
    community: public
    data: get-next-request (1)
        get-next-request
            request-id: 1767019562
            error-status: noError (0)
            error-index: 0
            variable-bindings: 1 item
                1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1: Value (Null)
                    Object Name: 1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1 (iso.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1)
                    Value (Null)

    192.168.10.150  192.168.10.214  get-response 1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1.5 Value(00:02:18:a6:f7:65:88:f5:18:a6:f7:65:18:a6:f7:65:88:f5:b0:4e:26:8a:e3:cb:50:c7:bf:f2:db:95:b0:4e:26:ed:8d:c5:98:de:d0:76:e3:01:00:02:98:de:d0:76)
Simple Network Management Protocol
    version: v2c (1)
    community: public
    data: get-response (2)
        get-response
            request-id: 1767019562
            error-status: noError (0)
            error-index: 0
            variable-bindings: 1 item
                1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1.5: 000218a6f76588f518a6f76518a6f76588f5b04e268ae3cb...
                    Object Name: 1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1.5 (iso.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1.5)
                    Value (OctetString): 000218a6f76588f518a6f76518a6f76588f5b04e268ae3cb...

    192.168.10.214  192.168.10.150  get-next-request 1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1.5 Value(NULL)
Simple Network Management Protocol
    version: v2c (1)
    community: public
    data: get-next-request (1)
        get-next-request
            request-id: 1767019563
            error-status: noError (0)
            error-index: 0
            variable-bindings: 1 item
                1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1.5: Value (Null)
                    Object Name: 1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1.5 (iso.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1.5)
                    Value (Null)

    192.168.10.150  192.168.10.214  get-response 1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.2.48 VALUE(70:4f:57:4d:cc:cf:b0:4e:26:8b:45:11:ac:84:c6:1d:0e:c5:70:4f:57:3a:dd:5b:70:4f:57:4c:92:8f:b0:4e:26:8a:ef:99)
Simple Network Management Protocol
    version: v2c (1)
    community: public
    data: get-response (2)
        get-response
            request-id: 1767019563
            error-status: noError (0)
            error-index: 0
            variable-bindings: 1 item
                1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.2.48: 704f574dcccfb04e268b4511ac84c61d0ec5704f573add5b...
                    Object Name: 1.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.2.48 (iso.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.2.48)
                    Value (OctetString): 704f574dcccfb04e268b4511ac84c61d0ec5704f573add5b...

A: Okay. We can tell the following:

*

*The requests are identical from both managers

*The responses to both requests are identical

This means that either the Net-SNMP output is "mangled"/transformed, or the EasySNMP output is.
Unfortunately the packet captures don't show the interactions that were described in the original version of the post, so we cannot immediately tell which manager is at fault. However, it is possible to make a deduction based on the values that we see.
Your Python script's output is almost a superset of the snmpwalk output:

*

*Net-SNMP:

*

*AC 84 C6 5F 95 EF B0 4E 26 8B 1C C5 C0 4A 00 AE

*Python script:

*

*C2 AC C2 84 C3 86 5F C2 95 C3 AF C2 B0 4E 26 C2 8B 1C C3 85 C3 80 4A 00 C2 AE 59 C2 93 C2 B0 4E 26 C2 8B 4E C2 AD

So why have additional bytes been added, and why have some bytes been lost? This smells like a re-encoding of the source data, right?
We can observe that byte C2 pops up a lot. What's that? It's the "extended ASCII" (there's actually no such thing, but in many codepages) for the character Â. Aha, red flag. Why's it a red flag? Because this is commonly evidence of misinterpreted UTF-8. (I could explain in more detail why this is, but I'll let you research Unicode encodings separately if you desire.)
So, using an online tool or two, let's decode that second byte stream as UTF-8 and see what logical codepoints we get:

U+AC U+84 U+C6 U+5F U+95 U+EF U+B0 U+4E U+26 U+8B U+1C U+C5 U+C0 U+4A U+AE U+59 U+93 U+B0 U+4E U+26 U+8B U+4E U+AD

Hey, that looks familiar! (Again, I've bolded the bits that match the Net-SNMP output.) U+00 is missing (presumably because that is a "null" byte much as in ASCII) and there's still a bunch of noise at the end (if you're interested, they render like this: "Y°N&N"), but we can now at least see what's going on: your original byte stream has been re-encoded as a UTF-8 string. Indeed, Python 3's default encoding is UTF-8.
The reason that bytes like C6 disappeared entirely is that they fall outside of the ASCII range, so map "uncleanly" in Unicode. ASCII C6, it turns out, is U+00C6, which is represented in UTF-8 by C3 86, so now we know where the unbolded bytes come from, too.
So, EasySNMP is treating your walk result as a string rather than as an opaque sequence of bytes, and as a result Python has mangled it. Then, when you wrote .encode("hex"), you got the hex-pair representation of this new, falsified UTF-8 string.
This should probably not be happening. The SNMP response is clearly indicated as an "OctetString", and the spec tells us that "The OCTET STRING type represents arbitrary binary or textual data". The MIB (which you do not appear to be using, or at least have not provided) for the agent with which you are communicating may provide further encoding information; in the absence of that information, there's no way to know for sure how an OCTET STRING should be displayed. For example, this Net-SNMP bug discusses literally making a guess when applicable.
Anyway, all very interesting, but what can we do about it?
The EasySNMP docs are fairly thin, but we can poke around in the source code a bit (and, in the process, discover that EasySNMP is actually just a Python wrapper around Net-SNMP!) and on the EasySNMP issues list, where it turns out someone's complained about this before.
Again, then, what can we do about it?
Um, I'm not sure that there's much we can do about it. This is currently a flaw in EasySNMP. Things are Unicodised (either by EasySNMP itself, by way of conversion to Python strings, or by the Net-SNMP compat module described earlier) even when they should not be.
However, this chap has suggested a workaround that you could try:
session = Session(
   hostname='192.168.10.150',
   community='public',
   version=2,
   use_sprint_value=False
)

That new final argument ought to turn off value transformation. However, I'm not convinced, because per the docs it's already False by default.
Beyond trying it anyway, I think your best bet is to add your weight to the relevant issue report(s) and pressure the developer to come up with a fix. Sorry.

A: I believe you're having the same issue that I have. I've talked about it on Github recently as well. Compat.py within the library is encoding the data as latin-1 instead of utf-8.
Regardless, based on your original code example the following should work:
session = Session(hostname='192.168.10.150', community='public', version=2)
description = session.walk('iso.3.6.1.4.1.25355.3.2.6.4.2.5.1.7.1.1.1')

for item in description:
    print '{oid}.{oid_index} {snmp_type} = {value}'.format(
         oid=item.oid,
         oid_index=item.oid_index,
         snmp_type=item.snmp_type,
         value=item.value.encode("latin-1").hex())

This will give you the hex as a continuous string. If you'd rather it as a bytes object just leave off the '.hex()' in value.
You could also do some comparisons if you wanted to be sure if you know the hex with something like:
from easysnmp import snmp_get

OID = iso.0.8802.1.1.2.1.4.1.1.7.2520.9.1
foo = snmp_get(OID, hostname='192.0.2.1', community='public', version=2).value.encode('latin-1')
foo == bytes.fromhex("312f3300")

In that example we're assuming the OID is returning the 31 2F 33 00 hex value for comparison.

A: To get the right hex value, I'm using this.
     def toRaw(s):
       x = [ord(i) for i in list(s)]
       return bytearray(x)

     print(toRaw(item.value).hex().upper())


text:
Q: increment a variable date by a month Is there way on how to increment an input date by one month without using the date -d option? My machine do not have that functionality.
Sample:
$yearmonth=201912

Expected Output:
201912
202001

A: POSIXly (assuming $yearmonth doesn't have leading zeros):
case $((yearmonth += 1)) in
  (*13) yearmonth=$((yearmonth + 100 - 12))
esac

With ksh/bash/zsh, you could shorten it to:
((++yearmonth % 100 <= 12)) || ((yearmonth += 100 - 12))

A: Or
(( yearmonth += ((yearmonth % 100) == 12)?(100 - 11):1 ))


text:
Q: Simple Image Metrics with PIL I want to process uploaded photos with PIL and determine some "soft" image metrics like:

*

*is the image contrastful or dull?

*colorful or monochrome?

*bright or dark?

*is the image warm or cold (regarding light temperature)?

*is there a dominant hue?

the metrics should be measured in a rating-style, e.g. colorful++++ for a very colorful photo, colorful+ for a rather monochrome image.
I already noticed PIL's ImageStat Module, that calculates some interesting values for my metrics, e.g. RMS of histogram etc. However, this module is rather poorly documented, so I'm looking for more concrete algorithms to determine these metrics.

A: I don't think there are methods that give you a metric exactly for what you want, but the methods that it has, like RMS, takes you a long way there. To do things with color, you can split the image into one layer per color, and get the RMS on each layer, which tells you some of the things you want to know. You can also convert the image in different ways so that you only retain color information, etc.


text:
Q: How do I import SoapUI project in Postman? Can anyone help me in importing the SoapUI project in postman?
I have imported wsdls in SoapUI. So I need a way to get the wsdls from SoapUi to postman or if there is a way to use wsdl files in postman directly it will help too.
Thanks in advance.

A: From the previous comment, you can export and import collections and projects between Postman and SoapUI but only REST projects.
Exporting to Swagger in SoapUI will result in an error for a SOAP projects.
"Importing SoapUI projects into Postman", referenced in the previous post, is referring to a REST Project not a SOAP project.

A: Those two tools do not have a common format they can export to. The only common format between them is Swagger, which either of them can import. However, neither of them is able to export into this format.
Further, Postman is made with REST services in mind. As such, it cannot do anything with a WSDL. If you definitely must use Postman to test SOAP services, you will have to map all your calls as a POST call, unfortunately, all manually.
Updates:
I did little more digging. It seems that SoapUI is able to import a Postman collection.
And further, SoapUI is able to export a Swagger description: Project > Export Swagger.
Personally I have not tried either of these options.

A: After so much frustration, I installed a different tool called "SoapUI" by the SmartBear. IT worked very easily. I just gave it my wsdl url and it loaded all the end points.

A: The latest version of Postman (8.4.0) supports importing WSDL files as Postman Collections.

A: Osiris is correct. Now we can at least import interfaces from SoapUI:

*

*open SoapUI

*select interface you want to export

*in its context menu press "Export Definition" -> Save (it will be saved as wsdl and xsd files)

*open Postman -> Import -> select saved wsdl and xsd files


text:
Q: Get folder from page C# I have a question. I need to get a folder from user on the page and save hierarchy of folders' names to db. If I use IFormFile it takes only files, but I need exactly folders even if they are empty. How can I implement this?
This is form:
<form action="/Folders/Upload" method="post"
enctype="multipart/form-data">
    <input type="file" directory multiple>
    <input type="submit" value="Upload">
</form>

In controller I tried to get List<IFormFile> but it takes only files if they exist in folders and if there aren't any files it's Length is 0. But I need to get hierachy of folders(their names) even if there aren't any files. Can I somehow save the whole hierachy of folders or maybe take a zip from user?


text:
Q: put behaviours in correct class when drawing the UML class diagram this is a scenario of small office.
there is software projects and there is manager.
manager is responsible for managing those projects
manager can perform below actions

*

*create projects       //createProject()

*delete selected projects //deleteProjectById()

*edit the details of a selected project //updateProjectById()

*update his information //updateManagerInfo()

*add qualifications //addQualificationToManager()

*assign employees for s project //assignemployees()

*check project deadline//isProjectDeadlinExceed()
i want to model this scenario in uml class diagram
below there is manager,project classes with their attributes
manager class attributes
name
genaralInformation
educationalQualifications
salary

project class attributes
projectid
projectname
deadline
budget
assignedEmployeeList

to draw uml class diagram completely i need to place above methods(actions that manager can perform) among the manager class and project class
i,m sure following methods are belongs to manager class
because manager can only perform those actions and also those methods not involve changing state of project class attributes.
createProject()
deleteProjectById()
updateProjectById()
updateManagerInfo()
addQualificationToManager()

but i'm not sure where to put below methods?
assignemployees()
isProjectDeadlinExceed()

because above actions can perform manager and also above methods are work on attributes(state) of project class
where to put those methods ???

A: I think you are missing at least one abstraction, that is the set of all projects. Let's call this thing a ProjectPortfolio. Then I would perhaps go with this design (in java syntax):
public interface ProjectPortfolio {
    Project createProject(...);
    Project findById(...);
}

public interface Project {
    void delete();
    void update(...);
    void assignEmployees(...);
    boolean isDeadlineExceeded();
}

public interface Manager {
    void updateInfo(...);
    void addQualification(...);
}

It seems to me you are trying to put methods into the Manager, because the manager is the one doing them. Usually methods should be on the object that is being acted upon (the "subject" of the action).
So, for example, if you want delete() a project, that method should be (barring other requirements) on the Project object.
Therefore when you want to createProject(), you have to find a suitable "subject" where that operation makes sense.
Think about it this way: You are inside the application, you are surrounded by objects, which are your friends with whom you are trying to make the application work. So you should ask yourself: Who can I ask to help me?. For example for createProject() can I ask one of my Manager object friends? No, because those guys just represent some real-world people, they don't know how to create a project. And Project objects represent a single already created project. Therefore you have to write a new friend called ProjectPortfolio, who knows about all projects. :)

A:
The use case diagram shows your scenario in a user goal perspective, helping you to design your class system. It does not mean that every use case has to be mapped as method of the actor that fulfills the action ( even, the actor doesn't deserve a class!).
In my opinion,in your scenario, Manager calls methods in the Project class to fulfill his functional requirements. Making reference to the following class diagram

you can see that the functional requirements are satisfied. As an example,in this class system,  to add an employee to a project a manager has only to call a method in Project, choosing into a list of projects that he owns.


text:
Q: Create admin account by default in Spring boot I have a user entity:
User.java
@Entity
public class user {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@NotNull
@NotBlank
private String firstname;
...

When I am deploying the application the first time it will create this table in my database.
My question: is there any way to create an admin user with firstname together with the table user when it gets created?

A: i prefer  always to avoid sql script so i use CommandLineRunner interface.
this is an example using spring data, its not a working code :
@Component
public class CommandLineAppStartupRunner implements CommandLineRunner {
    @Autowired
    UserRepository userRepository;

    @Override
    public void run(String...args) throws Exception {
        User admin = new user(firstName);
        userRepository.save(admin);
    }
}

before the app starts this class will be executed.

A: This answer actually shows a better approach and should be the accepted one.

You can put something like this in src/main/resources/data.sql:
INSERT INTO users (firstname, password, enabled)
SELECT 'admin', 'secret', TRUE
WHERE NOT EXISTS (SELECT * FROM users WHERE firstname='admin');

Assuming you are using PostgreSQL for the database backend.
As I don't know the database schema you are using, you'll have to modify this query to match your schema, but it should give you the basic idea.
I think you don't even need to add any configuration for this to work as Spring will pick it up automatically and use it for database initialization if it's in the right directory.
According to another answer to a similar question, in Spring Boot 2.x you'll have to add the following piece of configuration for this to work:
spring.datasource.initialization-mode=always


text:
Q: Clash of Clans, Clan Castle- gold and elixir When you have the war gold and elixir storage in your clan castle, what happens when you collect it?
Like do you take all the gold and elixir your clan has won?
Or do you only collect the war and elixir you from which you have won from the war?
Sorry for the many questions, its just that I don't want to make a mistake and take all the resources if we share it as a clan. ><

A:
When you have the war gold and elixir storage in your clan castle, what happens when you collect it?

When you collect your war win bonus from your clan castle, it goes directly into your storage.

Do you only collect the war and elixir you from which you have won from the war?

No. War win bonuses can be accumulated over several wars, however: If you run out of space in your clan castle, any excess resource will be thrown away.
That's why it is recommended to claim your resources right after getting them (if your win always gives you close to your clan castle's capacity.

I don't want to make a mistake and take all the resources if we share it as a clan.

Don't worry - War win bonuses are awarded on a per player basis. For example, a high-up player defeating other people with Town Hall (let's say 8) will recieve more war loot bonus than those defeating Town Hall 6 players. You can't steal another player's War Win bonus (if they have some unclaimed) unless you looted it from a multiplayer battle.
Your war loot bonus is determined by the matches that you win, regardless if you only scored one star. As long as it's a defeat (scoring more than 1 star), you'll receive the loot bonus for the village you've won it from.
Lastly, even if 10 players defeat the same village, they'll all recieve the war win bonus for that village (if they win the war, otherwise - the standard 40%). War win bonus works like your league bonus, except you only get to claim the win bonus AFTER the war has been done. All loot from previous wars will be avaliable for collection (even when in another war)


text:
Q: Getting Empty Object in postman i get empty object and 200 response when i try to get the movies which are bought,
i can buy the movie but can not show it
here is the repository function
   public async Task<IEnumerable<CartItem>> CartItems(int UserId)
        {
            return await (from cart in this.context.Cart
                          join cartItem in this.context.CartItem
                          on cart.Id equals cartItem.CartId
                          where cart.UserId == UserId
                          select new CartItem
                          {
                              Id = cartItem.Id,
                              MovieId = cartItem.MovieId,
                              mengde = cartItem.mengde,
                              CartId = cartItem.CartId,
                          }).ToListAsync();

        }

and the controller

        [HttpGet("CurrentUser")]
        public int GetLoggetInUserId()
        {
            int id = Convert.ToInt32(HttpContext.User.FindFirstValue("UserId"));
            return id;
        }

        [HttpGet("GetItems")]

        public async Task<ActionResult<IEnumerable<CartItemDTO>>> CartItems()
        {

            try
            {
                int userId = GetLoggetInUserId();
                // here we returned cartItem object
                var cartItems = await this.shoping.CartItems(userId);

                if (cartItems == null)
                {

                    return NoContent();
                }

                var movies = await this.repository.GetAll();

                if (movies == null)
                {
                    throw new Exception("No products exist in the system");
                }

                var UserCartItems = cartItems.ConvertToDto(movies);

                return Ok(UserCartItems);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "the GET call to /api/user fieled");
                return StatusCode(StatusCodes.Status500InternalServerError,
                    ex.Message);

            }

        }

and the interface
 public interface IShoping
    {

        Task<CartItem> AddItem(CartItemToAddDto cartItemToAddDto);
        Task<CartItem> DeleteItem(int Id);
        Task<CartItem> GetItem(int id);
        Task<IEnumerable<CartItem>> CartItems(int UserId);
        Task<CartItem> UpdateItem(int Id, CartItemMengdeUpdate cartItemMengdeUpdate);

the buy function works but when i try to get all the bought movies i get an empty object
(https://i.stack.imgur.com/boAYK.png)


text:
Q: SQLServer 2014 stored procedure to copy data based on a unique ID not existing in destination I have two tables, an initial datafeed table and a destination table called livedata.
I'd like to write a stored procedure to copy records from the datafeed table to the livedata table if the livedata table doesn't contain the record already.
The datafeed table has a unique identifier called IDColumn which I have created in the livedata table too.
Any help much appreciated.
Thanks
Mark

A: If the columns are the same, then something simple like this will do:
create procedure dbo.livedata_import_datafeed as
begin;
  set nocount, xact_abort on;
    insert into dbo.livedata
    select *
    from datafeed d
    where not exists (
      select 1
      from livedata l
      where l.IDColumn = d.IDColumn
      )
end;
go


text:
Q: Build a array of div's id using each DIV inside section I'm trying to get the ID of each DIV inside this HTML code

        ...

        ...

        ...

    <button type="button" class="create-variation" id="create-variation" style="">Crear variaciones</button>

So I made this:
function getDivId(div) {
    var inputValues = [];
    $("#" + div + ' > div').each(function() {
        inputValues.push($(this).val());
    })
    return inputValues;
}

And I call here:
$('#choices').on("click", "#create-variation", function(e) {
    var parent_id = $(this).closest("section").attr("id");
    var element = getDivId(parent_id);

    iterateChoices("", element[0], element.slice(1), 0);
});

I need to build something like this:
var element = new Array($('#talla_choice_24 input:text'), $('#color_choice_25 input:text'), $('#sport_choice_26 input:text'));

But I get this error:

Uncaught TypeError: Object  has no method 'each'

What is wrong?
UPDATE
This is the code for iterateChoices() function:
function iterateChoices(row, element, choices, counter) {
    if ($.isArray(choices) && choices.length > 0) {
        element.each(function(index, item) {
            if (counter == 0)
                row = '<input type="text" required="required" value="" name="pupc[]" /><input type="text" required="required" value="" name="pprice[]" /><input type="text" required="required" value="" name="pqty[]" />';

            iterateChoices(row + '<input value="' + item.value + '">', choices[0], choices.slice(1), counter + 1);
        });
    } else {
        html_temp = "";
        $.each(element, function(index, item) {
            html_temp += row + '<input value="' + item.value + '">
';
        });
        html += html_temp;
    }
}

I also made some changes at this code:
function getDivId(div) {
    var inputValues = [];
    $("#" + div + ' > div').each(function() {
        inputValues.push("#" + $(this).attr('id') + ' input:text');
    });

    return inputValues;
}

And now the error change to this:

Uncaught TypeError: Object #talla_choice_24 input:text has no method 'each'

UPDATE 2
I still continue change getDivId() function to build a array like this:
 var element = new Array($('#talla_choice_24 input:text'), $('#color_choice_25 input:text'), $('#number_choice_23 input:text'), $('#sport_choice_23 input:text'));

But can't get it since array values are constructed as strings, see below:
function getDivId(div) {
    var inputValues = [];
    $("#" + div + ' > div').each(function() {

        inputValues.push('$("#' + $(this).attr('id') + ' input:text")');
    });

    return inputValues;
}

I'm getting:
("$('#talla_choice_24 input:text')", "$('#color_choice_25 input:text')")

I think there is the problem

A: You are using the val method on a div element, which just returns an empty string. There is no each method on a string.

You don't need the id of each div to get the input elements inside them. This will get you the inputs in a single jQuery object:
var element = $(this).closest("section").find("> div input:text");

If you really need an array of separate jQuery objects, you can then do this:
element = element.map(function(){ return $(this); }).get();

A: var arr = [];
$("#create-variation").on('click', function(){
    $("#choices > div").each(function(a,b){
        arr.push($(this).text());
    });
});

A: After some headaches I realized how to fix the (my) error, here is the solution to all the problems:
function getDivId(div) {
    var inputValues = [];
    $("#" + div + ' > div').each(function() {
        inputValues.push($("#" + $(this).attr('id') + " input:text"));
    });

    return inputValues;
}