text:
Q: I have a gradle sync error JAVA_LETTER_OR_DIGIT when trying to add Firebase to my android project When I added the dependencies as told in the firebase guide and sync the project ,I get the error JAVA__LETTER_OR_DIGIT .I work with MAC OS X Yosemite and my android studio version is 3.1.4
My app grade file
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "e.apple.mse_project"
        minSdkVersion 22
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.google.firebase:firebase-analytics:17.2.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

apply plugin: 'com.google.gms.google-services'

My project grade file
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.4'
        classpath 'com.google.gms:google-services:4.3.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

This is the error that I get in the build console
The error log that shows in my build console
Thanks in advance !

A: The problem is with Android gradle plugin which doesn't work well with Google's Maven repository.
You can downgrade your google-services down to 4.2.0 as it was said by @mownathi-manigundan. Version 4.2.0 is available in AndroidTools Repository which outdated gradle plugin handles just fine
But it'd be better to update your plugin up to 3.2 or higher and use recommended com.google.gms:google-services:4.3.2. You can read more here how to to this

A: Try changing your version of gms google service in your project gradle as com.google.gms:google-services:4.2.0


text:
Q: AMOLED display vs. LCD display: Power consumption when displaying white only? LCD's power consumption only depends on the screen brightness setting, not on the displayed content, unlike AMOLED, where brighter colours (towards white) cause more power consumption, while black means that the pixel is completely turned off (=no power consumption).
Now, what consumes more power at the same brightness?

*

*LCD?

*AMOLED displaying white?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use different functoids within an array or vector I have written a small piece of code where I am able to call setter and getter functions packed within a functoid using mem_fun templates.
I now would like to use this approach on top of a class hierarchy where every class might have getter and setter which can be registered as pair within a vector or array to be able to call the getter and setter if needed. GUIObject and GUICompositeObject are example classes out of the described class hierarchy.
The bound_mem_fun_t for the objects have unfortunately different types and thats the reason I don't know how to integrate them into an array/vector of pointers to the functors.
In c++11 I would use std::function. Is there a way to emulate this in c++98?
Because our compiler support only c++98 I cannot use the new features of c++11 or c++14. Also boost is not allowed.
#include <functional>

class GUIObject
{
    int m_Alpha;
public:
    void SetAlpha(int a) { m_Alpha = a;};
    int GetAlpha() {return m_Alpha;};
};

class GUICompositeObject: public GUIObject
{
    int m_NumOfChilds;
public:
    void SetNumOfChilds(int NumOfChilds) { m_NumOfChilds = NumOfChilds;};
    int GetNumOfChilds() {return m_NumOfChilds;};
};

template<typename T>
struct bound_mem_fun_t
{
    bound_mem_fun_t(std::mem_fun_t<int, T> GetFunc, std::mem_fun1_t<void, T, int> SetFunc, T* o) :
            m_GetFunc(GetFunc), m_SetFunc(SetFunc), obj(o) { } ;
    int operator()() { return m_GetFunc(obj); } ;
    void operator()(int i) { m_SetFunc(obj, i); } ;
    std::mem_fun_t<int, T> m_GetFunc;
    std::mem_fun1_t<void, T, int> m_SetFunc;
    T* obj;
};

int main()
{
    GUIObject kGUIObject;
    GUICompositeObject kCompObj;

    bound_mem_fun_t<GUIObject> GUIObjectFunc(std::mem_fun(&GUIObject::GetAlpha), std::mem_fun(&GUIObject::SetAlpha), &kGUIObject);
    GUIObjectFunc(17);
    int ii = GUIObjectFunc();

    bound_mem_fun_t<GUICompositeObject> GUICompObjectFunc(std::mem_fun(&GUICompositeObject::GetNumOfChilds), std::mem_fun(&GUICompositeObject::SetNumOfChilds), &kCompObj);
    GUICompObjectFunc(17);
    int iChilds = GUICompObjectFunc();

    return 0;
}

Here is the complete solution after @filmors answer:
#include <functional>
#include <vector>
#include <iostream>

class GUIObject
{
    int m_Alpha;
public:
    void SetAlpha(int a) { m_Alpha = a;};
    int GetAlpha() {return m_Alpha;};
};

class GUICompositeObject: public GUIObject
{
    int m_NumOfChilds;
public:
    void SetNumOfChilds(int NumOfChilds) { m_NumOfChilds = NumOfChilds;};
    int GetNumOfChilds() {return m_NumOfChilds;};
};

struct bound_mem_fun_base
{
    virtual int operator()() =0;
    virtual void operator()(int) =0;
};

template<typename T>
struct bound_mem_fun_t : public bound_mem_fun_base
{
    bound_mem_fun_t(std::mem_fun_t<int, T> GetFunc, std::mem_fun1_t<void, T, int> SetFunc, T* o) :
            m_GetFunc(GetFunc), m_SetFunc(SetFunc), obj(o) { } ;
    virtual int operator()() { return m_GetFunc(obj); } ;
    virtual void operator()(int i) { m_SetFunc(obj, i); } ;
    std::mem_fun_t<int, T> m_GetFunc;
    std::mem_fun1_t<void, T, int> m_SetFunc;
    T* obj;
};

template<typename T> bound_mem_fun_t<T>* make_setter(std::mem_fun_t<int, T> GetFunc, std::mem_fun1_t<void, T, int> SetFunc, T* o)
{
    return new bound_mem_fun_t<T> (GetFunc, SetFunc, o);
}

int main()
{
    GUIObject kGUIObject;
    GUICompositeObject kCompObj;

    std::vector<bound_mem_fun_base*> kBoundVector;

    kBoundVector.push_back(new bound_mem_fun_t<GUIObject> (std::mem_fun(&GUIObject::GetAlpha), std::mem_fun(&GUIObject::SetAlpha), &kGUIObject));
    kBoundVector.push_back(new bound_mem_fun_t<GUICompositeObject> (std::mem_fun(&GUICompositeObject::GetNumOfChilds), std::mem_fun(&GUICompositeObject::SetNumOfChilds), &kCompObj));
    kBoundVector.push_back(make_setter<GUIObject> (std::mem_fun(&GUIObject::GetAlpha), std::mem_fun(&GUIObject::SetAlpha), &kGUIObject));
    kBoundVector.push_back(make_setter<GUICompositeObject> (std::mem_fun(&GUICompositeObject::GetNumOfChilds), std::mem_fun(&GUICompositeObject::SetNumOfChilds), &kCompObj));

    for (int i = 0; i < 4 ; i++)
    {
        (*kBoundVector[i])(i*10);
        int res = (*kBoundVector[i])();
        std::cout << "Getter result " << res << "\n";
    }

    return 0;
}

Unfortunately the make_setter function does not really shorten the creation of the functor. Any ideas will be welcome.

A: Just give your bound_mem_fun_t<T> a common base class and use dynamic dispatch to solve your problem:
struct bound_mem_fun_base {
    virtual int operator()() = 0;
    virtual void operator()(int) = 0;
};

template <typename T>
struct bound_mem_fun_t : bound_mem_fun_t ...

Then you can keep pointers to bound_mem_fun_base in your vector and call the elements as (*v[0])().
Also, TR1 does contain std::tr1::function, is that available?

A: First a remark on std::function from c++11: That will not solve your problem, because you need an already bounded function pointer. This pointer must be bound to your object. I believe what you need is an own implementation to std::bind.
I started only a very! small Binder class which is hopefully a starting point for your needs. If you need to have template parameter lists in older c++ versions, take a look for loki. http://loki-lib.sourceforge.net/
As a hint I can give you a short example of what i did:
class A
{
    private:
        int val;
    public:
        A(int i): val(i) {}
        void Do(int i) { std::cout << "A " << val<< " " << i << std::endl; }
};

class B
{
    private:
        int val;
    public:
        B(int i): val(i){}
        void Go(int i) { std::cout << "B " << val << " " << i << std::endl; }
};

class Base
{
    public:
        virtual void operator()(int i)=0;
};

template <typename T>
class Binder: public Base
{
    void (T::*fnct)(int);
    T* obj;

    public:
    Binder( void(T::*_fnct)(int), T*_obj):fnct(_fnct),obj(_obj){}
    void operator()(int i)
    {
        (obj->*fnct)(i);
    }

};

int main()
{
    A a(100);
    B b(200);

    // c++11 usage for this example
    //std::function<void(int)> af=  std::bind( &A::Do, &a, std::placeholders::_1);
    //af(1);

    // hand crafted solution
    Base* actions[2];

    actions[0]= new Binder<A>( &A::Do, &a);
    actions[1]= new Binder<B>( &B::Go, &b);

    actions[0]->operator()(55);
    actions[1]->operator()(77);

}


text:
Q: Django - issue with displaying SearchHeadline object in a template I am working on search functionality and I need to implement SearchHeadline to highlight searched words however I am struggling to do it in multiple fields.
What I'd like to do is to highlight not only words in the title field but also the short_description field. I found this question and tried to implement Concat however, in my case title and short_description are placed in 2 seperated html elements so I cannot just concatenate them and display as 1 headline because I need to display the whole title and the whole short_description and highlight matching words.
views.py
class SearchResultsList(LoginRequiredMixin, ListView, CategoryMixin):
    model = QA
    context_object_name = "query_list"
    template_name = "search/SearchView.html"

    def get_queryset(self):
        query = self.request.GET.get("q")
        search_vector = SearchVector("title", weight="A") + SearchVector("short_description", weight="B")
        search_query = SearchQuery(query)
        search_headline = SearchHeadline('title', search_query, start_sel='',stop_sel='') # how to implement SearchHeadline to short_description?
        return QA.objects.annotate(
            search=search_vector,
            rank=SearchRank(search_vector, search_query)
        ).annotate(headline=search_headline).filter(rank__gte=0.3).order_by("-rank")

        #The code below is working but it concatenates the title with the short description and I need to separate these fields. Moreover, it shows only a preview, not the whole title and short description value
        # return QA.objects.annotate(search_vectors=SearchVector('title', 'short_description'), ).annotate(headline=SearchHeadline(Concat(F('title'), Value(' '), F('short_description')),SearchQuery(query),start_sel='', stop_sel='')).filter(search_vectors=SearchQuery(query))

SearchView.html
{% for query in query_list %}

{{query.headline | safe}}

{{query.short_description |safe}}
 # how to implement SearchHeadline to short_description so it displayed whole text and highlights matching words as in the title field?

{% empty %}

No results

{% endfor %}


text:
Q: Unable to include a stylesheet link in my view I'm having a problem declaring a stylesheet tag in my Rails 5 view.  I have this
<%= stylesheet_link_tag    'form', media: 'all', 'data-turbolinks-track': 'reload' %>

and then in my config/initializers/assets.rb I have this at the end
Rails.application.config.assets.precompile += %w( form.css )

My file is located at app/assets/stylesheets/form.css.scss, but even after restarting my server, I get the error below
Sprockets::Rails::Helper::AssetNotPrecompiled in MyEvents#index

Asset was not declared to be precompiled in production.
Add `Rails.application.config.assets.precompile += %w( form.css )` to `config/initializers/assets.rb` and restart your server

How do I get Rails to include this stylesheet on my page?

A: When I changed the stylesheet tag to simply
<%= stylesheet_link_tag    'form' %>

then eveerything worked.


text:
Q: How to Clear a OnScroll(AbsListView) - Android I have a onScrollListener that calls an AsyncTask once the last View in the ListView is shown. The AsyncTask adds Data to a ListView using an ArrayAdapter. The problem is when I clear the ArrayAdapter with arrayAdapter.clear() it clears the adapter but all the variables in AbsListView still think the Items exist so it doesn't detect when I am at the bottom of the ListView, Here is the onScrollListener.
class EndlessScrollListener implements OnScrollListener {
                private int visibleThreshold = 5;
                private boolean loading = true;

                public EndlessScrollListener() {
                }
                public EndlessScrollListener(int visibleThreshold) {
                    this.visibleThreshold = visibleThreshold;
                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem,
                        int visibleItemCount, int totalItemCount) {

                   if (loading) {
                        if (totalItemCount > previousTotal) {
                           loading = false;
                            previousTotal = totalItemCount;
                        }
                }
                    if (!loading && (firstVisibleItem + visibleItemCount) == totalItemCount) {

                        new loadComments().execute();
                        loading = true;
                    }

                }

                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {
                }
            }

How Can I also reset the variables in AbsListView so it understand the when I have reached the bottom of the listView?

A: After calling clear() on your Adapter, you must call adapter.notifyDataSetChanged(). Here is the snippet from the API:

public void notifyDataSetChanged()
Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.


text:
Q: Submitting POST request from Cordova app to Google App Engine not reaching server at all I have a Cordova app (HTML/Javascript-files wrapped into iOS WebView) which is exhibiting some weird behaviour.
I submit forms to  a python-script on Google App Engine, and this works sometimes, but not all the time. When the form includes base64 encodes images, it is more likely that the it won't work.
What I mean with not working is that it doesn't reach the server at all. The server logs show that no request to the "/submit"-handler has been made. This is only for the iOS-version of the app. The Android-version works fine with the same code.
My biggest suspicions was the cross-domain issue. Here's my jQuery code which sends the form:
$.ajax({
    type: 'POST',
    url: "http://myapp.appspot.com/submit",
    data: submittedEntryString,
    crossDomain: true,
    cache: false
}).done(function(data) {
    console.log(data);
}).fail(function(jqXHR, textStatus, errorThrown) {
    console.log(textStatus);
    console.log(errorThrown);
    console.log(jqXHR.responseText);
});

However I have added the header to my response. I suppose this is the correct way to do it(?)
self.response.headers['Access-Control-Allow-Origin'] = '*'
self.write("form submitted! form id is: " + str(s.form_id))

Any ideas what would cause this kind of behaviour?

A: The cross domain issue only occurs when you test your app code on PC browser after code below is inserted into config.xml.
<access origin="*" />

Anyway, your code seems to be correct.
My suggestion is that you could try the steps below.
(1) Not post your image and check if text data could be posted well.
(2) Use phonegap "Filetransfer" to post data includes images.


text:
Q: How to get bash to print the output without the fields with zero size when running smem command? Here is the 'smem' command I run on the Redhat/CentOS Linux system. I expect the output be printed without the fields with zero size however I would expect the heading columns.
 smem -kt -c "pid user command swap"
  PID User     Command                         Swap
 7894 root     /sbin/agetty --noclear tty1        0
 9666 root     ./nimbus /opt/nimsoft              0
 7850 root     /sbin/auditd                  236.0K
 7885 root     /usr/sbin/irqbalance --fore        0
11205 root     nimbus(hdb)                        0
10701 root     nimbus(spooler)                    0
 8446 trapsanalyzer1 /opt/traps/analyzerd/analyz        0
50316 apache   /usr/sbin/httpd -DFOREGROUN        0
50310 apache   /usr/sbin/httpd -DFOREGROUN        0
 3971 root     /usr/sbin/lvmetad -f           36.0K
63988 root     su -                               0
 7905 ntp      /usr/sbin/ntpd -u ntp:ntp -     4.0K
 7876 dbus     /usr/bin/dbus-daemon --syst    44.0K
 9672 root     nimbus(controller)                 0
 7888 root     /usr/lib/systemd/systemd-lo        0
63990 root     -bash                              0
59978 postfix  pickup -l -t unix -u               0
 3977 root     /usr/lib/systemd/systemd-ud   736.0K
 9016 postfix  qmgr -l -t unix -u                 0
50303 root     /usr/sbin/httpd -DFOREGROUN        0
 3941 root     /usr/lib/systemd/systemd-jo    52.0K
 8199 root     //usr/lib/vmware-caf/pme/bi        0
 8598 daemon   /opt/quest/sbin/.vasd -p /v        0
 8131 root     /usr/sbin/vmtoolsd                 0
 7881 root     /usr/sbin/NetworkManager --     8.0K
 8364 root     /opt/puppetlabs/puppet/bin/        0
 8616 daemon   /opt/quest/sbin/.vasd -p /v        0
23290 root     /usr/sbin/rsyslogd -n           3.8M
64091 root     python /bin/smem -kt -c pid        0
 7887 polkitd  /usr/lib/polkit-1/polkitd -        0
 8363 root     /usr/bin/python2 -Es /usr/s        0
53606 root     /usr/share/metricbeat/bin/m        0
24631 nagios   /usr/local/ncpa/ncpa_passiv        0
24582 nagios   /usr/local/ncpa/ncpa_listen        0
 7886 root     /opt/traps/bin/authorized      76.0K
 7872 root     /opt/traps/bin/pmd             12.0K
 8374 root     /opt/puppetlabs/puppet/bin/        0
 7883 root     /opt/traps/bin/trapsd          64.0K
----------------------------------------------------
   54 10                                       5.1M

A: Like this?:
$ awk '$NF!=0' file
  PID User     Command                         Swap
 7850 root     /sbin/auditd                  236.0K
...
 7883 root     /opt/traps/bin/trapsd          64.0K
----------------------------------------------------
   54 10                                       5.1M

But instead of using the form awk ... file you'd probably like to smem ... | awk '$NF!=0'.

A: Could you please try following, for extra precautions removing the space from last fields(in case it is there).
smem -kt -c "pid user command swap" | awk 'FNR==1{print;next} {sub(/[[:space:]]+$/,"")} $NF==0{next} 1'


text:
Q: Filling combobox with data from php database and Submit Hi guys I am trying to filling db from php mysql to combobox  its work to show data but i can't submit when i am trying to add value in the option. Column i want to show is LawGroup.

Here is code that show data

                        <select name="idlawgroup" id="custom-select" width="300" style="width: 300px">
                        <?php
                            $res=mysqli_query($link,"SELECT * FROM lawgroup");
                            while($row=mysqli_fetch_array($res))
                            {
                              ?>
                              <option><?php echo $row["NameLawGroup"]; ?> </option>
                              <?php
                            }
                              ?>

                        </select>
                        <?php echo $lawgroup_err;?>

And this is the code i want to add value

                        <select name="idlawgroup" id="custom-select" width="300" style="width: 300px">
                        <?php
                            $res=mysqli_query($link,"SELECT * FROM lawgroup");
                            while($row=mysqli_fetch_array($res))
                            {
                              ?>
                              <option value="$row["IDLawGroup"]"><?php echo $row["NameLawGroup"]; ?> </option>
                              <?php
                            }
                              ?>
                        </select>
                        <?php echo $lawgroup_err;?>

A: As @TheBoiYouLost pointed out in the comment section of the question, the problematic line is
<option value="$row["IDLawGroup"]"><?php echo $row["NameLawGroup"]; ?> </option>

Fix:
<option value="<?php echo $row["IDLawGroup"]; ?>"><?php echo $row["NameLawGroup"]; ?> </option>


text:
Q: How can I define A and B depending from each other typed class using refined library? Problem:
I have a case class Passenger, that starts from point A and goes to point B.
A valid passenger means that point A doesn't equal to point B.
Passenger(
  a: Int,
  b: Int
)

Question:
How can I design Passenger class using refind library to reach the goal?
I think Passenger should take two or one refined type parameters, something like:
    Passenger[A, B Refined NotEqual[A]](...)

Example:
I expect that the following code doesn't compile:
Passenger(42, 42)

And this compiles correctly:
Passenger(1, 42)


text:
Q: Cache list comprehension and processing results I have a list comprehension, which is created from a dictionary (about 1000 key-value pairs):
comprehension_result = [SomeObject(property_a=key, property_b=value) for key, value in some_dictionary.items()]

Then I have a list processing method processing_method, which iterates over the items in comprehension_result, performs some processing, and returns another list:
another_list = processing_method(comprehension_result)

The result of another_list is used in a class property, like:
# SomeClass.py

class SomeClass:
    ...
    some_property = another_list

The thing is, SomeClass can be instantiated many times at once, and the value of another_list is obtained on-the-fly, meaning that it is time consuming to create many instances of SomeClass.
I want to ask, is there a caching mechanism, or helper function in Python, which can store the value of another_list somewhere, so it is only calculated once, and all the instances can use that?


text:
Q: Fabric crashlytics for Android How can I enable Fabric Crashlytics in my app using Eclipse without using they Eclipse Plugin.
There reason why I ask is because, when I follow this proguard-dexguard steps for export my APK with Proguard. My App size does not reduce in size. as comparing when I used to use this :
proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt

But after enable Crashlytics I can not longer use the above line of code. I have to export as per web site says Export Crashlytics-enabled Android Application.
Any suggestions ?

A: try add below code in your proguard-project.txt
-keep class io.fabric.sdk.android.** { *; }
-keep interface io.fabric.sdk.android.** { *; }
-keep class com.digits.sdk.android.core.** { *; }
-keep interface com.digits.sdk.android.core.** { *; }
-keep class com.twitter.sdk.android.** { *; }
-keep interface com.twitter.sdk.android.** { *; }

-keep class io.fabric.** { *; }
-keep interface io.fabric.** { *; }
-keep class com.digits.** { *; }
-keep interface com.digits.** { *; }
-keep class com.twitter.** { *; }
-keep interface com.twitter.** { *; }
-keep class com.crashlytics.** { *; }
-keep interface com.crashlytics.** { *; }


text:
Q: ArrayList and List declaration So I started learning Java about a month ago. And there is this one thing that I can't quite put my finger on.
What is difference between
List<String> list1 = new ArrayList<>();

and
ArrayList<String> list2 = new ArrayList<>();

I get that in list1 declaration is done by using name of Array class and initialization by using name of ArrayList class, and in list2 declaration and intialization both are done by using name of ArrayList class. But what is the difference if there are any.
And even when I make object for inherited class and do the same thing, declaration using name of one class and initializing using name of other. Is there any difference apart form the fact that the code looks different??
Ps : Kinda new to all the terminology and learned most stuff from books, oracle website and stuff but not completely from one source so if i made any mistake please correct me :)

A: ArrayList is contained under the List interface. When you use ArrayList, you are adding more specification and using ArrayList methods.
See Polymorphism


text:
Q: delphi simulate fifo with TStringList i need to process a received data from a tcp link.the data are frames of hex string at length of 203 bytes.
i save them at the end of tstringlist
MyList.Add( input );

and from a second thread read the first string and process it and remove firs from the list
procedure TMyThread.Execute;
 var str : string;
begin
    while not Terminated do
    begin
      FTermEvent.WaitFor(100);
      if not Terminated then
      begin
          str := MyList[0];
          MyList.Delete(0);
          //some process
      end;
    end
end;

The question is , is this thread safe?!

A: If you are afraid to loose input data using database, you can try to use TThreadStringList.
I imagine that your software receives data from multiple devices simultaneously (and in this case you should create a  multi-thread socked to make you sure  to receive all the data) if you are receiving data from a single device instead , you should make sure that the tcp protocol supports a sort of aknowlage system to avoid losing data or at least to report in a log, the data that your application has not been able to receive completely.
Anyway, TThreadStringList is a simple wrapper for TStringList.
It should makes possible to access a String List from different threads without any conflicts.
I can't test it but for you should be easy and quick to try.
The link:
TThreadStringList


text:
Q: Exclude -ObjC from some files - Xcode I have added -ObjC to "Other linking flags" under Build Settings in my Xcode project to be able to use Admob in my application. But, when I try to install Google Analytics - i get an error like this:
_OBJC_CLASS_$_GAI", referenced from:
When i removed -ObjC from Other Linking Flags and removed the AdMob files, everything worked fine. My question is, is there a way to exclude the analytics files from being affected by -ObjC in other linking flags?

A: In Xcode, you can add compiler flags on a file-by-file basis.

*

*Open Xcode, and navigate to Project Editor > Build Phases > Compile Sources

*Hold the command key and select each file with which you'd like to flag.

*Double-click on the "Compiler Flags" portion (right-hand side) of the table

*Add the -ObjC flag.

*Compile!

Source: iOS Developer Library: Controlling How an Individual File is Compiled


text:
Q: How to create an Inner Shadow effect using Expression Blend I'm aware of the DropShadowEffect using blend, but I need the shadow to appear on the inside of the control giving it an internal recessed appearance.
Any ideas will be greatly appreciated.

A: here is a technique that uses a drop shadow with a clipping path to trim the outside edge leaving only the inner portion of the shadow
http://www.codeproject.com/KB/WPF/innershadows.aspx


text:
Q: "list indices must be integers or slices, not NoneType" Error I get an error when the board is filled and all spaces have been occupied and I don't know why?
Here's my code for where the error is:
def insertLetter(letter, pos):
    board[pos] = letter

A: The line edgesOpen = [] is indented too much, putting it inside the if 5 in possibleMoves: block (and after the return statement, making it dead code). Therefore edgesOpen is not defined. You need to remove one level of indentation from that line to fix the error.


text:
Q: DOMParser parseFromString method not working as expected I'm trying to use the DOMParser to parse a string of html as a document object. This is what I've done:

  let parser = new DOMParser();
  let url = document.getElementsByClassName("a-link-emphasis")[0].href;
  fetch(url)
    .then(response => response.text())
    .then(data => {
      let doc = parser.parseFromString(data, "text/xml");
      console.log(doc);
    })
    .catch(function(error) {
      console.log(error);
    });

I parse the response from the url as text so that the data variable is equal to the html source code of the page specified. It should be equal to a stringified version  of this page's source code. This is the console.log of the data variable:
image.
However when I try to parse this string with the parseFromString method, the variable doc is equal to the following html elements
<parsererror style="display: block; white-space: pre; border: 2px solid #c77; padding: 0 1em 0 1em; margin: 1em; background-color: #fdd; color: black">
This page contains the following errors:

error on line 1 at column 2: StartTag: invalid element name

Below is a rendering of the page up to the first error.
</parsererror>

Does anyone know what could be doing this?
Thanks very much for your help.


text:
Q: Laravel does not display validation errors when using $request->validate I am not able to display the validation errors on a specific form/page when using $request->validate($rules);. Here is the controller code:
public function store(Request $request) {

  $rules = [
    'dummy-field' => 'required|string',
  ];

  $params = $request->validate($rules);
  // $this->validate($request, $rules); // Same result with this

  dd($params);
}

In my view:
@if($errors->any())

    @foreach($errors->all() as $error)

{{ $error }}

    @endforeach

@endif

When I submit the form (without the dummy-field) I'm properly redirected back to the previous page (If my form would pass the validation I should see the dd output), but the error messages are not displayed. I also tried dd($errors) and the ErrorBag is actually empty.
The weird thing is, using a manual Validator the error messages are properly displayed. Refactoring the controller to:
$rules = [
  'dummy-field' => 'required|string',
];

$validator = Validator::make($request->all(), $rules);

if ($validator->fails()) {
  return redirect()->back()->withErrors($validator);
}

dd($validator);

I see the error messages.
I really can't understand this behaviour. I'm using $request->validate() for other forms in my app and I don't have any trouble.
I'm using laravel 8.
Does someone have any idea why something like this could happen?

A: I finally found a solution. Posting it here in case it may help someone.
The problem lies in the cookie session driver
The browser has a maximum size for a cookie (around 4k I think, but it may vary). When using $request->validate(), the redirect will put into the session both the errors and the input. If the input is long enough (in my case I had some textarea with ~300 characters text), the cookie will exceed the maximum size and the browser will ignore it, so Laravel will not be able to retrieve the errors from the session.
I can't use the file driver because my application is distributed across multiple servers beyond a load balancer, so I resolved everything using the redis driver.


text:
Q: With React / Redux, is there any reason not to program the store globally? I love Redux, but to use it, I have LOTS of additional code scattered all over my application: connect, mapDispatchToProps, mapStateToProps etc etc
It appears to me however that I should be able to both dispatch to the store and get any value from the store via a global window level reference to the store object.  If I did this, it would cut alot of code out of my application.
So the question is, what is wrong with this approach?  Why NOT do all my Redux disptach and state access via window.store?

A: I wrote a long Reddit comment a while back about why you should use the React-Redux library instead of writing store code by hand.
Quoting the main part of that answer:

First, while you can manually write the code to subscribe to the Redux store in your React components, there's absolutely no reason to write that code yourself.  The wrapper components generated by React-Redux's connect function already have that store subscription logic taken care of for you.
Second, connect does a lot of work to ensure that your actual components only re-render when they actually need to.  That includes lots of memoization work, and comparisons against the props from the parent component and the values returned by your mapStateToProps function for that component.  By not using connect, you're giving up all those performance improvements, and your components will be unnecessarily re-rendering all the time.
Third, by only connecting your top-level component, you are also causing the rest of your app to re-render unnecessarily.  The best performance pattern is to connect lots of components in your app, with each connected component only extracting the pieces of data it actually needs via mapStateToProps.  That way, if any other data changes, that component won't re-render.
Fourth, you're manually importing the store into your components, and directly coupling them together, thus making it harder to test the components.  I personally try to keep my components "unaware" of Redux.  They never reference props.dispatch, but rather call pre-bound action creators like this.props.someFunction().  The component doesn't "know" that it's a Redux action creator - that function could be a callback from a parent component, a bound-up Redux action creator, or a mock function in a test, thus making the component more reusable and testable.
And finally, the vast majority of apps built using React and Redux use the React-Redux library.  It's the official way to bind the two together, and doing anything else will just confuse other developers looking at your project.

Also, per the Redux FAQ entry on importing the store directly:

While you can reference your store instance by importing it directly, this is not a recommended pattern in Redux. If you create a store instance and export it from a module, it will become a singleton. This means it will be harder to isolate a Redux app as a component of a larger app, if this is ever necessary, or to enable server rendering, because on the server you want to create separate store instances for every request.

Summarizing all that:

*

*Better performance

*Lower coupling via dependency injection of the store

*Better testability

*Better architecture

I'd also suggest you read through my two-part post The Tao of Redux, Part 1 - Implementation and Intent, and The Tao of Redux, Part 2 - Practice and Philosophy.  These two posts discuss the history and intent behind Redux's design, how it's meant to be used, why common usage patterns exist, and other ways that people may use Redux.


text:
Q: How effective is the Turbocharger for the Devotion LMG? So the tooltip apparently states:

Reduces autofire spin-up time for compatible weapons.

I have only had one match where I even found this hop-up for the LMG, but still couldn't find a Deovtion LMG anywhere to test it out.  It's a Legendary rarity hop-up so it's probably rare enough to not be found commonly.
I'm wondering how effective this attachment actually affects the Devotion LMG.  To start with, the gun already has a painfully long spool up time before max fire rate is reached, so I'm wondering if it's even worth getting this attachment when it means sticking with the Devotion long enough to hopefully find it through the course of the match.

A: Very effective. I have found both the Devotion and the exotic (there is also a legendary one, which is less effective) attachment in several matches. It removes perhaps 90% of the spin up time, making the weapon extremely effective. It basically feels like it is firing at full speed right a trigger pull.
I would highly recommend using this if available.
The main problem when using the Devotion with the turbocharger is ammo since the fire rate is so high. Compounding this issue is that energy ammo can be hard to find. I would suggest having at least 100 rounds to feel safe using this, as running out of ammo is very easy with this attachment and has been the main problem I faced.


text:
Q: EXT4-fs error (device loop0) ext4_mb_generate_buddy I've been randomly getting theses in my /var/log/messages
[5747511.945300] EXT4-fs error (device loop0): ext4_mb_generate_buddy: EXT4-fs: group 1: 29505 blocks in bitmap, 29455 in gd

Not had any luck with google is this a drive failue or just a kernel glitch or a need to fsck?
kernel:
2.6.32-320.4.1.lve1.1.4.el6.x86_64 #1 SMP Wed Mar 7 06:32:27 EST 2012 x86_64 x86_64 x86_64 GNU/Linux

the DC i think gave me a new drive over a few months ago

A: This was a kernel bug. I've updated to kernel 3.0.57 from elrepo and it's all working fine now.

A: I my case the SD card of my Bananapi was corrupt (and the root filesystem was readonly).
I fixed that with fsck.


text:
Q: How to make Xcode automatically conform to a protocol When I use a prototype table view, I always have to conform to the protocol TableViewDataSource. I always forget what methods I need to implement, so I have to look at the source of the protocol every time. This is really time consuming.
I think Xcode must have a feature that automatically implements the needed methods for you, right? Just like IntelliJ IDEA, Eclipse, and Visual Studio.
I want to know where can I find this feature. If there's isn't, is there a workaround for this? At least I don't have to open the source code of the protocol each time I conform to it.
If you don't understand what I mean, here's some code:
I have a protocol
protocol Hello {
    func doStuff ()
}

When I conform to it,
class MyClass: Hello {

}

I often don't remember the names of the methods that I need to implement. If Xcode has a feature that turns the above code, into this:
class MyClass: Hello {
    func doStuff () {
        code
    }
}

Now you understand what I mean? I just want to ask where to find such a feature.

A: Well if i understood your problem then here is a workaround:
try to define methods with protocol as prefix like here hello then you'll not have to remember the methods just start typing protocol name and XCODE will prompt you with all available methods see here:

And if you want autocomplete protocol try
Snippets

A: Xcode 9, takes care of implementation of mandatory methods of Swift Datasource & Delegates.
Look at these snapshots, with example of UICollectionViewDataSource:
Indicating warning to implement protocol methods:

By clicking on 'Fix' button, it has added all mandatory methods:

A: Very similar to Amjad's post, Xcode 9/10 brings the functionality to add missing protocol requirements right from within the code editor.
Just "right click" on the class name: "Refactor" --> "Add Missing Protocol Requirements"

A: Xcode 9 : you can add missing Protocol Requirements by add new shortcut to your Key Bindings Set

*

*From the top Xcode menu (top left) choose Preferences.

*Choose Key Binding.

*Search about protocol. you will find Command called Refactor -> Add Missing Protocol Requirements

*Press on Key column then add your shortcut. ex: cmd + shift + M
Now you can add missing Protocol Requirements by clicking on class name name (or his extension) then press your shortcut

A: Xcode won't do it for you.
If you look at the documentation for the protocol, it's clearly marked which functions you have to implement:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDataSource_Protocol/


text:
Q: Is it possible to specify the function type using -> I have following method definition, which works.
public static String runFunction2(Function<String,String> function, String input) {
    return function.apply(input);
}

But I want to specify the function type explicitly like Scala does:
public static String runFunction(String -> String function, String input) {
    return function.apply(input);
}

There is compiling error in the above code, Does Java 8 not support this snytax?

A: No.  Java doesn't support that syntax.  In fact, Java doesn't have any special syntax for function types1.
Java function types are a kind of Java interface type, and you need to use the same syntax that you use when using any interface type.
Java only has special syntax (for example lambdas and method references) for expressing function values.

1 - It is not impossible that a future Java version might, but I wouldn't hold my breath waiting ...


text:
Q: Can this multi-tree data structure update in O(log(n)) instead of O(n)? Consider a doubly linked multi-tree data structure that relates strings with arrays of strings.
Property 1: A string can belong to zero or more collections S of strings, i.e. belongsTo: string => Array<S<string>>.
For example, the strings 'a', 'b', 'c', 'd', and 'x' could be related to the collections S(), S('a'), S('x'), S('a', 'b'), and S('a', 'b', 'c') such that each of the following expressions returns true.
belongsTo('a') // [S()]
belongsTo('x') // [S()]               both 'a' and 'x' belong to S()
belongsTo('b') // [S('a'), S('x')]    'b' belongs to both S('a') and S('x')
belongsTo('c') // [S('a', 'b')]
belongsTo('d') // [S('a', 'b', 'c')]

Note that a string can belong to many collections S, and a collection S can have many strings which belong to it.
Property 1.1: belongsTo ignores case and order:
belongsTo('c') // S('a', 'b')
belongsTo('C') // S('a', 'b')

Property 1.2: belongsTo is O(1)
Property 2: contains returns an array of strings that belong to the given collection S:
contains(S()) // ['a', 'x']
contains(S('a')) // ['b'])
contains(S('a', 'b')) // ['c'])
contains(S('a', 'b', 'c')) // ['d']
contains(S('x')) // ['b']

Property 2.1: contains ignores case and order
contains(S('a', 'b')) // ['c']
contains(S('A', 'B')) // ['c']
contains(S('b', 'a')) // ['c']

Property 2.2: contains is O(1)
The above can be accomplished simply with something like the following:
const hashString = s => s.toLowerCase()
const hashArray = arr => sort(arr.map(hashString).concat()).join('_')

const stringIndex = {
  [hashString('a')]: [[]],
  [hashString('b')]: [['a'], ['x']],
  [hashString('c')]: [['a', 'b']],
  [hashString('d')]: [['a', 'b', 'c']],
  [hashString('x')]: [[]]
}

const sIndex = {
  [hashArray([])]: ['a', 'x'],
  [hashArray(['a'])]: ['b'],
  [hashArray(['a', 'b'])]: ['c'],
  [hashArray(['a', 'b', 'c'])]: ['d'],
  [hashArray(['x'])]: ['b']
}

// getters
const belongsTo = s => stringIndex[hashString(s)]
const contains = arr => sIndex[hashArray(arr)]

// others
const adjacent = (arr, s) => arr.concat(s)
const addTo = (arr, s) => { /* adds a string to a collection */ }
const update = (arr, old, new) { /* replace a string in a collection */ }

Here's the downside. update(arr) (defined above) takes O(descendants(arr).length), where descendants are all of the strings that a given collection contains, and all of the strings that the adjacent collections contain, and all of the strings that the adjacent collections to the adjacent collections contain, etc. (Adjacency here is a similar concept to children, but this is not a tree.)
As soon as I try to abstract away the strings into ids, I lose the hashing functionality that preserves properties 1.1 and 1.2 (unordered and case-insensitive).
Is there a way to do update in O(1) or O(log(n)) instead of O(descendants)?


text:
Q: jquery's Ajax calls and response time on links while remote site's long to answer I have a problem with an async call using jquery (ajax, load, get, post). While I wait for the remote site to answer I can't navigate my links until the remote web site either answers or times out.
If I click a link to an external web site (google for example) the page switches right away. I've tried this on my local IIS, windows 2008 IIS7 and the web server that comes with VS2008.
To reproduce copy the following code and change the proxy page to one of your own and make it wait for a long time (or you might want to try the following web service as it takes forever to answer: http://www.webservicex.net/globalweather.asmx/GetWeather?CityName=Inuvik&CountryName=Canada). You'll need to use a proxypage because you can't make remote ajax calls).
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <title>Test</title>

            go google

            go this page

            go home page

AjaxProxy.aspx => is a proxy paeg that is used to return the response of the rmote page
AjaxDelay.aspx => is the simulated remote service/page with an added delay of 10 seconds (d=10) to simulate a very slow remote site/service
Edit: Added AjaxProxy content and AjaxDelay content (both pages are in asp.net 2.0 with nothing in the aspx page)
AjaxProxy
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Request.QueryString.Count = 0 Then Response.Write(" ") : Exit Sub

    Dim Url As String = HttpUtility.UrlDecode(Request.QueryString().ToString)
    Dim req As HttpWebRequest = WebRequest.Create(Url)
    Dim res As HttpWebResponse = req.GetResponse
    Dim sreader As StreamReader = New StreamReader(res.GetResponseStream)
    Dim myhtml As String = sreader.ReadToEnd
    sreader.Close()
    res.Close()
    If Url.EndsWith(".xml") Then
        Response.AddHeader("Content-type", "application/xml")
    End If
    Response.Write(myhtml)
End Sub

AjaxDelay
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim Del As Integer = 2
    If String.IsNullOrEmpty(Request("d")) = False Then
        Integer.TryParse(Request("d"), Del)
        If Del = 0 Then Del = 2
    End If

    Del = Del * 1000
    Threading.Thread.Sleep(Del)
    Response.Write(String.Format("Delayed for {0} seconds", Del / 1000))
End Sub

A: Well if the Server that contains the Proxy is located on the local machine that is also making the ajax requests it could be possible that the proxy is doing something to halt the computer processing itself.  Have you looked for deficiencies in the proxy code that could cause major blocking?
When you say

windows 2008 IIS7

Is that on a remote machine or is that the local OS/IIS?
Just an additional.. That webservice call returns extremely fast for me.
Edit:
I could not duplicate this with FF3, Chrome, IE6/7
I tried with the following code, it didn't matter what I put in as a substitute url.

Proxy:
using System;
using System.Web;

public class PageProxy : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
            if (context.Request.QueryString["d"] != null)
                System.Threading.Thread.Sleep(10000);

            byte[] externalPage = new System.Net.WebClient().DownloadData(context.Request["externalURI"]);
            context.Response.OutputStream.Write(externalPage, 0, externalPage.Length);
            context.Response.End();
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
}

A: This works fine for me in Firefox 3.1 and IE8. I replaced the URL with a ColdFusion page that takes 15 seconds to render. I changed the "go this page" link to:
go this page

And actually created that file (empty).


text:
Q: Invalid 'where' condition. An entity member is invoking an invalid property or method. Error on LINQ Query I am running a linq query against CRM 2011 and I keep getting this error:
Invalid 'where' condition. An entity member is invoking an invalid property or method.
My code looks like this:
        try
        {

            string rsmName = "Bob Harrison";
            var linqQuery = (from r in gServiceContext.CreateQuery("opportunity")
                             join c in gServiceContext.CreateQuery("account") on ((EntityReference) r["accountid"]).Id equals c["accountid"] into opp
                             from o in opp.DefaultIfEmpty()
                             where ((EntityReference)r["ownerid"]).Name.Equals(rsmName)
                             select new
                                        {
                                            AccountId = !r.Contains("accountid") ? string.Empty : r["accountid"],
                                            Account = !o.Contains("name") ? string.Empty : o["name"]
                                        });

            ddlCustomer.DataSource = linqQuery;
            ddlCustomer.DataValueField = "AccountId";
            ddlCustomer.DataTextField = "Account";
            ddlCustomer.DataBind();
        }
        catch (Exception ex)
        {
        }

Any idea how to fix this?
Thanks!

A: It looks CRM Linq provider has a limited capabilities and the query is too complex. Try to use FetchXml.

A: The problem isn't the Linq provider, but an issue with EntityReferences. There's unforunately no documentation on it, but my best guess is that since there's no constructor for EntityReference that takes a name, it is ordinarily null unless it's otherwise populated.
But anyway, this can still be done via linq the same way it would be done via fetchxml - by querying the SystemUser table. See below (you'll have to translate to late-binding).
var linqQuery = from r in gServiceContext.OpportunitySet
                join c in gServiceContext.AccountSet on r.AccountId.Id equals c.AccountId into opp
                from o in opp.DefaultIfEmpty()
                where o.OwnerId.Id == gServiceContext.SystemUserSet.Single(y => y.FullName.Equals(rsmName)).SystemUserId
                select new
                {
                    AccountId = !r.Contains("accountid") ? string.Empty : r["accountid"],
                    Account = !o.Contains("name") ? string.Empty : o["name"]
                };


text:
Q: pyqt5 - worker class doesn't emit to main thread I want to write a simple server/client chat application.
On the client side I create a thread and listen to message from server and when I receive message I call updateChatHistory function to append message to a QPlainTextEdit object in gui.
But the worker class never emits to main thread
class Ui_MainWindow(object):
    ...

    def updateChatHistory(self, text):
        print(text)
        self.worker = WorkerThread(text)
        self.worker.finishSignal.connect(self.appendToChatHistory)
        self.worker.start()

    def appendToChatHistory(self, text):
        # nothing prints and this function will not be called
        print('test', text)
        self.chatHistory.appendPlainText(text)

    # I call this method in setupUi function
    def connect_to_server(self):
        self.sckt = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
        self.sckt.connect((socket.gethostname(), self.port))

        t = threading.Thread(target=self.listen_for_message)
        t.daemon = True
        t.start()

    def listen_for_message(self):
        while True:
            msg = self.sckt.recv(1024).decode('utf-8')
            self.updateChatHistory(msg)

    ...

class WorkerThread(QThread):
    finishSignal = QtCore.pyqtSignal(str)

    def __init__(self, text):
        super(WorkerThread, self).__init__()
        self.text = text

    def run(self):
        self.finishSignal.emit(self.text)

I also tried without using worker class but I get this Error and I can't append anymore.
QObject::connect: Cannot queue arguments of type 'QTextBlock'
(Make sure 'QTextBlock' is registered using qRegisterMetaType().)
QObject::connect: Cannot queue arguments of type 'QTextCursor'
(Make sure 'QTextCursor' is registered using qRegisterMetaType().)

EDIT: added extra code for cleararity


text:
Q: Docker container not showing files in the shared volume I hope someone can help me to locate the issue. I created a SQL Server 2019 container using this code:
docker run --name SQL19 -p 1433:1433 -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=zzzzz258*" -v /SqlDockerVol/userdatabase:/userdatabase -v /SqlDockerVol/sqlbackups:/sqlbackups -d mcr.microsoft.com/mssql/server:2019-lates

The problem I am having is the container not showing the files I saved in the /sqlbackups folder.
I am using Ubuntu 20.04.
I logged into the SQL19 container like this:
docker exec -it  SQL19 /bin/bash

then issued ls sqlbackups to confirm.
Do I need to set any permission on the host folder. I am not familiar with Linux.
Thanks

A: I suspect you need to pass absolute path to your folder:
/SqlDockerVol/userdatabase

is it full absolute path?
If it is relative change it to:
$(pwd)/SqlDockerVol/userdatabase

Please check this Docker shared folder with Linux
And technically you need something like:
docker run --name SQL19 -p 1433:1433 -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=zzzzz258*" -v $(pwd)/SqlDockerVol/userdatabase:/userdatabase -v $(pwd)/SqlDockerVol/sqlbackups:/sqlbackups -d mcr.microsoft.com/mssql/server:2019-lates


text:
Q: MuleSoft deployment failing using maven I am trying to deploy a flow I created in Anypoint Studio to CloudHub using maven. I have my pom.xml configured as best as I can tell:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>capgemini</groupId>
    <artifactId>maven-test</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>mule</packaging>
    <name>Mule maven-test Application</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

        <mule.version>3.9.0</mule.version>
        <mule.tools.version>1.2</mule.tools.version>
        <cloudhub.domain>mydomain</cloudhub.domain>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.mule.tools.maven</groupId>
                <artifactId>mule-app-maven-plugin</artifactId>
                <version>${mule.tools.version}</version>
                <extensions>true</extensions>
                <configuration>
                    <copyToAppsDirectory>true</copyToAppsDirectory>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>build-helper-maven-plugin</artifactId>
                <version>1.7</version>
                <executions>
                    <execution>
                        <id>add-resource</id>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>add-resource</goal>
                        </goals>
                        <configuration>
                            <resources>
                                <resource>
                                    <directory>src/main/app/</directory>
                                </resource>
                                <resource>
                                    <directory>src/main/api/</directory>
                                </resource>
                                <resource>
                                    <directory>mappings/</directory>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.mule.tools.maven</groupId>
                <artifactId>mule-maven-plugin</artifactId>
                <version>2.2.1</version>
                <configuration>
                    <deploymentType>cloudhub</deploymentType>
                    <muleVersion>3.9.0</muleVersion>
                    <username>myusername</username>
                    <password>mypassword</password>
                    <applicationName>circleci-maven</applicationName>
                    <redeploy>true</redeploy>
                    <target>Cloudhub</target>
                    <domain>${cloudhub.domain}</domain>
                    <targetType>server</targetType>
                    <environment>Development</environment>
                </configuration>
                <executions>
                    <execution>
                        <id>deploy</id>
                        <phase>deploy</phase>
                        <goals>
                            <goal>deploy</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-deploy-plugin</artifactId>
                <configuration>
                    <skip>true</skip>
                </configuration>
        </plugin>
        </plugins>
    </build>

    <!-- Mule Dependencies -->
    <dependencies>
        <dependency>
            <groupId>org.jfrog.maven.annomojo</groupId>
            <artifactId>maven-plugin-anno</artifactId>
            <version>1.4.1</version>
        </dependency>
        <!-- Xml configuration -->
        <dependency>
            <groupId>com.mulesoft.muleesb</groupId>
            <artifactId>mule-core-ee</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
        <!-- Xml configuration -->
        <dependency>
            <groupId>com.mulesoft.muleesb.modules</groupId>
            <artifactId>mule-module-spring-config-ee</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
        <!-- Mule Transports -->
        <dependency>
            <groupId>org.mule.transports</groupId>
            <artifactId>mule-transport-file</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.mule.transports</groupId>
            <artifactId>mule-transport-http</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.mulesoft.muleesb.transports</groupId>
            <artifactId>mule-transport-jdbc-ee</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.mulesoft.muleesb.transports</groupId>
            <artifactId>mule-transport-jms-ee</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.mule.transports</groupId>
            <artifactId>mule-transport-vm</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
        <!-- Mule Modules -->
        <dependency>
            <groupId>org.mule.modules</groupId>
            <artifactId>mule-module-scripting</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.mule.modules</groupId>
            <artifactId>mule-module-xml</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
        <!-- for testing -->
        <dependency>
            <groupId>org.mule.tests</groupId>
            <artifactId>mule-tests-functional</artifactId>
            <version>${mule.version}</version>
            <scope>test</scope>
        </dependency>
    <dependency>
            <groupId>org.mule.modules</groupId>
            <artifactId>mule-module-http</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
    <dependency>
            <groupId>org.mule.modules</groupId>
            <artifactId>mule-module-spring-config</artifactId>
            <version>${mule.version}</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <repositories>
          <repository>
            <id>Central</id>
            <name>Central</name>
            <url>http://repo1.maven.org/maven2/</url>
            <layout>default</layout>
        </repository>
        <repository>
            <id>mulesoft-releases</id>
            <name>MuleSoft Releases Repository</name>
            <url>http://repository.mulesoft.org/releases/</url>
            <layout>default</layout>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>mulesoft-release</id>
            <name>mulesoft release repository</name>
            <layout>default</layout>
            <url>http://repository.mulesoft.org/releases/</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

</project>

And I keep getting the following error:
[INFO] No application configured. Using project artifact: C:\workspace\maven-test\target\maven-test-1.0.0-SNAPSHOT.zip
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 11.383 s
[INFO] Finished at: 2018-07-03T10:33:29-04:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.mule.tools.maven:mule-maven-plugin:2.2.1:deploy (default-cli) on project maven-test: Execution default-cli of goal org.mule.tools.maven:mule-maven-plugin:2.2.1:deploy failed.: NullPointerException -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException

I have tried changing things around but can't seem to find anything that works or a detailed explanation of how to get the thing to work. Can someone please tell me what I am missing?

A: There are a few things wrong here. target, targetType and domain are not applicable for CloudHub deployments via the mule-maven-plugin, and you need to provide some more info (like workerType) Make sure you specify businessGroup as well. Here's an example of a configuration that has yielded a successful deployment for me in the past:
<plugin>
  <groupId>org.mule.tools.maven</groupId>
  <artifactId>mule-maven-plugin</artifactId>
  <version>2.2.1</version>
  <configuration>
    <skip>false</skip>
    <deploymentType>${deployment.type}</deploymentType>
    <muleVersion>${mule.version}</muleVersion>
    <username>${username}</username>
    <password>${password}</password>
    <applicationName>${application.name}</applicationName>
    <environment>${arm.environment}</environment>
    <businessGroup>${business.group}</businessGroup>
    <region>${region}</region>
    <workerType>${worker.type}</workerType>
    <workers>${workers}</workers>
    <redeploy>${redeploy}</redeploy>
    <properties>
      <env>${mule.env}</env>
      <vault.key>${vault.key}</vault.key>
    </properties>
  </configuration>
  <executions>
    <execution>
      <id>deploy</id>
      <phase>deploy</phase>
      <goals>
        <goal>deploy</goal>
      </goals>
    </execution>
  </executions>
</plugin>

You can replace the placeholders with your values. Information on what all these fields are can be found here in the documentation.


text:
Q: Using the Factory Pattern in PHP and Laravel Should a factory be responsible for finding models as well as creating them?
for example:
If i had a product model, should its factory have methods such as:
$product = $productFactory->findByID(32);

$product = $productFactory->all();

$product = $productFactory->findByName($productName);

$product = $productFactory->create($data);

A: Well, actually the Factory Pattern is a creational pattern which uses factory methods to deal with the problem of creating objects even without specifying a staic class, which means it create objects dynamically at the run-time. This pattern is used to deal with object creation mechanisms which lets a client class to to use a dynamic class built on run time. This pattern uses a factory method (abstract) and this method builds objects using other classes/objects depending on the request of the client class that uses the built object. Well, it's a broad thing, anyways.
Instead of thinking in design-patterns such as which pattern you should follow, try to find out the use case of your class and use them accordingly. Most probably you meant Model as classes which extends Eloquent ORM and in this case your model classes already have those methods if you extended the Eloquent ORM so you don't need to create those in your classes but to separate the business logic and DB layer you may use normal classes where you may use those classes as dependencies to call methods from your database layer classes. probably it sounds confusing anyways.
It depends on you how do you organize your directory structure but only think about SoC and that's  enough to get the idea, for a clean application architectural pattern. Don't think too deep in design patterns, instead think of a clean application model, that's it. Probably this article may help you a little bit (Specially discussed using Laravel and Repository Pattern).
For Factory Pattern, you may check this simple but helpful article.


text:
Q: sumproduct among dataframes I have 2 dfs:
df1:       0   1
       B   B0  B1
       S   S0  S1

df2:       B   S
      3    B3  S3
      4    B4  S4
      5    B5  S5

I am unsuccesfully trying to obtain new values for B and S which are a sumproduct of each row in df2 by its corresponding row in df1.
The desired output im looking for is :
               B                S
      3    B3*B0+S3*B1     B3*S0+S3*S1
      4    B4*B0+S4*B1     B4*S0+S4*S1
      5    B5*B0+S5*B1     B5*S0+S5*S1

The main problem im having is how to reference the corresponding indices (B or S) in df1 with the columns (B or S) in df2.
We consider that df2 has higher dimensions than df1

A: That's basically matrix-multiplication between the second and transpose of the first -
df2.dot(df1.T)

Sample run -
1) Inputs :
In [100]: df1
Out[100]:
   0  1
0  7  5
1  2  8

In [101]: df2
Out[101]:
   0  1
0  6  5
1  1  5
2  6  6

2) Get outputs using expression posted in the question :
# First col of output using the expression used in the question
In [102]: df2.iloc[:,0]*df1.iloc[0,0] + df2.iloc[:,1]*df1.iloc[0,1]
Out[102]:
0    67
1    32
2    72
dtype: int64

# Second col of output using the expression used in the question
In [103]: df2.iloc[:,0]*df1.iloc[1,0] + df2.iloc[:,1]*df1.iloc[1,1]
Out[103]:
0    52
1    42
2    60
dtype: int64

3) Verify using proposed one :
# Using proposed method
In [104]: df2.dot(df1.T)
Out[104]:
    0   1
0  67  52
1  32  42
2  72  60


text:
Q: как создать карту для игры, scroll во все стороны, kotlin android? создаю настольную игру и хочу создать карту больше экрана.. как её сделать, что использовать? чтобы можно было по ней перемещаться как в google картах по горизонтали, вертикали, диагонали и взаимодействовать с объектами на карте, изменять их..  хочу по типу плоского шара, т.е. если долго скролить вправо, то приходим снова на то же место где и были и т.д.

A: Android Studio создана для создания приложений и в связи с этим не имеет никаких удобных возможностей для создания игр.
Для лёгкого и удобного процесса осуществления вашей цели нужно использовать среду разработки игр, например, Unity (используется язык C#).


text:
Q: CORS issue vue/express/axios I have a VueJS app consuming an ExpressJS api. Attempting to hit an express route from the front end landing page form to send a "Contact Us" email via SendGrid but getting a proxy error in production on heroku.
here is the method in my component:
 async sendContactMessage() {
      console.log('email valid? ', this.validateEmail(this.contactEmail))
      if (!this.validateEmail(this.contactEmail)) {
        this.contactNotice = "Please enter a valid email."
      }

      else if (this.contactMessage.length < 10) {
        this.contactNotice = " The message is too short"
      } else {
        await MailersService.sendMessage({
          email: this.contactEmail,
          message: this.contactMessage
        })
        this.showContact = false
      }
    },

here is the api call in MailersService:
sendMessage (params) {
    let response = axios.post('/contacts/question', params)
    if (response.status === 200) {
      return response.data;
    }
  }

on the Express side, here is the route I am posting to:
router.post('/question', async (req, res, next) => {
  console.log('in Express, sending mail from contact form. this is request: ', req)
  let newMessage = req.body
  console.log("new message object is: ", newMessage)
  const msg = {
    to: 'contact@companydomain.com',
    from: req.body.email, // Use the email address or domain you verified above
    subject: 'Message from Beta Signup Form',
    text: req.body.message
  };
  await sgMail.send(msg);

  res.json({
    success: true, message: 'ok'
  });   // respond back to request
});

in app.js for cors, I have:
app.use(cors());
app.use( function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
})

This works locally, but on Heroku, it throws the error:
Access to XMLHttpRequest at 'https://...-api.herokuapp.com/api/contacts/question' from origin 'https://....com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.


text:
Q: Elevation issue password always wrong? ubuntu Newbie - I install OS using one account and then later created a second account made administrator with auto login and no password, then I logged in using new account and deleted old account. Now when ever I go to do anything it wants elevation and no matter what you type in the password field wont work. Any suggestions outside of scrapping it and installing Windows?

A: You are going to need add the new user to the "sudoers" file (or the admin group).  You are  probably running into a situation where this new user doesn't have permission to run the "sudo" command.
You are going to need to get to a root shell. This link will show you how:
http://www.psychocats.net/ubuntu/resetpassword/
That ^ is for resetting a password, but it describes how to get to the root prompt.
Once you have your root promt you can refer to this link:
How can I add a new user as sudoer using the command line?
More specifically (from said post):
sudo adduser <username> admin

Then reboot the machine:
init 6

Run that ^ at the root prompt.  Let it boot normally, log in as the "new" user and give it a shot.  You should be able to "elevate" (sudo) now.


text:
Q: Visual Latex Editor on Mac I am looking for visual Latex editor (Something like Microsoft Word). Is there any helpful.
The reason why I am looking for one is that I am tied to a deadline and I don't have enough time to get adapted with scripting language of Latex.
Most of visual editors are not available under Mac OS (Based on this List ), Can anyone help finding one with double interfaces (Scripting and visual).


text:
Q: Doctrine - I'm getting Entity class instead of Repository class I create instance of entity manager
$this->em = Connection::MainMySql()->GetEntityManager();

After some queries I try to get object from a Repository class.
$usersArray = $this->em->createQueryBuilder()
                        ->select("us")
                        ->from('Model\Repo\mytables\User', "us")
                        ->where("us.idUser = :idUser")
                        ->setParameter("idUser", $idUser)
                        ->getQuery()
                        ->execute();

Why do I then get list of objects of class Model\Entity\mytables\User instead of Model\Repo\mytables\User even after I specify desired class in from(...) section?

A: In fact, a repository cannot be used as a representation of a database entry.
In other words, Repositories should contain methods to retrieve/create/update/delete database entries represented by entities.
This is why the EntityManager is called Entity Manager, it manages Entities and not Repository classes.
For instance, you can perfectly do:
// Return an instance of the Repository Model\Repo\mytables\User
$repository = $this->em->getRepository('Model\Entity\mytables\User');

// The repository is used to create the QueryBuilder, so the from statement is already filled by doctrine as model\Entity\mytables\User
$query = $repository->createQueryBuilder('u')
// ...

This is also why you can do:
$repository = $this->em->getRepository('Model\Entity\mytables\User');
// Return all entries of the 'users' table as Model\Entity\mytables\User instances
$users = $repository->findAll();

I'm surprised that the from statement of your query doesn't produce an error such as "Model\Entity\mytables\User is not a valid entity".
Also, your structure looks confusing, you must differentiate properly Repositories (the Models) from Entities in order to use them according to their respective roles.


text:
Q: JHipster module hooks error Context:
I have a jhipster project for whom I installed some jhipster modules (yeoman generators) that should behave as post-entity hooks. One of the jhipster modules is not created by me, it is actually jhipster-entity-audit. I first ran yo jhipster-entity-audit, which succedeed and created the .jhipster\modules\jhi-hooks.json file.
Problem: When I run the jdl importer, as new entities are being created, I am expecting to see jhipster-entity-audit executing for each newly create entity as it should behave as a post entity hook. Instead, I am receiving this output:

Mentions:
I surely do have jhipster-entity-audit generator installed. I tried installing it through many methods, with Yarn/Node (local and/or global).
I would really appreciate some suggestions about how to solve this issue, and also, optional questions if I have not succeeded to provide all the information needed for you to be able to help me.

A: answer : this is not a bug, it's not supported yet.
You may use it in several steps though :

*

*yo jhipster

*yo jhipster:import-jdl

*yo jhipster-entity-audit

*yo jhipster:entity EntityName

*Repeat step 4 for each entity (and probably in the correct order, I don't remember the requirement of this module)...

details :
jhipster:import-jdl doesn't support post hook for the moment. It's not as simple as it running several times the entity generator and his hook. The context is not the same.
You'll have to wait until it does.
I have similar problems with the module I coded : https://github.com/bastienmichaux/generator-jhipster-db-helper/issues/46
I intend to solve this problem by calling the entity generator myself but it is because my module has a similar function as the jdl importer. And when I'll have done so, we'll see how we can integrate it into the jdl importer. So we're talking about 2 months or something like that.


text:
Q: C# Singleton-Pattern not working as expected after implementing parallel instead of concurrent processing Disclaimer: I know about questions like Thread Safe C# Singleton Pattern, however these do not answer my question.
Let me state my problem by first describing my C# project:
I have a class JobProcessor that accepts an object of the class JobTicket, which holds information about "what to do". The JobProcessor uses the Facade Pattern to coordinate other classes according to the Parameters in JobTicket, such as e.g. the path to a .log file about that very Job. For that I have a Singleton class Logger, for which the JobProcessor set the path at the start of the Job and then every other class would just call Logger.Log(message). This worked fine until I got to the point to implement parallelization with a class JobManager that accepts objects of the class JobTicket and saves them in a queue. The JobManager instantiates a new JobProcessor with a JobTicket from its queue. And that with up to 4 in parallel.
Now you can already imagine what happened: If more than one JobProcessor runs at once, one overwrites the path of the Logger. How can I make sure that the Logger is contained inside the JobProcessor without changing a lot of code? I thought about having a Logger field in the JobProcessor class, but then I have to pass it down to every other class that wants to use it, since by the Facade pattern the facade knows every class it uses, but every class that is used by it does not know the facade.
In hindsight I see that the singleton pattern for the logger was not as smart as thought, but passing it down to every class seems tedious. Is there a smarter way? Can I have one singleton per thread?
public static class JobManager
{
    private static BlockingCollection<JobTicket> _jobs = new BlockingCollection<JobTicket>();

    public static void AddJob(JobTicket job)
    {
        _jobs.Add(job);
    }

    public static void StartConsumer()
    {
        Task.Factory.StartNew(() =>
        {
            void processJob()
            {
                while (!_jobs.IsCompleted)
                {
                    var job = _jobs.Take();
                    try
                    {
                        using (JobProcessor processor = new JobProcessor(job))
                        {
                            processor.Start();
                        }
                    }
                    catch
                    {
                        // Alert something that an error happened
                    }
                }
            };
            // process 4 jobs in parallel
            Parallel.Invoke(processJob, processJob, processJob, processJob);
        });
    }
}

public class JobProcessor
{
    private JobTicket jobticket;

    public JobProcessor(JobTicket jobticket) {
        this.jobticket = jobticket;
        // ...
    }

    public void Start() {
        if(!(jobticket.LogPath is null)) {
            var logger = new TextLogger(jobticket.LogPath);
            Logger.SetLogger(logger);
        }
        Logger.Log("Job started");
        // Process job
        var a = new ClassA(...);
        if (jobticket.x)
            a.DoSomething();
        else
            a.DoSomethingElse();
    }
}

public class ClassA {
    //...
    public void DoSomething() {
        //...
        Logger.Log("I did something");
    }
    public void DoSomethingElse() {
        //...
        Logger.Log("I did something else");
    }
}

// I know this is not thread-safe, but what I want is one Logger instance per JobProcessor and not one Logger instance for all JobProcessors.
public static class Logger
{
    private static BaseLogger _logger = new ConsoleLogger();

    public static void Log(string message) {
        _logger.Log(message);
    }

    public static void SetLogger(BaseLogger logger)
    {
        _logger = logger;
    }
}

public abstract class BaseLogger
{
    public abstract void Log(string message);
}

public class TextLogger : BaseLogger
{
    public readonly string path;
    public TextLogger(string path) : base()
    {
        this.path = path;
    }

    public override void Log(string message)
    {
        File.AppendAllText(path, message);
    }
}

public class ConsoleLogger : BaseLogger
{
    public override void Log(string message)
    {
        Console.WriteLine(message);
    }
}

A: You are able to create sort of Dictionary<ThreadId, BaseLogger> in your static logger class. You will have own logger for each thread.
Additionally, you can change SetLogger signature to smth like void SetLogger(Func<BaseLogger> loggerFactory) to create amount of loggers that you need inside of Logger.

A: Based on the comments, it seems like ThreadStaticAttribute turned out to be the answer.
According to the documentation for ThreadStaticAttribute:

Indicates that the value of a static field is unique for each thread.

So marking Logger._logger with that attribute should make each instance unique for each thread.


text:
Q: How to include a plain html website in a vaadin application I need to embed a plain html website in my vaadin application. My current approach is following.
Add the website content to src/main/webapp/embedded directory in my source.
Add a servlet mapping like below, so that requests to embedded directory do not go to the vaadin servlet and handled by default servlet of tomcat.
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/embedded/*</url-pattern>
</servlet-mapping>

<servlet-mapping>
    <servlet-name>VaadinServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Can anyone notice anything wrong in this approach? Or can someone suggest a better way?

A: if you want display the site inside your vaadin application, you can use the BrowserFrame component:
String filepath = VaadinServlet.getCurrent().getServletContext().getRealPath("embedded/mysite.html");
File htmlFile = new File(filepath);

FileResource fileResource = new FileResource(htmlFile);

BrowserFrame frame = new BrowserFrame(null, fileResource);


text:
Q: TortoiseHG Sync - How to save URL I've recently migrated to Mercurial for source control and am using TortoiseHG.  Everything is working great, but whenever I go to "Synchronize" to do a push, the remote repository URL is blank and I need to type it in every time.  How do I save it so that the remote repository source is saved?

A: You did not mention which version of TortoiseHg, but there are two "standard" ways to save the URL:
1) Manually add the following lines to your <project_dir>\.hg\hgrc file:
[paths]
  default = http://server/path/to/remote/repo

2) Click the "Save" icon in TortoiseHg's Sync view:


text:
Q: Python Can't Find Modules I'm running a python script which resizes and converts images to JPG and an RGB.  This script worked perfectly until I upgraded my computers HD and moved everything over from my Time Machine backup.  Now when I try to run the script it can't find any modules.  Specifically the Image module (I use Pillow).
Traceback (most recent call last):
  File "processImgs.py", line 1, in <module>
    import os, sys, argparse, shutil, imgFunctions
  File "/web/script/python/img_processing/imgFunctions.py", line 1, in <module>
    import os, sys, Image, shutil, re
ImportError: No module named Image

I am using Homebrew to manage my modules, and "brew list" outputs the following:
freetype    graphicsmagick  libpng      libtool     little-cms2 openssl     pkg-config  readline    webp
gdbm        jpeg        libtiff     little-cms  openjpeg    pillow      python      sqlite

If i run "pip list" I get:
Pillow (2.3.0)
pip (1.5.4)
setuptools (2.2)
wsgiref (0.1.2)

If i run "help(modules)" in python, the Image module isn't listed.

A: Could be your python path isn't set up correctly after the move.
see here for the homebrew/python docs page and it seems that a reinstall of homebrew may fix it.


text:
Q: Login Incorrect Solaris 10 I've been trying to update Bash on Solaris 10 from Version 3 to 4.2 However, in the process i seem to have broken one of the custom accounts.
To install bash i've been making modifications to the /etc/passwd file when i was experiencing "Invalid Shell" errors. However i'm now getting a "Login Incorrect" error which i can't seem to get passed.
I'm able to login to the machine as root, the profile for the custom user appears to still exist however i can not seem to stop this error from occurring.
Does anyone have any ideas what might have went wrong here?

A: Resolved. There was a syntax error on the line of the user in question. I used the "pwconv" command to identify this syntax error. Fixed the error and all was resolved.


text:
Q: How to get POST API response in Cypress? I am working on a project to automate using Cypress. In this project, I need to create an order for a patient. When I click on the submit button it will call the following API https://ibis-dev.droicelabs.us/api/dispenser/orders/ using the POST method and return one unique order that I want to get.
I have registered cy.intercept on top of my test like this:
cy.intercept({
    method: 'POST',
    url: 'https://ibis-dev.droicelabs.us/api/dispenser/orders/',
}).as('ordersCall')

And when the submit button is clicked I have used:
cy.clickOnElementUsingXpath(practicePageSelectors.submit_CreateOrderButton); // click on submit button
cy.wait('@ordersCall')
    .its('response.body')
    .then((body) => {
        // parsing might be not needed always, depends on the api response
        const bodyData = JSON.parse(body)
        cy.log(bodyData)
    })

But it returns the following error:
Timed out retrying after 5000ms: cy.wait() timed out waiting 5000ms for the 1st request to the route: ordersCall. No request ever occurred in cy.wait('@ordersCall')
Can anyone help me to get an orderID? Is there any other way to get the orderID?

A: After checking the provided images in the question comments, the error is as follows: Your intercept command in your Cypress test is waiting for requests to be made to your DEV environment, but looking at your last image from the console in the Cypress test runner your requests are being made to the QA environment.
So you either have to adjust your Interceptor like this:
cy.intercept({
    method: 'POST',
    url: 'https://ibis-qa.droicelabs.us/api/dispenser/orders/',
}).as('ordersCall')

or think about using relative paths for API calls to be independent from the environment:
cy.intercept({
    method: 'POST',
    url: '/api/dispenser/orders/',
}).as('ordersCall')


text:
Q: Jquery keyup/blur date and days calculation I have a form which i would like to calculate the end date from the start date and the number of days selected.
So process......
Select days
Select start date
Auto populate enddate = starts days + days
I have got the following working but does anybody know how to populate with the calculation and so it has days and startdate inputed before the calculation takes place.
var $title3 = $("#enddate");
$("#startdate").keyup(function () {
    $title3.val(this.value);
});
$("#startdate").blur(function () {
    $title3.val(this.value);
});
$("#days").keyup(function () {
    $title3.val(this.value);
});
$("#days").blur(function () {
    $title3.val(this.value);
});

              echo'

                Days:

                <select id="days" name="days">
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
                <option value="5">5</option>
                </select>

                  Start Date:
                  <input type="text" name="startdate" id="startdate" class="required" readonly="readonly"/>

                  End Date:
                  <input type="text" name="enddate2" id="enddate2" class="required" readonly="readonly"/>

';

MOD
This is a solution i have come up with but need the maxDate for the enddate to be selectedDate + 5days excluding weekends. How would i write this?
Also how could i work out the difference in days from the 2 outcomes of enddate and startdate but exclude the weekends?
var $ac_start_date = '<?php echo $ac_end_date ?>',
    $ac_start_date_flip = '<?php echo $ac_end_date_flip ?>',
    $ac_start_parsed = Date.parse($ac_start_date),
    _today = new Date().getTime();

// For Opera and older winXP IE n such
if (isNaN($ac_start_parsed)) {
    $ac_start_parsed  = Date.parse($ac_start_date_flip);
}

var _aDayinMS = 1000 * 60 * 60 * 24;

// Calculate the difference in milliseconds
var difference_ms = Math.abs($ac_start_parsed - _today);

// Convert back to days and return
var DAY_DIFFERENCE = Math.round(difference_ms/_aDayinMS);

// do initialization here
$("#startdate").datepicker({
            dateFormat: 'dd-mm-yy',
            changeMonth: true,
            changeYear: true,
            yearRange: '0:+100',
            onSelect: function( selectedDate ) {
                $( "#enddate" ).datepicker( "option", "minDate", selectedDate );
                $( "#enddate" ).datepicker( "option", "maxDate", selectedDate + 5days excluding weekends);
            },
            minDate: '+1d',
            maxDate: '+' + (DAY_DIFFERENCE + 1) + 'd'
});

// do initialization here
$("#enddate").datepicker({
            dateFormat: 'dd-mm-yy',
            changeMonth: true,
            changeYear: true,
            yearRange: '0:+100'
});

AHHA...
$(".selector").datepicker({ beforeShowDay: $.datepicker.noWeekends })


text: Q: %lprun-like module profiling using kernprof I would like to profile certain modules using kernprof without inserting @profile decorators. Inside IPython shell %lprun has awesome feature -m module which allows to profile all lines in a specified module. But if I need to run some script from the command I use kernprof. The latter unfortunately doesn't seem to have this functionality allowing to profile only using the decorator. How can I bring this module-profiling functionality to command line kernprof invocation?


text:
Q: Problem using sed back reference I am trying to remove some junk and substitute words with the key digits, starting with strings like:
>ref|NC_035781.1|
>ref|NC_035782.1|
>ref|NC_035783.1|
>ref|NC_035784.1|

and wanting to end with:
>NC_035781.1
>NC_035782.1
>NC_035783.1
>NC_035784.1

I tried
sed 's/\>ref\|NC_03578\([0-9]\)\.1\|/>NC_03578\1\.1/g' chr.test | grep '>NC_'

to test it and got back many more results than expected looking like:
>NC_03578.1>>NC_03578.1r>NC_03578.1e>NC_03578.1f>NC_03578.1|>NC_035780.1|>NC_03578.1 >NC_03578.1C>NC_03578.1r>NC_03578.1a>NC_03578.1s>NC_03578.1s>NC_03578.1o>NC_03578.1s>NC_03578.1t>NC_03578.1r>NC_03578.1e>NC_03578.1a>NC_03578.1
...

What am I doing wrong?

A: The main issue is that you have escaped > and | and I suspect you are using GNU sed. In which case, \> acts as end of word boundary and \| will act as alternation operator.
$ sed 's/>ref|\(NC_03578[0-9]\.1\)|.*/>\1/' chr.test
>NC_035781.1
>NC_035782.1
>NC_035783.1
>NC_035784.1

The modified command is shown above. Also, there seems to be some spaces at end of line, so I've added .* to remove them. Use sed -n '/NC_/ s/>ref|\(NC_03578[0-9]\.1\)|.*/>\1/p' to include the grep operation within sed itself

You can also use awk
$ awk -F'|' '/NC_/{print ">" $2}' chr.test
>NC_035781.1
>NC_035782.1
>NC_035783.1
>NC_035784.1

*

*-F'|' to define | as field separator. | is a regexp operator, but when FS (the field separator special awk variable set by -F) is a single character, it is not treated as a regexp. -F'[|]' or -F'\\|' would also work but would be less efficient.

*/NC_/ if input line contains NC_

*

*print ">" $2 print > character and the second field


text:
Q: How to have two radio buttons of one group checked at the same time? I have a pricing table where I put radio buttons on the top of the table and on the bottom.
No matter if the user clicks on the radio button on the top or bottom, I want both radio buttons to be checked at the same time.

<input type="radio" name="group1">If you check me...

<input type="radio" name="group1">...I also want to be checked

<input type="radio" name="group2">If you check me...

<input type="radio" name="group2">...I also want to be checked

 Just a pic of a cat

https://codepen.io/Insane415/pen/mwOOWM

A: Radio buttons don't work that way. You can only select one at a time in a group.
You should use checkboxes instead.

4.10.5.1.13 Radio Button state
  (type=radio)
The input element represents a control that, when used in
  conjunction with other input elements, forms a radio button group
  in which only one control can have its checkedness state set to true.

A: yes use checkboxes instead and increase border-radius to let them look like a radio

A:

<input type="radio" name="group1">If you check me...

<input type="radio" name="group1">...I also want to be checked

<input type="radio" name="group2">If you check me...

<input type="radio" name="group2">...I also want to be checked

 Just a pic of a cat


text:
Q: How get a date (value) from a DatePicker and assign it to property an object? I'm using the react-datepicker library. How to extract a value from the DatePicker component and assign it to thedate property in the Pick object. Downloading data from the input was simple. How to do it with a data picker?
class Form extends Component {
  constructor(){
    super();
    this.state = {
      startDate: new Date()
    }
  }

  create(event) {
    event.preventDefault();

    const pick = {
      date: this.date.value, /
      color: this.color.value,
     description: this.description.value
    }

   this.form.reset();
  }

  handleChange = (date) => {
    this.setState({
      startDate: date
    });
  }

  render() {

    return (
      <form ref={(input) => this.form= input} onSubmit={(e) =>
          this.create(e)}>

          {/*<input ref={(input) => this.date = input} type="text"
          />*/}
       <DatePicker
        dateFormat="yyyy/MM/dd"
        selected={this.state.startDate}
        onChange={this.handleChange}
      />
      <input ref={(input) => this.time = input} type="text" />

       <textarea ref={(input) => this.description = input}
     placeholder="" ></textarea>

         <button >Cancel</button>
         <button type="submit">Save</button>

     </form>
    )
   }
 }

A: Assuming the rest of your code functions as expected, when the form is submitted it will be in your state, so get it from there:
const pick = {
      date: this.state.startDate,
      color: this.color.value,
     description: this.description.value
    }

A: handleChange = (e) => {
   this.setState( {[e.target.name]: e.target.value} )
}

you'll need to make sure that the name on the datePicker forms match the name in your state. So if your state is
this.state = {
   date: new Date();
}

Then the input on that field needs to be date as well.
 <input
                    name="date"
                    id="date"
                    type="date"
                    defaultValue="2017-05-24"
                    onChange={handleInputChange}
                    value={inputs.date}
                />

The method I posted allows you to reuse that for any form component. Just make sure you are matching the form input name and the state you are using.


text:
Q: How much ice will melt in water contained in a copper container? Lets say some amount of ice is given to some amount of water in a copper container ( I will not give the exact values because you can choose them at your wish).The ice is at a temperature and the water and copper container is at some temperature. We will assume that it is separated from the out side environment. The question is what percent of ice will melt?
Now , the part that bugs me that , if I try to calculate the temperature $T$ (with calorimeter equations) that the system will settle to , then I will can get three kinds of values(depending on the initial values) :
$(1)$ $T = 0^0C$
$(2)$ $T < 0^0C$
$(3)$ $T > 0^0C$
for the $(2)$ option , all the water will turn into ice , so no ice will melt.
for the $(3)$ option , all the ice will turn into water .
for the $(1)$ option , It is not clear if the water is water or ice , because it is in a transition phase.(kind of confused with this one)
So asking the question "What percentage of ice will melt in water contained in a copper container" Is kind of weird to me, because either $0$% or $100$% of the ice will turn into water. Is there something wrong with my line of reasoning?

A: If the final temperature is 0 C it can be 100% ice, 100% water or anything in between, without knowing the initial temperatures and quantities of ice, water and copper.
Hope this helps.


text:
Q: How can I use npm with a cordova app in visual studio I'm trying to write a hybrid app using the "Tools for Apache Cordova" visual studio project template.
In order to use angular2 I have added the required modules to packages.json.
Once I have compiled everything and fixed any other missing packages, the app refuses to load angular, presumably because the the packages are all the in the '~/nodes_module' folder while the website files are in the 'www' folder.
I have the same problem whether I load the sample (https://github.com/dbiele/TypeScript-Cordova-SystemJS-Angular2-beta) or follow the angular quickstart (https://angular.io/guide/quickstart).
I'm sure I'm doing something fundamentally wrong with respect to how a hybit app should be packaged. Help will be greatly appreciated.
I'm using visual Studio Community 2015.
I updated node and npm to the latests version and updated the path in visual studio so it can find them.

A: You miss just a little piece: you need a task for copying the needed scripts into your www folder. I would recommend to use a Gulp task, which you can invoke from Visual Studio's Task Runner.
Never install the npm packages direct into the www folder. In this way you get too much files, which increase your app's size unnecessary. This approach works for server applications, but not for mobile apps.
I, personally, would also recommend to use Ionic2. Not only is it a great framework for mobile apps, additionally it provides you a working gulpfile.

A: If you are interested in using Angular2 with Cordova, I highly recommend using the Ionic framework. Ionic2 is in beta and uses Angular2 (installation instructions here: http://ionicframework.com/docs/v2/getting-started/installation/) whereas the original Ionic framework is stable, but uses Angular 1 (http://ionicframework.com/getting-started/).
The benefits of Ionic are numerous:

*

*Knowledgeable community (https://forum.ionicframework.com/)

*Large library of plugins (http://ngcordova.com/)

*Built-in CSS library / pre-build components (http://ionicframework.com/docs/components/)

*Development tooling: live reloading, SASS support, icon/splash creation, etc. (http://ionicframework.com/docs/cli/)

Best of luck!