text:
Q: Website with Admins that can add/edit articles/pages Recently, we have launched the website for our Call of Duty clan. However, we would like admins to be able to log in on the page, and allow them to add or edit articles to the homepage or other pages, or edit pages like a member roster.
I'm not expecting very specific answers since this is quite vague i think, but i was wondering what kind of system we should be using for this. I myself have quite some experience with HTML and css, but less with PHP and JS. I can use them, but i don't have the experience to know what system to use for these kind of situations.

A: The term for what you're looking for is CMS, or Content Management System. There are a hojillion of these out there, and some of them even with free hosting. Here is a directory for php CMS:
http://php.opensourcecms.com/scripts/show.php?catid=1&cat=CMS%20/%20Portals
DotNetNuke is a popular Windows CMS. Here is a site with free DNN hosting:
http://www.dnn4free.com/
HTH.

A: it's easy to answer your question!
I would install Joomla - www.joomla.org. A lot of other clans for Call of Duty use it, and it's really user-friendly to install. (It's also free).
Joomla allows you and other people you choose to upload articles, edit them - all via the Admin section. No programming or PHP experience is necessary.  for install instructions, just search YouTube.com for "Install Joomla".
G'Luck!

A: There are a lot of engines out there. Joomla, Wordpress(blog+), Drupal, and etc. If you are looking to blog a lot I would suggest Wordpress.  Basically these are CMS (content management systems).

A: It has been mentioned, but I would like to throw in my support for wordpress. Especially if you don't have a ton of experience with web based applications, deployment with most hosting providers is extremely easy.


text:
Q: Javascript Regex array of matches not working properly I'm using the javascript match() function as follows
var str = "100% Scored";
var reg = "/\b(10|sales|100%)\b/i"
var res = str.match(reg);

But res is not getting '100%' value.  I tried changing the regex many ways but no success.

A: Create a regular expression literal with /…/, like this:
var reg = /\b(10|sales|100%)\b/i;

Note however, that \b will only match a position between 'word' characters, and % is not a word character, so this will not match the "100% Scored"
Try this pattern:
var str = "100% Scored";
var reg = /\b(10|sales|100%)(?!\w)/i;
var res = str.match(reg);
console.log(res);         // [ "100%", "100%" ]

A: use this pattern for taking out X% or XX% or XXX%:
var str = "100% Scored";
var reg = "^[0-9]{1,3}%"
var res = str.match(reg);

A: Try the below Regex
var reg = /\b(10|sales|100%)(?!\w)/i;

Working Fiddle

redpajama_set_name: RedPajamaStackExchange


text:
Q: jquery remove of prepended element not working Basically, I want to have two functions. The first prepends an element div which contains some ajax data and a button which can fire the close function. The first function does everything I want it to, except I'm having trouble applyin the onclick attribute on the  which will fire the remove function when clicked.
But independent of this, I haven't been able to get the remove function to work.
If you can help me do this better I would be grateful.
function displayCrRef(refPid, refFs, pidOfReferringP) {

    $.get("crRefParaExtract.php", {
        pid: refPid,
        fs: refFs
    }, function(data) {

        $("#pwrap_" + pidOfReferringP).prepend("
" + "Return to normal text" + data + "
");

    });
    var rmFxnParam = "'" + refPid + "'";
    $("#crossRefRemoveButton").attr("onclick", "removeCrossRef(" + rmFxnParam + ")");
    $("#" + pidOfReferringP).css({
        float: 'left',
        width: '425px'
    });
    $("#menu_" + pidOfReferringP).css({
        float: 'none',
        clear: 'both'
    });
   }

   function removeCrossRef(refPid) {
       $("#crRef_" + refPid).remove();

   }

A: Beginning an id with # is not valid. I believe you're confusing the id value with jQuery's CSS selectors.
[hashTag] + [ID of Element] = CSS ID Selector
This should work:
function displayCrRef(refPid, refFs, pidOfReferringP) {

    ...
    // Remove the hash tag here: id='crRef_" + refPid + "'
    $("#pwrap_" + pidOfReferringP).prepend("
" + "Return to normal text" + data + "
");
    ...

}

function removeCrossRef(refPid) {
    $("#crRef_" + refPid).remove();
}

Additional Information

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be
  followed by any number of letters, digits ([0-9]), hyphens ("-"),
  underscores ("_"), colons (":"), and periods (".").

Reference: http://www.w3.org/TR/html4/types.html

A: $("#crossRefRemoveButton").addEventListener('click',function(){
   removeCrossRef(rmFxnParam);
});


text:
Q: Julia: type stability using the base.ntuples function I recently started using Julia, and am at the moment struggling with some aspects of typing. I am trying to define a type TensorTrain (https://www.researchgate.net/profile/Ivan_Oseledets2/publication/220412263_Tensor-Train_Decomposition/links/5bbfb5c5299bf1004c5a56e3/Tensor-Train-Decomposition.pdf), but I cannot get one of the methods I define to be stable:
abstract type AbstractTensorTrain <: Any end

struct TensorTrain{T<:AbstractFloat} <: AbstractTensorTrain
    cores::Vector{Array{T,3}}
end

Base.size(t::TensorTrain, d::Int) = size(t.cores[d],2)
Base.size(t::TensorTrain) = ntuple(d->size(t,d),length(t.cores))

However if I run:
@code_warntype TensorTrain([rand(2,3,4)]);

I get:
Variables
  #self#::Core.Compiler.Const(size, false)
  t::TensorTrain{Float64}
  #19::var"#19#20"{TensorTrain{Float64}}
  d::Int64

Body::Tuple{Vararg{Int64,N} where N}
1 ─ %1 = Base.getproperty(t, :cores)::Array{Array{Float64,3},1}
│        (d = Main.length(%1))
│   %3 = Main.:(var"#19#20")::Core.Compiler.Const(var"#19#20", false)
│   %4 = Core.typeof(t)::Core.Compiler.Const(TensorTrain{Float64}, false)
│   %5 = Core.apply_type(%3, %4)::Core.Compiler.Const(var"#19#20"{TensorTrain{Float64}}, false)
│        (#19 = %new(%5, t))
│   %7 = #19::var"#19#20"{TensorTrain{Float64}}
│   %8 = Main.ntuple(%7, d)::Tuple{Vararg{Int64,N} where N}
└──      return %8

Why is this?

A: Because d = length(t.cores) is only known at runtime, so there's no way ntuple could statically infer the N parameter.  There is a method that takes a Val, which is useful for type stability in other cases, but it does not change anything here -- the d is still dynamic.
You could make cores an NTuple or StaticVector, though (which are really the same things), then this will work.  But do check whether it really makes a difference, before delving into type-level programming.


text:
Q: How to get count of records month-wise from mysql table? I have a mysql table points like this
id | points | orderid | date
1  | 10     | 1234    | 2014-01-14
2  | 20     | 4321    | 2014-02-04
3  | 10     | 1234    | 2014-01-13

I want to get count of records for unique orderids
like if i want to fech total records for month of jan then result will be
1 not 2 because i need to fetch records for unique orderids

A: Use the DISTINCT modifier in the COUNT() function.
SELECT YEAR(date) AS y, MONTH(date) AS m, COUNT(DISTINCT orderid)
FROM yourTable
GROUP BY y, m

A: SELECT MONTHNAME(date_reg) M, YEAR(date_reg) Y, COUNT(MONTHNAME(date_reg)) T
FROM users
WHERE date_reg BETWEEN DATE_ADD(DATE_SUB(DATE_SUB(LAST_DAY(NOW()), INTERVAL
   DAY(LAST_DAY(NOW())) DAY), INTERVAL 5 MONTH), INTERVAL 1 DAY) AND
   DATE_SUB(LAST_DAY(NOW()), INTERVAL DAY(LAST_DAY(NOW())) DAY)
GROUP BY M
ORDER BY Y, M DESC;

A: You can use substr function of MySQL to cut down the complete date string into year and month and group the resulting string.
select substr(createdTime,1,7) as month,COUNT(1) from TABLENAME where {CONDITION} group by month order by 1;


text:
Q: How to do a manual injection in the angular jasmine In the app.module.ts, I have CustomInterceptor like below.
App.module.ts
.
.
Provider: [{
  provide: HTTP_INTERCEPTORS,
  useClass: CustomInterceptor,
  Multi:true
 }],
.
.

Test.component.spec.ts
  TestBed.configureTestingModule([{
   provider: {
     provide: HTTP_INTERCEPTORS,
     useClass: CustomInterceptor,
     multi:true
   }
  }];

So this is what I tried;
     BeforeEach(inject([{
       provide: HTTP_INTERCEPTORS,
        useClass: CustomInterceptor,
        multi:true
      }],(interceptor)=>{
         interceptor =interceptor;
       })));

it('interceptor is created', () => {
  Expect(interceptor).toBeTrusty(); //error [[object] [object]]
});

Is this the Correct way to inject custom token into test class?
ANSWER:
Just found my own solution. The whole injectable and injector concepts and how it are used are new to me, and finally I realise what is wrong with my code.
Instead of looking at {provide: xxx, --:yyy}, I should have looked at the Injector. Reading
Before(inject([Injector, (injector: Injector) => {
 let cInterceptor = injector.get(HTTP_INTERCEPTORS); // find the token service in the provider register
 interceptor = cInterceptor.find(ci => ci instanceOf CustomInterceptor) as CustomInterceptor; // because of multiple, it stores as array and then convert it to the class we need it
});


text:
Q: Reading a CSV with line breaks and nested quotes How do you read a csv into c# with line breaks and nested quotes.
At first I was looking for paired quoted to denote a value, but you can have nested quotes!
How is excel able to do it?

A: Don't try to reinvent the wheel:

*

*A Fast CSV Reader

A: You can try also this one!
http://www.csvreader.com/


text:
Q: Stackdriver unable to determine collectd endpoint All my hosts stopped reporting stats to collectd google gateway. This is due to some internal change on google side.

In logs files I see this:
Jan 13 08:52:36 ign-rpt01 systemd[1]: Stopping LSB: start and stop Stackdriver Agent...
Jan 13 08:52:36 ign-rpt01 stackdriver-agent[10768]: mesg: ttyname failed: Inappropriate ioctl for device
Jan 13 08:52:36 ign-rpt01 stackdriver-agent[10768]:  * Stopping Stackdriver metrics collection agent stackdriver-agent
Jan 13 08:52:37 ign-rpt01 stackdriver-agent[10768]:    ...done.
Jan 13 08:52:37 ign-rpt01 systemd[1]: Stopped LSB: start and stop Stackdriver Agent.
Jan 13 08:52:37 ign-rpt01 systemd[1]: Starting LSB: start and stop Stackdriver Agent...
Jan 13 08:52:37 ign-rpt01 stackdriver-agent[10794]: mesg: ttyname failed: Inappropriate ioctl for device
Jan 13 08:52:37 ign-rpt01 stackdriver-agent[10794]:  * Starting Stackdriver metrics collection agent stackdriver-agent
Jan 13 08:52:38 ign-rpt01 stackdriver-agent[10794]: Unable to determine collectd endpoint!
Jan 13 08:52:38 ign-rpt01 stackdriver-agent[10794]:  * not starting, configuration error
Jan 13 08:52:38 ign-rpt01 stackdriver-agent[10794]:    ...fail!
Jan 13 08:52:38 ign-rpt01 systemd[1]: Started LSB: start and stop Stackdriver Agent.
Jan 13 08:53:16 ign-rpt01 extractd[10869]: Error sending processes data: Stackdriver gateway replied with a 401: <title>HTTP 401: Unauthorized (Invalid API key)</title>HTTP 401: Unauthorized (Invalid API key)
Jan 13 08:54:16 ign-rpt01 extractd[10903]: Error sending processes data: Stackdriver gateway replied with a 401: <title>HTTP 401: Unauthorized (Invalid API key)</title>HTTP 401: Unauthorized (Invalid API key)
Jan 13 08:55:16 ign-rpt01 extractd[10947]: Error sending processes data: Stackdriver gateway replied with a 401: <title>HTTP 401: Unauthorized (Invalid API key)</title>HTTP 401: Unauthorized (Invalid API key)

A: When I go to stackdriver account settings:
The following instances are using a deprecated configuration of the monitoring agent. Alerting policies referencing metrics from these agents do not work as intended and are currently unsupported. Dashboards using metrics from these agents are also unsupported and will soon stop working.

Please update your monitoring agent. Learn more
Okay, it turns out that now only --write-gcm is supported now.
TL;DR version
Just run this:
curl -O "https://repo.stackdriver.com/stack-install.sh"
sudo bash stack-install.sh --write-gcm

And hey, my stats are starting to come in again:


text:
Q: Fluent NHibernate atutomapping, simple question, extra field being added for foreign key relationships Im sorry if I don't make any sense my brain is fried right now. I just started programming in NHibernate, decided to move to Fluent Nhibernate because of the automapping but I'm having a little trouble, here is the relation it should have:

Here is the relation Fluent Nhibernate's automapping made, notice that MemberId is added to the table:

I'm guessing this is because the relations are set to inverse in my conventions. I needed to make the relationships inverse() or the cascades didn't work. Here are my conventions:
public class HasManyConvention : IHasManyConvention
    {
        public void Apply(FluentNHibernate.Conventions.Instances.IOneToManyCollectionInstance instance)
        {
            instance.Key.Column(instance.EntityType.Name + "ID");
            //instance.Inverse();
            if (instance.Member.GetCustomAttributes(typeof(CascadeAttribute), false).Length <= 0)
            {
                instance.Cascade.None();
                return;
            }
            var cascadeOption = (CascadeAttribute)instance.Member.GetCustomAttributes(typeof(CascadeAttribute), false)[0];
            switch (cascadeOption.CascadeOption)
            {
                case Enums.CascadeOptions.All:
                    instance.Cascade.All();
                    break;

                case Enums.CascadeOptions.AllDeleteOrphan:
                    instance.Cascade.AllDeleteOrphan();
                    break;

                case Enums.CascadeOptions.Delete:
                    instance.Cascade.All();
                    break;

                case Enums.CascadeOptions.DeleteOrphan:
                    instance.Cascade.DeleteOrphan();
                    break;

                case Enums.CascadeOptions.None:
                    instance.Cascade.None();
                    break;

                case Enums.CascadeOptions.SaveUpdate:
                    instance.Cascade.SaveUpdate();
                    break;
            }

        }
    }

 public class ReferenceConvention : IReferenceConvention
    {
        public void Apply(FluentNHibernate.Conventions.Instances.IManyToOneInstance instance)
        {
            instance.Column(instance.Property.Name + "Fk");
            if (Attribute.IsDefined(instance.Property.PropertyType.Assembly, typeof(DomainSignatureAttribute)))
                instance.UniqueKey("DomainSignature");
            else
                instance.Index(instance.Property.Name + "Index");
        }
    }

And my two entities:
public class Member : Entity
    {
        public Member()
        {

            Mail = new List<Mail>();
        }

        [Cascade(Enums.CascadeOptions.All)]
        public virtual IList<Mail> Mail
        {
            get; set;
        }

    }

public class Mail : Entity
    {

        public virtual Member Receiver
        {
            get; set;
        }

        public virtual Member Sender
        {
            get; set;
        }

        public virtual string Subject
        {
            get;
            set;
        }

        public virtual string Body
        {
            get; set;
        }
    }

Why does fluent nhibernate map MemberId when it's obvious that Receiver and Sender are foreign keys to the member table?

A: Because Member.Mail is mapped as one-to-many which results in a foreign key in Mail. Nobody ever said that 'Member.Mail' is an inverse relation and nobody ever said how the foreign key is called. So it creates a standard foreign key.


text:
Q: Android: Check network and real internet connectivity Below is the piece of Android code which works fine to check if network is connected or not.
public static boolean isNetworkAvailable(Context context)
{
    ConnectivityManager mConnectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    return (mConnectivityManager != null && mConnectivityManager.getActiveNetworkInfo().isConnectedOrConnecting()) ? true : false;
}

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

But having an  active network interface doesn't guarantee that a particular networked service is available.
A lot of time happens that we are connected to network but still not reachable to common internet network services, e.g. Google
Common scenario:

*

*Android device connected to a Wi-Fi, which turns out to be a private
network. So isNetworkAvailable will return that network is connected, but could
not be connected to any other service

*Some times the phone signal shows it is connected to service provider data plan. so network connectivity is true , but still cannot access Google/Yahoo.

One way is to check if "isNetworkAvailable" function returns TRUE, then run following code
HttpGet request = new HttpGet(url));
   HttpParams httpParameters = new BasicHttpParams();
   int timeoutConnection = 60000;
   HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
   int timeoutSocket = 60000;
   HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

   DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
   request.addHeader("Content-Type", "application/json");
   HttpResponse response = httpClient.execute(request);

   HttpEntity entity = response.getEntity();

     if (entity != null)
      {
         result = EntityUtils.toString(entity);
      }

   }
 catch (SocketException e)
  {
     return "Socket Exceptiopn:" + e.toString();
  }
 catch (Exception e)
  {
     return "General Execption:" + e.toString();
  }

But I think this is not an good way because it may consume lot of time
So is there any alternative efficient (in terms of time taken,speed) way ensure that we are connected to network as well as reachable to most common internet services ?

A: check this code... it worked for me :)
public static void isNetworkAvailable(final Handler handler, final int timeout) {

        // ask fo message '0' (not connected) or '1' (connected) on 'handler'
        // the answer must be send before before within the 'timeout' (in milliseconds)

        new Thread() {

            private boolean responded = false;

            @Override
            public void run() {

                // set 'responded' to TRUE if is able to connect with google mobile (responds fast)

                new Thread() {

                    @Override
                    public void run() {
                        HttpGet requestForTest = new HttpGet("http://m.google.com");
                        try {
                            new DefaultHttpClient().execute(requestForTest); // can last...
                            responded = true;
                        } catch (Exception e) {}
                    }

                }.start();

                try {
                    int waited = 0;
                    while(!responded && (waited < timeout)) {
                        sleep(100);
                        if(!responded ) {
                            waited += 100;
                        }
                    }
                }
                catch(InterruptedException e) {} // do nothing
                finally {
                    if (!responded) { handler.sendEmptyMessage(0); }
                    else { handler.sendEmptyMessage(1); }
                }

            }

        }.start();

}

Then, I define the handler:
Handler h = new Handler() {

    @Override
    public void handleMessage(Message msg) {

        if (msg.what != 1) { // code if not connected

        } else { // code if connected

        }

    }
};

and launch the test:
isNetworkAvailable(h,2000); // get the answser within 2000 ms

Code from Gilbou https://stackoverflow.com/a/5803489/2603719
I hope i can Help you

A: Issue #1:
Android device connected to a Wi-Fi, which turns out to be a private network.
So isNetworkAvailable will return that network is connected, but could not be connected to any other service.
Issue #2:
Sometimes the phone signal shows it is connected to service provider data plan. so network connectivity is true , but still cannot access google/yahoo.
I'm not sure about Issue #1 but I'm sure that following approach will solve Issue #2.

Ultimately, you will need to Monitor the change in Network connection,
Step 1:
Just register a BroadcastReceiver for following action
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
Step 2:
when you get callback on onReceive(Context context,Intent intent) method ,check for connectivity status.
i.e:
boolean isConnected = getIntent().getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY);
//apart from EXTRA_NO_CONNECTIVITY, there are other parameters also which will be useful to monitor
Reference:
Examples:
Working Example of Step1,Step2: how-to-monitor-network-connectivity-in-android
Android-getting-notified-of-connectivity-changes
Github: Example for network-detect-notify
Android Docs:
Connectivity Monitoring
Connectivity Manager
I hope it will be helpful !!

A: Use This code to check internet connection, it check all the internet connection over device. And Make Sure you have added Internet Permission in menifest.
        boolean flag=false;
        ConnectivityManager connectivity = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null)
        {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED)
                    {
                        flag=true;

                    }

        }
        if(flag==true)
        {
             Log.e("TAG","Internet Is Connected");
        }
        else
        {
              Log.e("TAG","Internet Is Not Connected");
        }


text:
Q: C++ layout of an object containing containers As someone with a lot of assembler language experience and old habits to lose, I recently did a project in C++ using a lot of the features that c++03 and c++11 have to offer (mostly the container classes, including some from Boost).  It was surprisingly easy - and I tried wherever I could to favor simplicity over premature optimization.  As we move into code review and performance testing I'm sure some of the old hands will have aneurisms at not seeing exactly how every byte is manipulated, so I want to have some advance ammunition.
I defined a class whose instance members contain several vectors and maps.  Not "pointers to" vectors and maps.  And I realized that I haven't got the slightest idea how much contiguous space my objects take up, or what the performance implications might be for frequently clearing and re-populating these containers.
What does such an object look like, once instantiated?

A: Formally, there aren't any constraints on the implementation
other than those specified in the standard, with regards to
interface and complexity.  Practically, most, if not all
implementations derive from the same code base, and are fairly
similar.
The basic implementation of vector is three pointers.  The
actual memory for the objects in the vector is dynamically
allocated.  Depending on how the vector was "grown", the dynamic
area may contain extra memory; the three pointers point to the
start of the memory, the byte after the last byte currently
used, and the byte after the last byte allocated.  Perhaps the
most significant aspect of the implementation is that it
separates allocation and initialization: the vector will, in
many cases, allocate more memory than is needed, without
constructing objects in it, and will only construct the objects
when needed.  In addition, when you remove objects, or clear the
vector, it will not free the memory; it will only destruct the
objects, and will change the pointer to the end of the used
memory to reflect this.  Later, when you insert objects, no
allocation will be needed.
When you add objects beyond the amount of allocated space,
vector will allocate a new, larger area; copy the objects into
it, then destruct the objects in the old space, and delete it.
Because of the complexity constrains, vector must grow the area
exponentially, by multiplying the size by some fixed constant
(1.5 and 2 are the most common factors), rather than by
incrementing it by some fixed amount.  The result is that if you
grow the vector from empty using push_back, there will not be
too many reallocations and copies; another result is that if you
grow the vector from empty, it can end up using almost twice as
much memory as necessary.  These issues can be avoided if you
preallocate using std::vector<>::reserve().
As for map, the complexity constraints and the fact that it must
be ordered mean that some sort of balanced tree must be used.
In all of the implementations I know, this is a classical
red-black tree: each entry is allocated separately, in a node
which contains two or three pointers, plus maybe a boolean, in
addition to the data.
I might add that the above applies to the optimized versions of
the containers.  The usual implementations, when not optimized,
will add additional pointers to link all iterators to the
container, so that they can be marked when the container does
something which would invalidate them, and so that they can do
bounds checking.
Finally: these classes are templates, so in practice, you have
access to the sources, and can look at them.  (Issues like
exception safety sometimes make the implementations less
straight forward than we might like, but the implementations
with g++ or VC++ aren't really that hard to understand.)

A: A map is a binary tree (of some variety, I believe it's customarily a Red-Black tree), so the map itself probably only contains a pointer and some housekeeping data (such as the number of elements).
As with any other binary tree, each node will then contain two or three pointers (two for "left & right" nodes, and perhaps one to the previous node above to avoid having to traverse the whole tree to find where the previous node(s) are).
In general, vector shouldn't be noticeably slower than a regular array, and certainly no worse than your own implementation of a variable size array using pointers.

A: A vector is a wrapper for an array. The vector class contains a pointer to a contiguous block of memory and knows its size somehow. When you clear a vector, it usually retains its old buffer (implementation-dependent) so that the next time you reuse it, there are less allocations. If you resize a vector above its current buffer size, it will have to allocate a new one. Reusing and clearing the same vectors to store objects is efficient. (std::string is similar). If you want to find out exactly how much a vector has allocated in its buffer, call the capacity function and multiply this by the size of the element type. You can call the reserve function to manually increase the buffer size, in expectation of the vector taking more elements shortly.
Maps are more complicated so I don't know. But if you need an associative container, you would have to use something complicated in C too, right?

A: Just wanted to add to the answers of others few things that I think are important.
Firstly, the default (in implementations I've seen) sizeof(std::vector<T>) is constant and made up of three pointers. Below is excerpt from GCC 4.7.2 STL header, the relevant parts:
template<typename _Tp, typename _Alloc>
struct _Vector_base
{
 ...
 struct _Vector_impl : public _Tp_alloc_type
 {
  pointer _M_start;
  pointer _M_finish;
  pointer _M_end_of_storage;
  ...
 };
 ...
 _Vector_impl _M_impl;
 ...
};

template<typename _Tp, typename _Alloc = std::allocator<_Tp> >
class vector : protected _Vector_base<_Tp, _Alloc>
{
 ...
};

That's where the three pointers come from. Their names are self-explanatory, I think. But there is also a base class - the allocator. Which takes me to my second point.
Secondly, std::vector< T, Allocator = std::allocator<T>> takes second template parameter that is a class that handles memory operations. It's through functions of this class vector does memory management. There is a default STL allocator std::allocator<T>>. It has no data-members, only functions such as allocate, destroy etc. It bases its memory handling around new/delete. But you can write your own allocator and supply it to the std::vector as second template parameter. It has to conform to certain rules, such as functions it provides etc, but how the memory management is done internally - it's up to you, as long as it does not violate logic of std::vector relies on. It might introduce some data-members that will add to the sizeof(std::vector) through the inheritance above. It also gives you the "control over each bit".

A: Basically, a vector is just a pointer to an array, along with its capacity (total allocated memory) and size (actually used elements):
struct vector {
    Item* elements;
    size_t capacity;
    size_t size;
};

Of course thanks to encapsulation all of this is well hidden and the users never get to handle the gory details (reallocation, calling constructors/destructors when needed, etc) directly.
As to your performance questions regarding clearing, it depends how you clear the vector:

*

*Swapping it with a temporary empty vector (the usual idiom) will delete the old array: std::vector<int>().swap(myVector);

*Using clear() or resize(0) will erase all the items and keep the allocated memory and capacity unchanged.

If you are concerned about efficiency, IMHO the main point to consider is to call reserve() in advance (if you can) in order to pre-allocate the array and avoid useless reallocations and copies (or moves with C++11). When adding a lot of items to a vector, this can make a big difference (as we all know, dynamic allocation is very costly so reducing it can give a big performance boost).
There is a lot more to say about this, but I believe I covered the essential details. Don't hesitate to ask if you need more information on a particular point.

Concerning maps, they are usually implemented using red-black trees. But the standard doesn't mandate this, it only gives functional and complexity requirements so any other data structure that fits the bill is good to go. I have to admit, I don't know how RB-trees are implemented but I guess that, again, a map contains at least a pointer and a size.
And of course, each and every container type is different (eg. unordered maps are usually hash tables).


text:
Q: Building height adjustable desk I'm building a memory preset control panel for my adjustable height desk.
I have an electric desk running with a 3A/24V motor with an up/down switch and SMPS.
To add the memory functionality, I am planning to buy a Pi Pico module and a 3A motor driver circuit.

*

*Will this setup work? Are there any redundancies in my setup?

*I'm planning to program the Pi Pico to move motor at determined inches per second with a determined volt and current. Will this work? (What will happen if the load/weight on the table increases? Will this logic still work?)

A: While voltage to the motor will be constant, if you want to maintain a specific speed, the current delivered to the motor will vary based on the weight of the desk.
How will you be ensuring the motor's speed? You will likely want an encoder in a feedback loop with some sort of PID control. This may be overengineering, but would ensure a constant motor speed regardless of external variables.


text:
Q: call two procedures in select query? How to call two procedures in a select query
e.g.:
SELECT sp_get_input_xml (:in_request_oid,
                                    :in_contract_oid,
                                    :in_contract_type,
                                    :out_input_xml
                                   ),
       sp_get_output_xml (:in_request_oid,
                                     :in_contract_oid,
                                     :in_contract_type,
                                     :out_output_xml
                                    )
  FROM DUAL;

What's the correct way to call two procedures using select statement?

A: Looks like oracle. You can't call PROCEDURES from a SQL query, you can only call FUNCTIONS. If these are functions, that is perfectly acceptable. If you are procedures you'll need to use a PL/SQL block to call them.


text:
Q: Add sound on hover to each item of menu without a pause As I said I've created a menu which displays sound when I hover it. Code which I use is connected with a short pause before playing sound after hovering another item of the menu. How can I play it simultaneously, I mean, how can I remove the pause effect?

$(document).ready(function() {
  var beepOne = $("#beep-one")[0];
  $("#menu-glowne a")
    .mouseenter(function() {
      beepOne.pause();
      beepOne.play();
    });

});
<audio id="beep-one" controls="controls" preload="auto">
  <source src="http://localhost/wp-content/uploads/2016/04/Click2-Sebastian-759472264.mp3"></source>
  <source src="http://localhost/wp-content/uploads/2016/04/Click2-Sebastian-759472264.wav"></source>
</audio>

One

Two

Three

A: Replace the pause with setTimeOut, or maybe jQuery .delay(). Example with 300ms timeout:
$(document).ready(function() {
  var beepOne = $("#beep-one")[0];
  $("#menu-glowne a")
    .mouseenter(function() {
      setTimeout(function() {
        beepOne.play();
      }, 300);
    });
});

I do not know if a new sound cancels out the previous one.
Also, as commented, playing sound unannounced is a bad user experience. You better have it disabled by default and ask the user, or let them enable it via a checkbox or something.


text:
Q: ActiveRecord query that groups by ID and sums rows My Postgresql DB has this structure:
TABLE Orders
id (string)
userId (string)
prodId (string)
value (integer)

This is an example of data:
id      userId      prodId    value
1       a@a.aaa     prod1     5
2       b@b.bbb     prod1     -1
3       a@a.aaa     prod1     -4
4       a@a.aaa     prod2     9

I want to do a query from ActiveRecord that sums all the values for a specific userId, so the query for (a@a.aaa) would return a LIST like this:
prod1    1
prod2    9

My first approach is this one, but it doesn't work:
orderList = Orders.select("SUM(orders.amount) AS num_prods").where((:userId => HERE_USER_ID).group(:prodId)

EDIT: rephrased thanks to feedback

A: Order.where(userId: id).group(:prodId).sum(:value) # replace `:id` with your value

This should give you a hash, like so
{1=>10, 2=>20, 5=>20}

the keys 1,2,5 represent the product id, and the values 10,20,20 represent the sum values.


text:
Q: Getting object properties that start with a number I've got an object where one of the properties starts with a number. I've read that this was allowed, but I'm getting this error:

SyntaxError: identifier starts immediately after numeric literal

var stats = {"LOAD_AVG":{"1_MIN":0.08,"5_MIN":0.08,"15_MIN":0.08},"COUNTS":{"TOTAL":888,"RUNNING":1,"SLEEPING":887,"STOPPED":0,"ZOMBIE":0},"CPU":{"USER_CPU_TIME":8.9,"SYSTEM_CPU_TIME":2.4,"NICE_CPU_TIME":0,"IO_WAIT_TIME":1,"HARD_TIME":0,"SOFT_TIME":0.1,"STEAL_TIME":0},"MEMORY":{"PHYSICAL":{"TOTAL":"3921.98mb","IN_USE":"3682.652mb (93.9%)","AVAILABLE":"239.328mb (6.1%)","BUFFERS":"266.492mb (6.8%)"},"SWAP":{"TOTAL":"4194.296mb","IN_USE":"64.264mb (1.5%)","AVAILABLE":"4130.032mb (98.5%)","CACHE":"1191.328mb (28.4%)"}}};

//works fine
window.alert(stats.COUNTS.TOTAL);

//doesn't work
window.alert(stats.LOAD_AVG.1_MIN);

Here's a fiddle.
How can I access the properties that begin with a number without rewriting the PHP that generated it?

A: You can use bracket access for properties that aren't valid JavaScript identifiers, that goes for property names with spaces or other language symbols like +, *
window.alert(stats.LOAD_AVG["1_MIN"]);

You can use bracket access anywhere really
window.alert(stats["COUNTS"]["TOTAL"]);


text:
Q: gxt GridInlineEditing doesn't notify data change in ListStore when the user completeEdit Actually I am using GWT with gxt (3.1) framework. I want to create an editable grid.
So I write the code :
List<ColumnConfig<String[], ?>> l = createColumnList(cols);

gridDataDisplay = new Grid<String[]>(store, new ColumnModel<String[]>(l));

int indice = 0;
final GridEditing<String[]> editing = new GridInlineEditing<String[]>(gridDataDisplay);
for(ColumnConfig<String[], ?> columnConfig : l) {
    if (!notEditable.contains(indice)) {
        ColumnConfig<String[], String> tempColumnConfig = (ColumnConfig<String[], String>) columnConfig;
        editing.addEditor(tempColumnConfig, new TextField());
     }
     indice++;

 }

So I follow the tutorial Grid Editing.
With the code below, I can modify my data by click on the column cell. But when validate : the change don't appear on my table. The Grid dislay the old value until call store.commitChanges();
Thank you in advance for your help.

A: Finally, I found out what is the problem. I guess it will help other people.
When, I created my ListStore, I use a keyProvider an integer that I increment every time I add a new record.
Apparently, the key keyProvider must use only the model attribute.


text:
Q: Grouping column data in Pandas Dataframes I have a Panda data frame (df) with many columns. For the sake of simplicity, I am posting three columns with dummy data here.
Timestamp    Source    Length
0            1              5
1            1              5
2            1              5
3            2              5
4            2              5
5            3              5
6            1              5
7            3              5
8            2              5
9            1              5

Using Panda functions, First I set timestamp as index of the df.
index = pd.DatetimeIndex(data[data.columns[1]]*10**9) # Convert timestamp
df = df.set_index(index) # Set Timestamp as index

Next I can use groupby and pd.TimeGrouper functions to group the data into 5 seconds bins and compute cumulative length for each bin as following:
df_length = data[data.columns[5]].groupby(pd.TimeGrouper('5S')).sum()

So the df_length dataframe should look like:
Timestamp     Length
0             25
5             25

Now the problem is: "I want to get the same bins of 5 seconds, but ant to compute the cumulative length for each source (1,2 and 3) in separate columns in the following format:
Timestamp    1     2     3
0            15    10    0
5            10    5     10

I think I can use df.groupby with some conditions to get it. But confused and tired now :(

Appreciate solution using panda functions only.

A: You can add new column for groupby Source for MultiIndex DataFrame and then reshape by unstack last level of MultiIndex for columns:
print (df[df.columns[2]].groupby([pd.TimeGrouper('5S'), df['Source']]).sum())
Timestamp            Source
1970-01-01 00:00:00  1         15
                     2         10
1970-01-01 00:00:05  1         10
                     2          5
                     3         10
Name: Length, dtype: int64

df1 = df[df.columns[2]].groupby([pd.TimeGrouper('5S'), df['Source']])
                       .sum()
                       .unstack(fill_value=0)
print (df1)
Source                1   2   3
Timestamp
1970-01-01 00:00:00  15  10   0
1970-01-01 00:00:05  10   5  10


text:
Q: Google Analytics API - how do I get access tokens without being an Admin I'm very new to using APIs and I'm struggling to figure out the authentication. With my email I can log in to a corporate analytics page and view the information. My account is only at a 'user' level. How do I get access tokens so I can scrape the data from the page using the Google API? Do I need the admins of the page to get these tokens? I tried using the generate access token but I don't know the service account email. Any advice would be appreciated because I'm so confused.

A: Answer:  how do I get access tokens without being an Admin
As long as your personal account has read access you can use Oauht2 to authorize your application and then be able to access the data that way you do not need to be admin.
All your other questions

How do I get access tokens so I can scrape the data from the page using the Google API?

First off if you use Oauth2 in your application and login with your own user you you will be able to use the Google Analytics api as you have read access thats all you need for the Google analytics api in order to request data.

Do I need the admins of the page to get these tokens?

No anyone with read access can authorize an application to access the google analytics api.

I tried using the generate access token but I don't know the service account email.

Service accounts are completely different than normal Oauth2.  A service account is a dummy user which needs to be preauthorized to access the data it has nothing to do with your personal access.  To preauthorize a service account to access the google analytics api you will need to have admin access to the google analytics account and take the service ac count email address and add it as a user on the google analytics account.  It will then have access to read the data.

Any advice would be appreciated because I'm so confused.

Decide if your application should be allowing users to login to it and access the data on their own google analytics accounts.  If so then you should be using Oauth2 and not a service account.
If you are only trying to access this single google analytics account then you should be using a service account.  However you will need to contact the admin to have them grant your service account access to the data.


text:
Q: sql server query outer join where issue I have 3 tables: Post, User and Favorites
Post
----------
PostId
Nombre
UserId
Banned

User
----------
UserId
UserName
Info

Favorites
-----------
PostId
UserId

I'm trying to get all posts and telling if the posts are favourites or not, so if a post isn't among favourites, it will appear on the query but favourite flag will be false.
this is my query:
SELECT
 p.Nombre as title,
 CASE ISNULL(f.PostId,0) WHEN 0 THEN 'false' ELSE 'true' END as favorito
 FROM Post p
 inner join User u on p.UserId = u.UserId
 left outer join Favorite f on p.PostId = f.PostId
 where
 p.Banned = 0

and it returns everything, and tells if there is a record in favorites, but when I add the filter on where section
 and f.UsuarioId = 4

only returns the posts the user likes. Shouldn't be when using left outer join or full outer join that if a record from secondary table doesn't exist should return the records from main table anyways?
¿How can I return all post using filter on secondary table? thanks!

A: Since you have filtered on f.UsuarioId = 4, that effectively converts the LEFT OUTER JOIN into an INNER JOIN by requiring that the Favorite have a record of a specific value. To still return all those with no related Favorite, you must test for a NULL in that table:
SELECT
 p.Nombre as title,
 CASE ISNULL(f.PostId,0) WHEN 0 THEN 'false' ELSE 'true' END as favorito
FROM
  Post p
  INNER JOINUser u ON p.UserId = u.UserId
  LEFT OUTER JOIN Favorite f ON p.PostId = f.PostId
WHERE
 p.Banned = 0
 -- Return either those related Favorite records for UsuarioId = 4 or the NULLs
 -- meaning a related record does not exist
 AND (f.UsuarioId = 4 OR f.UsuarioId IS NULL)


text:
Q: how to sort aggregate - Mongodb db.getCollection('shows').aggregate([
                     { $match: { _id: ObjectId("5d622cecbbe890f60ccd1ca4") } },

                     {  $lookup: { from: "episode", // collection name in db
                                   localField: "_id",
                                   foreignField: "show_id",
                                   as: "episode"
                                   }
                     },
                     { $sort: { 'episode._id': 1 } }
                   ])

So the below works fine however it seems that the sort is not sorting the collection episode in the correct order. It is still putting it oldest to newest when I want to have it newest to oldest.
I am wondering how this is done?

A: You can use  below aggregation
db.getCollection("shows").aggregate([
  { "$match": { "_id": ObjectId("5d622cecbbe890f60ccd1ca4") } },
  { "$lookup": {
    "from": "episode",
    "let": { "episodeId": "$_id" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": ["$show_id", "$$episodeId"] }}},
      { "$sort": { "_id": 1 }}
    ],
    "as": "episode"
  }}
])


text:
Q: Creating and Deserialize graph.microsoft.com objects We are using graph.microsoft.com to integrate our .NET application with Office365. For each object like event and we are now creating our own classes. Can we automatically create the classes?

A: You can create your own classes for all of the type of graph.microsoft.com but this means you have to keep track of changes yourself and for the complex types this is quite some work. Better to use the Microsoft.Graph SDK for .NET:
https://www.nuget.org/packages/Microsoft.Graph
For .NET the SDK is at 1.0. For other platform you can find status at: https://graph.microsoft.io/en-us/code-samples-and-sdks


text:
Q: Using md5 secured even its more difficult
Possible Duplicate:
Secure hash and salt for PHP passwords

I saw someone coding a password hash like this,
md5(uniqid(mt_rand('password', 15), true));

is that a secured way to do this? is that even worked out?

A: Not only is that not secure, it doesn't even work.
mt_rand takes 2 parameters, a min value and a max value.
mt_rand('password', 15)

This converts 'password' to an int (0), then returns a random number between 0 and 15.
uniqid(mt_rand('password', 15), true)

This then generates a unique ID, and prepends the random number from the previous step to it: calculating something like this:
144ffb22886d58e1.82100749

That string is then md5'd.
As you may be able to see, this code is 100% useless.  The original password is converted to 0 and lost forever, so all you're doing is hashing random numbers, which is pointless.  Now that you have your hash, there is no way to verify it again.  Since the password is converted, whatever the user enters doesn't matter.
So, no, this code is not secure, do not use it.
Personally, I use the phpass library.  It's secure, and simple to use.

A: To be honest I wouldn't even use md5 as a hashing algorithm for storing passwords.  I would look into using something like bcrypt. Also I don't even get how your example would work, but in any case if you want to secure it then stay away from md5, sha1 at the minimum and learn from others mistakes and use a salt.

A: No it isn't a safe way. It is crackable and, in your example, it is not repeatable. You would have to store the random value long with the hash itself. If th DB is compromised, then it becomes extremely simple to bruteforce the hash.
You should know that MD5 and SHA1 are two of the weakest hashing algorithms, that are available in PHP.
Much better is to use crypt() function, with CRYPT_BLOWFISH or PBKDF2.
update
Also, as PeeHaa mentioned, it does not work. The mt_rand('password', 15) will cause Warning: mt_rand() expects parameter 1 to be long, string given on line X.


text:
Q: unable to process a function inside a view using navigation bar I'm making a website using django and i have navigation bar that has a few items when i click on another item which is "delete" I am not able to see the page i intended to see
presently the 'insert' tab is my default tab and if i want to see the other link using delete tab i am not able
the views file is like this
    def home(request):
    form=insert()
    form1=insert()
    if request.method=="POST" and 'b1' in request.POST:
        form=insert(request.POST)
        if form.is_valid():
            form.save()
            return render(request,'employee/form.html')
    if request.method=="POST" and 'b2' in request.POST:
        allobjs=emp.objects.all()
        return render(request,'employee/form.html',{'form1':allobjs})
    if request.method=="POST" and 'b3' in request.POST:

        allobjs=emp.objects.all().delete()
       #return render(request,'employee/form.html',{'form1':allobjs})

    return render(request,'employee/form.html',{'forms':form,'form1':form1})
    def dele(request):
       return render(request,'employee/emp.html')

my code for navigation bar is

        Insert Record

        Delete Record

        Update Records

        Assign Duties

          View The duties

my app which is called employee has url.py like this
    urlpatterns = [
    path('',views.home,name='employee-insert'),
    path('',views.dele,name='employee-delete'),]

A: Make sure you import the view dele to the url, try to keep your action url like:
action={% url 'employee-dele' %}


text:
Q: Disabling dates based on first date picker I have two date pickers. When I select certain date on 1st date picker then based on that selected date I need to disable 30 days for next DatePicker

A: If I understood your question, this is your answer
I have edited Satpal sir's answer
    jsfiddle
startDate:
<input type="text" id="startDate" />
<br>targetDate:
<input type="text" id="targetDate" />

$(document).ready(function () {
    $("#startDate").datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: "dd-M-yy",
        minDate: 0,
        showMonthAfterYear: true,
        onClose: function () {
            $(this).toggleClass('ui-state-focus');
        },
        onSelect: function (selectedDate) {
            var date = $(this).datepicker("getDate");
            date.setDate(date.getDate() + 30);
            $('#targetDate').datepicker('option', 'minDate', date);
        }
    });
    $("#targetDate").datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: "dd-M-yy",
        showMonthAfterYear: true,
        onClose: function () {
            $(this).toggleClass('ui-state-focus');
        }
    });

});


text:
Q: How redirect while waiting for a response using react-router I'm trying to redirect from Login Component to DashBoard Component.
In this case my Login Component is called CodeClient and DashBoard Component is called IndexComponent.
My problem is that CodeClient Component makes request to authenticate with openid and when it makes the callback it doesn't enter sendToken(code, status) because it doesn't get info.I would like to redirect before to get the code and make the request.
If the render only contains:
class App extends Component {
    render() {
        return (
            <CodeClient />
        );
    }
}
export default App;

Enter on sendToken(code, status) and create the cookie and url shows next: http://localhost:3000/loginCallback?code=ab4d60814c50fe66de0bd9z4a3318f12&session_state=mVnqjmlT4gyTslk0cwbYeSOvxIKHqIl85pPX6Gh7f1c.63dfcdf9691b3ebcdd0cb28dcac27e94
But when I'm trying to make as I showed in one second show previous url and change for this: http://localhost:3000/login
My idea, is that user should not have access to any route without permissions and when user will be authenticated and refresh navigator continue on index page.
I'm not sure if I'm doing well and I'm going crazy to solve the problem the enter on getToken make the request, wait, create cookie and redirect to index.
Thanks and sorry for my English
Here is my code:
App.js
import React, { Component } from 'react';
import { BrowserRouter, Redirect, Switch, Route } from 'react-router-dom';

import './App.css';
import CodeClient from './components/Login/CodeClient';
import IndexComponent from './components/Index/IndexComponent';

const checkAuth = () => {
    const cookie = JSON.parse(localStorage.getItem('cookie'));
    if (!cookie) return false;
    try {
        const exp = cookie.exp;
        const current = new Date().getTime();
        if (exp < current) {
            return false;
        }
        return true;
    } catch (error) {
        return false;
    }
}

const Home = (props) => {
    if (checkAuth() === true) {
        return <IndexComponent {...props} />
    }
    return <Redirect to={{
        pathname: '/login',
        state: { from: props.location }
    }} />
}

const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route
    {...rest}
    render={props =>
        checkAuth() ? (
        <Component {...props} />
        ) : (
        <Redirect
            to={{
            pathname: "/login",
            state: { from: props.location }
            }}
        />
        )
    }
    />
);

class App extends Component {

    render() {

        return (
            <BrowserRouter>
                <Switch>
                    <Route path="/login" component={CodeClient} />
                    <PrivateRoute path="/" component={Home} />
                </Switch>
            </BrowserRouter>
        );
    }
}

export default App;

CodeClient.js
import React, { Component } from 'react';

import './CodeClient.css';
import request from 'request';

class CodeClient extends Component {

    constructor(props) {
        super(props);
        this.state = { messageError: '', ok: false };

        this.url = 'https://url_example/connect/authorize?scope=openid&response_type=code&client_id=myclientid&redirect_uri=http://localhost:3000/loginCallback';
        this.url = encodeURI(this.url);
    }

    handleLogin = (event) => {
        event.preventDefault();
        window.location.href = this.url;
    }

    componentDidMount() {
        var url_string = window.location.href;
        var url = new URL(url_string);
        var code = url.searchParams.get("code");
        var session_state = url.searchParams.get("session_state");

        if (code) {
            this.sendToken(code, session_state);
        }
    }

    sendToken = (code, state) => {
        var options = {
            method: 'POST',
            url: 'http://localhost:8080/login',
            headers: { 'content-type': 'application/json' },
            body: {
                code: code,
                state: state
            },
            json: true
        };

        request(options, (error, response, body) => {
            if (error) {
                this.setState({ messageError: 'Error al autenticarse: ', error, ok: false });
                // throw new Error(error);
            }

            if (body.ok === true) {
                this.createCookie(body);
                this.props.history.push('/');
            } else {
                this.setState({ messageError: 'El código ya no sirve', ok: false });
            }
        });
    }

    createCookie = (data) => {
        var info = {
            id: data.id,
            name: data.name,
            exp: new Date().getTime() + data.expires_in,
        };
        console.log(info)
        localStorage.setItem('cookie', JSON.stringify(info));
    }

    render() {
        return (

                        <form className="form-signin">
                            {
                                (this.state.ok === false) ? {this.state.messageError} :
                                    {this.state.messageError}
                            }

                            <button className="btn btn-lg btn-primary btn-block btn-signin" onClick={this.handleLogin} >Conectar</button>
                        </form>

        );
    }
}

export default CodeClient;

A: This is a possible solution, but it is a bad solution or bad implemented.
App.js
import React, { Component } from 'react';

import './App.css';
import request from 'request';
import IndexComponent from './components/Index/IndexComponent';

const checkAuth = () => {
    const cookie = JSON.parse(localStorage.getItem('cookie'));
    if (!cookie) return false;
    try {
        const exp = cookie.exp;
        const current = new Date().getTime();
        if (exp < current) {
            return false;
        }
        return true;
    } catch (error) {
        return false;
    }
}

class App extends Component {

    constructor(props) {
        super(props);
        // window.history.pushState("", "", '/');
        this.state = { logged: false, messageError: '', ok: false };

        this.url = 'https://url_example/connect/authorize?scope=openid&response_type=code&client_id=myclientid&redirect_uri=http://localhost:3000/loginCallback';
        this.url = encodeURI(this.url);
    }

    handleLogin = (event) => {
        event.preventDefault();
        window.location.href = this.url;
    }

    componentDidMount() {
        var url_string = window.location.href;
        var url = new URL(url_string);
        var code = url.searchParams.get("code");
        var session_state = url.searchParams.get("session_state");

        if (code) {
            this.sendToken(code, session_state);
        }
    }

    sendToken = (code, state) => {
        var options = {
            method: 'POST',
            url: 'http://localhost:8080/login',
            headers: { 'content-type': 'application/json' },
            body: {
                code: code,
                state: state
            },
            json: true
        };

        request(options, (error, response, body) => {
            if (error) {
                this.setState({ messageError: 'Error al autenticarse: ', error, ok: false });
                // throw new Error(error);
            }

            if (body.ok === true) {
                this.createCookie(body);
            } else {
                this.setState({ messageError: 'El código ya no sirve', ok: false });
            }
        });
    }

    createCookie = (data) => {
        var info = {
            id: data.id,
            name: data.name,
            exp: new Date().getTime() + data.expires_in,
        };
        localStorage.setItem('cookie', JSON.stringify(info));
        this.setState({ logged: true });
    }

    render() {
        if (checkAuth()) return <IndexComponent />;
        else {
            return (

                            <form className="form-signin">
                                {
                                    (this.state.ok === false) ? {this.state.messageError} :
                                        {this.state.messageError}
                                }

                                <button className="btn btn-lg btn-primary btn-block btn-signin" onClick={this.handleLogin} >Conectar</button>
                            </form>

            );
        }
    }
}

export default App;

IndexComponent.js
import React, { Component } from 'react';

import './IndexComponent.css'

const checkAuth = () => {
    const cookie = JSON.parse(localStorage.getItem('cookie'));
    if (!cookie) return false;
    try {
        const exp = cookie.exp;
        const current = new Date().getTime();
        if (exp < current) {
            return false;
        }
        return true;
    } catch (error) {
        return false;
    }
}

class IndexComponent extends Component {

    constructor(props) {
        super(props);
        window.history.pushState("", "", '/menu');
        this.checkCookie();
    }

    checkCookie = () => {
        if (!checkAuth()) {
            this.logout();
        }
    }

    logout = () => {
        localStorage.setItem('cookie', null);
        window.location.href = '/';
    }

    render() {
        return (

Home!

Estas logueado! Muy bien!

                <button onClick={() => {
                    this.logout()
                }}>Cerrar sesión</button>

        );
    }
}

export default IndexComponent;


text:
Q: psycopg2 with Postgres fetchall works but not execute I am trying to execute some Postgres queries with psycopg2.
import psycopg2

conn = psycopg2.connect(
    host="test.postgres.database.azure.com",
    database="postgres",
    user="test",
    password="test")
cur = conn.cursor()

sql = "select site_panel from test.ws_sites"

cur.execute(sql)
rows =  cur.fetchall()

The query above works well and returns the data but the following query does not delete the table as intended.
 cur.execute ("DROP TABLE IF EXISTS test.ws_sites")

Anything wrong I'm doing here?

A: A query that modifies table data or schema structure needs to be committed:
cur.execute ("DROP TABLE IF EXISTS test.ws_sites")
conn.commit()

Alternatively, place
conn.autocommit = True

after creating the connection.


text:
Q: Error on deploying django + uwsgi + nginx I'm trying to deploy a django project with uWSGI and nginx. I have the next configuration files:
uwsgi.ini
[uwsgi]

#Django-related settings
chdir = /home/amlalchy/api_aml_platform
module = api.wsgi
#static-map = /static=/home/amlalchy/api_aml_platform/services/static

#Process-related settings
master = true
processes = 10

# The socket(use the full path to be safe)
socket = /tmp/aml.sock

chmod-socket = 664
uid = www-data
gid = www-data

# Clear environment on exit
vacuum = true

uwsgi.service
[Unit]

Description=uWSGI Emperor service
After=network.target

[Service]

#User=amlalchy
#Group=www-data

ExecStartPre=/bin/bash -c 'mkdir -p /run/uwsgi; chown amlalchy:www-data /run/uwsgi'
ExecStart=/bin/bash -c 'cd /home/amlalchy/api_aml_platform && source /home/amlalchy/anaconda3/bin/activate AmlPlatform && uwsgi --ini /etc/uwsgi/sites/uwsgi.ini'

Restart=always
KillSignal=SIGQUIT
Type=notify
NotifyAccess=all

[Install]
WantedBy=multi-user.target

api.conf for the nginx configuration
server {
    listen 80;
    server_name server.prueba.com;
    charset utf-8;

    client_max_body_size 128M;

    location = /favicon.ico { access_log off; log_not_found off; }

    location /static {
        root /home/amlalchy/api_aml_platform/services;
    }

    location /media {
        root /home/amlalchy/api_aml_platform;
    }

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/tmp/aml.sock;
    uwsgi_read_timeout 300s;
    uwsgi_send_timeout 300s;
    }
}

I'm getting this error in /var/log/enginx/error.log :
2020/01/13 10:30:12 [error] 12641#12641: *1 open() "/home/amlalchy/api_aml_platform/services/static/css/global.css" failed (2: No such file or directory), client: 127.0.0.1, server: server.prueba.com, request: "GET /static/css/global.css HTTP/1.1", host: "127.0.0.1", referrer: "http://127.0.0.1/api/login/

I am newbie and I don't know what I'm missing because the static files exists... so I would be really grateful for any tip on my error.
Thanks in advance.

A: Where are your static files (css/js/images)? How do you deploy them?
As @ruddra suggested, how do you run your?
./manage.py collectstatic


text:
Q: Select multiple images from gallery and show in recyclerview I have to select multiple images from gallery and display them into horizontal recycler view, but I'm confusing how to do it right. I've created a recyclerview adapter for it
public class HorizontalRecyclerView extends RecyclerView.Adapter<HorizontalRecyclerView.HorizontalViewHolder> {

    private int[] images;
    private Uri uri;

    public HorizontalRecyclerView(int[] images, Uri uri) {
        this.images = images;
        this.uri = uri;
    }

    @NonNull
    @Override
    public HorizontalViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View view = inflater.inflate(R.layout.row_image, parent, false);
        return new HorizontalViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull HorizontalViewHolder horizontalViewHolder, int position) {
        //horizontalViewHolder.mImageRecyclerView.setImageResource(images[position]);
        horizontalViewHolder.mImageRecyclerView.setImageURI(uri);

        Picasso.get()
                .load(images[position])
                .into(horizontalViewHolder.mImageRecyclerView);
    }

    @Override
    public int getItemCount() {
        return images.length;
    }

    public class HorizontalViewHolder extends RecyclerView.ViewHolder {
        ImageView mImageRecyclerView;

        public HorizontalViewHolder(View itemView) {
            super(itemView);
            mImageRecyclerView = itemView.findViewById(R.id.imgLoader);
        }
    }
}

Can someone explain how can I do right?

A: Please refer to this question and this question
// before onCreate declare ---
final int PICK_IMAGE_MULTIPLE = 1;

// in onclick listener
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_IMAGE_MULTIPLE);

Then you should also override onActivityResult

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    try {
        // When an Image is picked
        if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK
                && null != data) {
            // Get the Image from data

            String[] filePathColumn = { MediaStore.Images.Media.DATA };
        imagesEncodedList = new ArrayList<String>();
        if(data.getData()!=null){

                Uri mImageUri=data.getData();

                // Get the cursor
                Cursor cursor = getContentResolver().query(mImageUri,
                        filePathColumn, null, null, null);
                // Move to first row
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imageEncoded  = cursor.getString(columnIndex);
                cursor.close();

            } else {
                if (data.getClipData() != null) {
                ClipData mClipData = data.getClipData();
                ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
                for (int i = 0; i < mClipData.getItemCount(); i++) {

                        ClipData.Item item = mClipData.getItemAt(i);
                    Uri uri = item.getUri();
                    mArrayUri.add(uri);
                    // Get the cursor
                    Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
                    // Move to first row
                    cursor.moveToFirst();

                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    imageEncoded  = cursor.getString(columnIndex);
                    imagesEncodedList.add(imageEncoded);
                    cursor.close();

                    }
                    Log.v("LOG_TAG", "Selected Images" + mArrayUri.size());
            }
        }
    } else {
        Toast.makeText(this, "You haven't picked Image",
                    Toast.LENGTH_LONG).show();
    }
} catch (Exception e) {
    Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                .show();
}

    super.onActivityResult(requestCode, resultCode, data);
}

Quoted from https://stackoverflow.com/a/34047251/9640177

A: You can try something like,
Define your recyclerView and adapter like this,
ArrayList<Uri> uri = new ArrayList<>();
RecyclerView recyclerView;
HorizontalRecyclerView adapter;

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

    recyclerView = findViewById(R.id.recyclerview);

    adapter = new HorizontalRecyclerView(uri);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(adapter);

}

Step 1: Select multiple images from Gallery (can be inside an onClick)
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Pictures: "), 1);

Step 2: Once selected you need to extract the selected image's URI and store it in an ArrayList<Uri>
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
        if (resultCode == Activity.RESULT_OK) {
            if (data.getClipData() != null) {
                int count = data.getClipData().getItemCount();
                for (int i = 0; i < count; i++) {
                    uri.add(data.getClipData().getItemAt(i).getUri());
                }
                adapter.notifyDataSetChanged();
            }
        } else if (data.getData() != null) {
            String imagePath = data.getData().getPath();
        }
    }
}

Step 3: Make changes to your Adapter like this
public class HorizontalRecyclerView extends RecyclerView.Adapter<HorizontalRecyclerView.HorizontalViewHolder> {

    private ArrayList<Uri> uri;

    public HorizontalRecyclerView(ArrayList<Uri> uri) {
        this.uri = uri;
    }

    @NonNull
    @Override
    public HorizontalViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View view = inflater.inflate(R.layout.item, parent, false);
        return new HorizontalViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull HorizontalViewHolder horizontalViewHolder, int position) {
        horizontalViewHolder.mImageRecyclerView.setImageURI(uri.get(position));
    }

    @Override
    public int getItemCount() {
        return uri.size();
    }

    public class HorizontalViewHolder extends RecyclerView.ViewHolder {
        ImageView mImageRecyclerView;

        public HorizontalViewHolder(View itemView) {
            super(itemView);
            mImageRecyclerView = itemView.findViewById(R.id.imageView);
        }
    }
}

This should do the trick. Refer this link.


text:
Q: Trying to understand this table - comparator with carry Create a circuit-table which compares two (signless) 4-bit binary numbers. The result is output signal c_i which is 1 if we have A≥B.
Given is A=0100 and B=0010. Fill the table whereby you choose c_-1 bit yourself so it makes all sense..
I believe this compare is done by subtraction and so we can use adder for this
(this is now for 1 bit:)
        3   2   1   0
----------------------
Ai      0   1   0   0
Bi      0   0   1   0
~Bi     1   1   0   1

Ci-1    1   0   0   1

Ci      1   1   0   1

We need to negate B, so negation of B is ~Bi in the table.
Then we add A and negation of B and if we see that Ci is 1 then we need to make sure that we get a carry when we add A and not B. I thought this is done like that.
Please can you tell me if this is right?

A: The simple answer is: compare is set-carry, subtract with carry. The only difference is the result is not stored.
So: Start with carry set, two-complement the compare value, add it to the accumulator value. You are done.

A: I think you need Ci-1 to do so: 1 0 1 1 but I'm not sure. Correct me if I'm wrong I'd also be interested in knowing it.


text:
Q: Using Expect in Bash to set the inital "postgres" user password? Following the tutorial here: http://www.unixmen.com/install-postgresql-9-4-phppgadmin-ubuntu-14-10/
I am scripting the installation of PostgreSQL in bash but having a problem when it comes to setting the initial user password.
Following the tutorial for this part we have:
# Login to postgresql prompt:
sudo -u postgres psql postgres

# .. and set postgres password with following command:
postgres=# \password postgres
Enter new password:
Enter it again:
postgres=# \q

Which is great but I want to set this password from the Bash script and one way that this type of task could generally with would using Expect:
# Build the command into a variable so that we can run it later
PSQL_QUERY=$(expect -c "

set timeout 10
spawn -u postgres psql postgres -c '\\\password postgres'

expect \"Enter new password:\"
send \"password\r\"

expect \"Enter it again:\"
send \"password\r\"

expect eof
");
# Run the command with automated entry
echo "$PSQL_QUERY";

But when I try to run the script I get output as follows:
root@node:/home/user# ./test.sh
send: spawn id exp6 not open
    while executing
"send "password\r""
spawn sudo -u postgres psql postgres -c '\password postgres'
psql: FATAL:  Peer authentication failed for user "postgres'"

Which I don't really understand both because I am new to PostgreSQL and because when I run the following:
root@node:/home/user# sudo -u postgres psql postgres -c '\password postgres'
Enter new password: <password>
Enter it again: <password>

It works. Could someone please help me with the understanding of where I am going wrong with this and how I could get it right so that I can set the new "postgres" user password from within a bash script. Thanks in advance!

A: Much easier:
sudo -u postgres psql -c "ALTER USER postgres WITH PASSWORD '{password}';"

Documentation on psql (PostgreSQL interactive terminal).


text:
Q: How to Specify Tablespace for XML Type Index creation in Oracle 11g I am trying to create an XML Index on XML Type column in one of my table.
We are using 2 tablespace here, one for Tables and the second for Indexes.
I would like to create the XMLIndex in the index tablespace.
I am using the below query -
CREATE INDEX VISION_IX1 ON MDT_VISION_LOGGING_TBL(RAWMESSAGE)
INDEXTYPE IS XDB.XMLINDEX
NOPARALLEL;

Please help me with where to mention the tablespace clause.

A: You have to name the path table to be able to specify the storage for the unstructured component:
CREATE TABLE MDT_VISION_LOGGING_TBL(ID NUMBER, RAWMESSAGE XMLTYPE) TABLESPACE TS_TABLES;

Table MDT_VISION_LOGGING_TBL created.

CREATE INDEX VISION_IX1 ON MDT_VISION_LOGGING_TBL(RAWMESSAGE)
INDEXTYPE IS XDB.XMLINDEX
PARAMETERS('PATH TABLE VISION_IX_PATH_TABLE (TABLESPACE TS_INDEXES)')
NOPARALLEL;

Index VISION_IX1 created.

You can see where the storage has been allocated:
SELECT US.SEGMENT_NAME, US.SEGMENT_TYPE, US.TABLESPACE_NAME
FROM USER_OBJECTS UO
JOIN USER_SEGMENTS US
ON US.SEGMENT_NAME = UO.OBJECT_NAME
WHERE UO.CREATED > TRUNC(SYSDATE);

SEGMENT_NAME                   SEGMENT_TYPE       TABLESPACE_NAME
------------------------------ ------------------ ------------------------------
MDT_VISION_LOGGING_TBL         TABLE              TS_TABLES
SYS304166_VISION_IX_PIKEY_IX   INDEX              TS_TABLES
SYS304166_VISION_IX_VALUE_IX   INDEX              TS_TABLES
SYS_IL0000304163C00003$$       LOBINDEX           TS_TABLES
SYS_LOB0000304163C00003$$      LOBSEGMENT         TS_TABLES
VISION_IX_PATH_TABLE           TABLE              TS_INDEXES

You can specify that the other two indexes that creates go in your preferred tablespace too:
CREATE INDEX VISION_IX1 ON MDT_VISION_LOGGING_TBL(RAWMESSAGE)
INDEXTYPE IS XDB.XMLINDEX
PARAMETERS('PATH TABLE VISION_IX_PATH_TABLE (TABLESPACE TS_TABLES)
  PIKEY INDEX VISION_IX_PIKEY (TABLESPACE TS_INDEXES)
  VALUE INDEX VISION_IX_VALUE (TABLESPACE TS_INDEXES)')
NOPARALLEL;

SELECT US.SEGMENT_NAME, US.SEGMENT_TYPE, US.TABLESPACE_NAME
FROM USER_OBJECTS UO
JOIN USER_SEGMENTS US
ON US.SEGMENT_NAME = UO.OBJECT_NAME
WHERE UO.CREATED > TRUNC(SYSDATE);

SEGMENT_NAME                   SEGMENT_TYPE       TABLESPACE_NAME
------------------------------ ------------------ ------------------------------
MDT_VISION_LOGGING_TBL         TABLE              TS_TABLES
SYS_IL0000304183C00003$$       LOBINDEX           TS_TABLES
SYS_LOB0000304183C00003$$      LOBSEGMENT         TS_TABLES
VISION_IX_PATH_TABLE           TABLE              TS_INDEXES
VISION_IX_PIKEY                INDEX              TS_INDEXES
VISION_IX_VALUE                INDEX              TS_INDEXES


text:
Q: mongoose convert all leaned ObjectIds to String format I'm using mongoose-paginate-v2 to paginate my documents, and I use lean=true to make them a plain Object (I want to filter them using accesscontrol.
When I get the leaned Objects , all ObjectIds are in Object formate like below:
{"_id":{"_bsontype":"ObjectID","id":{"type":"Buffer","data":[95,94,16,4,98,8,156,8,236,35,179,155]}}

I get that its the way that MongoDB handles it but I want to send String ObjectId to the client (so that it can access resources with that Id). I know that by using vituals and id instead of _id I can get the string representation of that object's _id, but the problem is I want All ids to be string, not just the id of the object.
If I try to write a middleware that changes all id objects to string representation, I'll need a way to deep find all ids in my result , which I don't know how to do.
How an I have all ids in string format, yet still have leaned object?

A: May be a little late in replying, we can use lodash transform for this-

var transform = require('lodash.transform');
var isObject = require('lodash.isobject');
const ObjectId = require('mongoose').Types.ObjectId;

const transformObjectId = obj => transform(obj, (acc, value, key, target) => {
    if(value instanceof ObjectId){
        acc[key] = value ? value.toString() : '';
    } else if(value instanceof Date){
        acc[key] = value;
    }else{
        acc[key] = isObject(value) ? transformObjectId(value) : value;
    }
  })

module.exports = {
    transformObjectId: transformObjectId
}


text:
Q: When i want to use 2 dimensional array it returns me undefined I work with database which I input.
I declared array and wanted to push another array in first one.
When I try to use my 2 dimensional array, console returned undefined.

let dataAboutCovid = [];
let date, totalCases, todayCases, recovered;
let country = "USA";

//Read file from input
//Control if country exist
//Put data about covid in dataAboutCovid

function readFile(input) {
  let database;

  for (i = 0; i < input.files.length; i++) {

    let reader = new FileReader();
    reader.readAsText(input.files[i]);

    reader.onload = function(e) {
      database = e.target.result;

      let arrayOfCountry = database.split(`\n`).find((item) => item.includes(country))
      if (!arrayOfCountry) {
        return
      }
      if (arrayOfCountry.slice(0, 3) == ",,,") {
        date = arrayOfCountry.slice(3, this.length).split(",")[1].split(" ")[0];
        totalCases = arrayOfCountry.slice(3, this.length).split(",")[4];
        todayCases = arrayOfCountry.slice(3, this.length).split(",")[5];
        recovered = arrayOfCountry.slice(3, this.length).split(",")[6];
        dataAboutCovid.push([date, totalCases, todayCases, recovered]);
      }
    }
  };

  console.log(dataAboutCovid[1][1])
}

A: I see two issues.

*

*When i is 0, you would only fill up dataAboutCovid[0], so dataAboutCovid[1] is undefined

*There's a possibility that console.log is executed before reader.onload due to the asynchronous nature of js.

A: I think you're trying to read a bunch of files rather than just one file and iterating on the split newlines


text:
Q: Subclass QList for Quicksort Calling Qsort from QList does not appear to work for sorting on 2 columns. If this is the case I would like to subclass QList and add a Quicksort method that calls a "compare" function to determine the sort order.
Being new to Qt (mainly Delphi) I am having trouble implementing the code.
I hope the following expresses the "concept" of the code required:
//prototype
#define TComp = int compare(pointer1, pointer2);

int MyComp(p1, p2)
{
  if      (p1.x < p2.x) return –1
  else if (p1.x > p2.x) return  1
  else if (p1.y < p2.y) return –1
  else if (p1.y > p2.y) return  1
  else                  return  0
}

class TObjList : public QList
{
public:
  void mySort(MyComp);
private:
  void QuickSort(TComp MyComp);
};

This is a big ask, but I need the help at this stage.

A: There are several things here I wouldn't do:

*

*Subclassing a container type like QList doesn't make sense, as it has no virtual methods to reimplement. Just to add a helper function doesn't justify subclassing, make it a free function.

*Implement sorting as member function instead of a generic function like std::sort.

*reimplement the whole sort algorithm just to get your own comparison operator used

I'd suggest to use std::sort and a custom comparison function (in C++11, this could use a lambda or std::tuple which implements lexicographical comparison like done here):
template <typename T>
bool xyLessThan(const T &lhs, const T &rhs)
{
    if (lhs.x == rhs.x)
        return lhs.y < rhs.y;
    return lhs.x < rhs.x;
}

And then e.g.
QList<Point> points;
...
std::sort(points.begin(), points.end(), &xyLessThan);

That uses a generic sorting algorithm which let's you specify the function to be used for comparison, which is xyLessThan here.
If you control the class of the elements (the T in QList) and if there's a "natural" sorting, you can add an operator< like this:
bool Point::operator<(const Point &other) const
{
    if (x == other.x)
        return y < other.y;
    return x < other.x;
}

then you can just do
std::sort(points.begin(), points.end());


text:
Q: Elemento não aceita a propriedade "height" nem "min-height" Tenho o seguinte arquivo com códigos HTML, CSS e JavaScript, meu problema é o seguinte:
Lá no final do arquivo, eu tenho um tag
 e dentro dela tenho uma
, o problema é que não funciona a propriedade height que estou tentando usar nessa local, a tentativa de usar a propriedade height está dentro desse bloco de códigos, veja que tentei usar o height e o min-height e mesmo assim não funciona.
.req li a {
background-color: red;
margin-right: 20px;
height: 50px;
line-height: 50px;
position: relative;
text-decoration: none; }

Arquivo:
<!DOCTYPE html>

<title>Menu</title>
<link href="http://netdna.bootstrapcdn.com/font-awesome/3.1.1/css/font-awesome.min.css" rel="stylesheet" />
<link href="css/bootstrap.min.css" rel="stylesheet">

<link rel="stylesheet" type="text/css" href="css/menu_style.css" />

<link href="css/font-awesome.min.css" rel="stylesheet" />
<link href="css/font-awesome.css" rel="stylesheet" />

Geral

Pesquisa

Conteúdo

Aplicativos

Privacidade

Aplicativos

Privacidade

Requisições

A: Funciona se forçar o elemento para inline-block:
.req li a {
   display: inline-block;
}


text:
Q: permanently decrypt messages in outlook (S/MIME) I have messages encrypted with S/MIME in Microsoft Outook. These can only be decrypted with the certificate installed on the client.
Encryption stays even when saving the messagesto disk (as .msg) or moving them to another e-mail account (drag and drop in exchange).
How can I permanently decrypt these messages?
Either for saving them on disk or inside of Exchange/IMAP.

A: I just found this option in Outlook:

*

*Open the encrypted email (you might need your password or whatever)

*in the email window, use the menu item 'File/Info/Properties'

*In the pop-up, under Security (top right), uncheck 'Encrypt email...', close, and save:

(It is grayed out in this shot, but if you have an encrypted email, it will be checked and changeable)


text:
Q: Getting general SSL Engine problem while calling API in mule4 I am trying to call https API end point(implemented in mulesoft) using Request component(Mule component) from another flow. When i am calling from local machine it working fine. But when i deployed to Anypoint Exchange it is throwing General SSL engine problem. Can anyone help me out?

A: Try to use alternative way to reach end point with this SSL error. I guess url starts with https:// since it is throwing SSL exception. Grab this url and try to open it in some browser. It will tell you what is the reason for exception and is SSL certificate valid or not.
Work around it - make http config to ignore SSL certificate.
https://simpleflatservice.com/mule4/HowToIgnoreInsecureCertificates.html
After all it is yours (probably) service and you may trust it.


text:
Q: SSD for detecting small objects I'm going to use Google Detection API's SSD model for detecting small objects (Like a Volleyball in a picture).
I want to change the following parametrs in config file (Aspect ratio, scale,..) :

anchor_generator {
  ssd_anchor_generator {
    num_layers: 6
    min_scale: 0.2
    max_scale: 0.95
    aspect_ratios: 1.0
    aspect_ratios: 2.0
    aspect_ratios: 0.5
    aspect_ratios: 3.0
    aspect_ratios: 0.3333

I have three questions:

*

*For modifying these parameters (scale, aspect ratio,...), Do I need to re-train the model? or after these modification I still can use pre-trained models and fine-tune for my data?

*Since the objects that I want to detect them are all small comparing to the image size, does increasing or decreasing number of conv layers in mobilenet improve (speed or accuracy) detection? if yes, in which file I can apply these changes?

*Is there any specific method for modifying SSD mobilenet detector to make it work better for detecting small objects? For example I know a 4X4 feature map (grid) is too big for size of my object, is there any way to remove course grids and just keep fine grids (like 8X8)?
Thank you.

A: For modifying these parameters (scale, aspect ratio,...), Do I need to re-train the model? or after these modification I still can use pre-trained models and fine-tune for my data?
Yes you need to retrain your model, because the network was trained to find volleyballs at that specific aspect ratio, however you can retrain the existing network rather than using a new one.
Since the objects that I want to detect them are all small comparing to the image size, does increasing or decreasing number of conv layers in mobilenet improve (speed or accuracy) detection? if yes, in which file I can apply these changes?
Typically you want the near minimal size network that still produces reasonable accuracy, however  I am not sure if tensorflow allows for setting image resampling limits, because at that size of an image you might resample the volleyball out of the image altogether.  Training is the slowest part of any neural network, and running a query for detection is not much of a concern for performance.
Is there any specific method for modifying SSD mobilenet detector to make it work better for detecting small objects? For example I know a 4X4 feature map (grid) is too big for size of my object, is there any way to remove course grids and just keep fine grids (like 8X8)?  As mentioned before resampling would be important to set, however I am not sure if it is possible. Perhaps that might be the scale parameters.

A: I would recommend you first to use the following tutorial for increasing the performance of this network family: https://github.com/tensorflow/models/blob/master/research/object_detection/colab_tutorials/generate_ssd_anchor_box_aspect_ratios_using_k_means_clustering.ipynb.
If you need it in TF1 tell me I can send it to you.
The thing is, that you must modify the network itself and know what to do. In the ssd_mobilenet_v2_feature_extractor.py line 110-114 could be interesting, here you can say when(which layer) to start the detection.
Another helpful thing in relation to the custom ssd-anchors is multiple_grid_anchor_generator.py line 328-329, because normally the config file says the ssd is 6 layers, the tutorial I linked will generate 6 custom ssd-anchors (read the tutorial for detailed explanation), but the python scripts limits it so 3...


text:
Q: Laravel vue-router getting single data I'm trying to return my data such as posts by their slug but so far I couldn't make it by Vue-router
Code
controller
public function single($slug)
    {
        $post = Post::where('slug', $slug)->first();
        return response()->json([
            "post" => $post
        ], 200);
    }

blog.vue
    <li v-for="post in posts" :key="post.slug">
      <router-link to="/blog/${post.slug}">{{ post.title }}</router-link>
    </li>

<script>
    export default {
        name: 'list',
        mounted() {
            if (this.posts.length) {
                return;
            }

            this.$store.dispatch('getPosts');
        },
        computed: {
            posts() {
                return this.$store.getters.posts;
            }
        }
    }
</script>

vuex store.js
state: {
        posts: []
    },
getters: {
        posts(state) {
            return state.posts;
        }
    },
mutations: {
        updatePosts(state, payload) {
            state.posts = payload;
        }
    },
actions: {
        getPosts(context) {
            axios.get('/api/posts')
            .then((response) => {
                context.commit('updatePosts', response.data.posts);
            })
        }
    }

Problem
The problem is that i get this kind of url in my loop
site.pp/blog/${post.slug}

I should get something like:
site.pp/blog/hello-world

Question

*

*Where did I make mistake? and how to fix it?


text:
Q: Redux newbie attempting to make chrome extension work I am looking for a solution to Redux token import (of which I only learned today). I am attempting to write a Redux expression into a chrome extension called "Highlight This" (found here https://www.highlightthis.net/).
It appears the extension takes Redux "tokens", whatever that might be, and I need it to highlight a filed only if populated and have attempted to wrap my head around the expression would be and got as far as probably needs to be a if/then but not much further than that as I have absolutely no previous experience with Redux expressions.
I need the extension to highlight a specific field that happens in the middle of a page, and the filed is either blank or has a date.
Looks like this:

description
value

Irrelevant 1
yyyy-mm-dd hh:mm:ss AM

Most Recent Flag Time
blank or yyyy-mm-dd hh:mm:ss AM

Irrelevant 2
yyyy-mm-dd hh:mm:ss AM

If someone can either point me in the right direction of what I should look at to write my own expression or show me an example I want to basically have the extension check the field right after "Most Recent Flag Time" and if it contains anything to simply highlight that date as it would as if I gave it a specific word to search and highlight automatically.


text:
Q: How to get the element clicked on? How would you check to see which item was clicked in the document, given this code?
if ( document.addEventListener && document.attachEvent && document.fireEvent ) {
    document.attachEvent( "onclick", function() {
     // ...
    });
}

A: // using e.srcElement or event.srcElement

try this :)
and see this http://www.quirksmode.org/js/events_advanced.html
if (document.addEventListener){
    document.addEventListener("click", function(event){
        var targetElement = event.target || event.srcElement;
        console.log(targetElement);
    });
} else if (document.attachEvent) {
    document.attachEvent("onclick", function(){
        var targetElement = event.target || event.srcElement;
        console.log(targetElement);
    });
}


text:
Q: How to get rows whose nth column contains mth column I have a CSV file contains domains and webmails, like this:
site1.com,mail.site1.com
site2.com,testmail.com
site3.com,mx.site3.com
site4.com,smtp.site4.com
site5.com,foomail.com
site6.com,barmail.com
site7.com,webmail.site7.com
site8.com,01mx.site8.com
site9.com,foobarmail.com
site10.com,mx-smtp222.site10.com

I want to get rows where the webmails column contains the domains column of the same row.  For the example above, the output should be:
site1.com,mail.site1.com
site3.com,mx.site3.com
site4.com,smtp.site4.com
site7.com,webmail.site7.com
site8.com,01mx.site8.com
site10.com,mx-smtp222.site10.com

A: With awk:
awk -F, '$2 ~ $1"$"' file.csv

*

*-F, sets the field separator as ,

*$2 ~ $1"$" tests if the second field ends with the first field; if so, print the record (default action)

With grep, grep by default print only matched lines:
grep -E '^([^,]+),.*\1$' file.csv

With sed, printing lines matching the condition:
sed -nE '/^([^,]+),.*\1$/ p' file.csv

Example:
% cat file.txt
site1.com,mail.site1.com
site2.com,testmail.com
site3.com,mx.site3.com
site4.com,smtp.site4.com
site5.com,foomail.com
site6.com,barmail.com
site7.com,webmail.site7.com
site8.com,01mx.site8.com
site9.com,foobarmail.com
site10.com,mx-smtp222.site10.com

% awk -F, '$2 ~ $1"$"' file.txt
site1.com,mail.site1.com
site3.com,mx.site3.com
site4.com,smtp.site4.com
site7.com,webmail.site7.com
site8.com,01mx.site8.com
site10.com,mx-smtp222.site10.com

% grep -E '^([^,]+),.*\1$' file.txt
site1.com,mail.site1.com
site3.com,mx.site3.com
site4.com,smtp.site4.com
site7.com,webmail.site7.com
site8.com,01mx.site8.com
site10.com,mx-smtp222.site10.com

% sed -nE '/^([^,]+),.*\1$/ p' file.txt
site1.com,mail.site1.com
site3.com,mx.site3.com
site4.com,smtp.site4.com
site7.com,webmail.site7.com
site8.com,01mx.site8.com
site10.com,mx-smtp222.site10.com


text:
Q: C-like type declaration. In most math books declaring an object along with its type is done with the type after a colon after the object, and the definition of this object is done in another expression. E.g.
$$
\begin{align}
n & : \mathbb{N} \\
f & :\mathbb{R} \to \mathbb{R}\\
\\
n & := 3. \\
f & := x \mapsto 2x.
\end{align}
$$
When I define an object while declaring its type, I do either the following (with the type of the object in the end, after the definiens):
$$
\begin{align}
n & := 3 & : \mathbb{N}. \\
f & := x \mapsto 2x & : \mathbb{R} \to \mathbb{R}.
\end{align}
$$
Or the following (with the type of the object after the definiendum):
$$
\begin{align}
n & : \mathbb{N} & := 3. \\
f &: \mathbb{R} \to \mathbb{R} & := x \mapsto 2x.
\end{align}
$$
But is it right to use a notation like in the C programming language, where the type is written before the object with no colon (like in the following example)?  Is there a math book which uses this notation instead of the colon one?
$$
\begin{align}
\mathbb{N} & \space n := 3. \\
\mathbb{R} \to \mathbb{R} & \space f := x \mapsto 2x.
\end{align}
$$

A: All four of these are horrible to read. The closest that I've seen to your last is $f: \mathbb{R}\ni x \mapsto 2x \in \mathbb{R}$, but that's rare and hiddeous as well. We aren't doing programming: what we're writing is intended to be readable by humans, not parseable by computers. Therefore, you should write something that is easy for humans to read. Sentences are easy for humans to read. For your examples, I'd write "let $x = 3$" (no need to specify that it's natural: we can see that) and Define \begin{align*}f:\mathbb{R}\to\mathbb{R}\\:x\mapsto 2x\end{align*}
respectively. No need to mess around with arcane patterns and arrangements of symbols that do nothing but make the text harder to read.


text:
Q: Rspec / Capybara issues -- Capybara won't visit page Ok so I'm kinda new, but have somewhat of an idea of what I'm doing, but this one just has me stumped for the past couple hours, so any help is very much appreciated.  I'm building a site and have been using Rspec and Capybara to test my site as I'm moving along. I ended up needing to remove turbolinks to improve functionality for my jscripts.  The next time I try to run tests, literally 50% of my test suite just magically broke. I've narrowed it down to that the commonality between all the failures was that the "visit" either appeared in or just before the code block. So basically removing Turbolinks somehow blew Capybara up or Rspec. I'm really having some trouble figuring this one out.  I tried updating the gems, that didn't work. I guess the next step is either skip the TDD concept, which I don't want to do, or start uninstalling the gems and do a reinstall and pray that that doesn't render my app useless...  Any help anyone can provide is much appreciated, and if you're in NYC I'll buy you a beer.
There are also other tests that are failing that don't require any sort of authentication, just to check the page for title and content and those are failing to.  I bring that up only to say I don't think that FactoryGirl is causing the problem.
Cheers.
The errors
2) User pages profile page
 Failure/Error: before { visit user_path(user) }
 NoMethodError:
   undefined method `user_path' for #<RSpec::ExampleGroups::UserPages::ProfilePage:0x00000004290410>
 # ./spec/requests/user_pages_spec.rb:10:in `block (3 levels) in <top (required)>'

3) User pages profile page
 Failure/Error: before { visit user_path(user) }
 NoMethodError:
   undefined method `user_path' for #<RSpec::ExampleGroups::UserPages::ProfilePage:0x00000004207c00>
 # ./spec/requests/user_pages_spec.rb:10:in `block (3 levels) in <top (required)>'

4) User pages signup page
 Failure/Error: before { visit signup_path }
 NameError:
   undefined local variable or method `signup_path' for #<RSpec::ExampleGroups::UserPages::SignupPage:0x000000041b3088>
 # ./spec/requests/user_pages_spec.rb:18:in `block (3 levels) in <top (required)>'

The test suite code
require 'spec_helper'

describe "User pages" do

subject { page }

#Profile tests
describe "profile page" do
    let(:user) { FactoryGirl.create(:user) }
    before { visit user_path(user) }

    it { should have_content(user.name) }
    it { should have_title(user.name) }
end

#Signup page tests
describe "signup page" do
    before { visit signup_path }

    it { should have_content('Sign up') }
    it { should have_title(full_title('Sign up')) }
end

describe "signup" do

    before { visit signup_path }

    let(:submit) { "Create my account" }

    describe "with invalid information" do
        it "should not create a user" do
            expect { click_button submit }.not_to change(User, :count)
        end
    end

    describe "with valid information" do
        before do
            fill_in "Name",                 with: "Example User"
            fill_in "Email",                with: "user@example.com"
            fill_in "Password",             with: "foobar00"
            fill_in "Confirmation",         with: "foobar00"
        end

        it "should create a user" do
            expect { click_button submit }.to change(User, :count).by(1)
                end
           end
      end
end

A: try to remove your visiting pages from before blocks  .
So , you just need :
describe "signup page" do
  feature "should have content 'Sign up' "
   visit signup_path
   it { should have_content('Sign up') }
  end
  feature "should have full title 'Sign up' "
   visit signup_path
   it { should have_title(full_title('Sign up')) }
  end
end

And you need to do like this in every describe block  .

A: Ok so to anyone else that runs into this issue, I did some more digging it's not a so uncommon occurrence for Capybara to get weird at times.  But I got the route errors to fix and pass green by adding "config.include Rails.application.routes.url_helpers" to the spec_helper.rb file.
Rspec.configure do |config|
*
*
*
config.include Rails.application.routes.url_helpers

end
Unfortunately I can't provide any insight why that line needed to be added, when previously it was not needed.  I'll have to leave that answer to someone with more knowledge than myself.