text:
Q: Add scroll view to the whole activity I want my whole activity to scroll. My activity contains a view pager and a gridview. I have read at various places that a scroll view does not work properly if there is a gridview in the layout. But, I want this to happen. Is there a way out?
xml file-
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin">
<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="#FFF">
    <include
        android:id="@+id/tool_bar2"
        layout="@layout/tool_bar2"
        ></include>
  <RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tool_bar"
android:id="@+id/imgbtn">
    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:layout_weight="1"

        android:background="#FFF">
    </android.support.v4.view.ViewPager>

  <Button
android:layout_width="30dp"
android:layout_height="25dp"
android:text="@string/left"
android:background="@drawable/btn_back"
android:textColor="#FFF"
android:onClick="sleft"
android:layout_alignLeft="@+id/pager"
android:layout_alignBottom="@+id/pager"
android:layout_marginBottom="80dp"
android:paddingLeft="15dp"
android:id="@+id/left"

/>
   <TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/pager"
android:layout_alignBottom="@+id/pager"
android:paddingRight="30dp"
android:paddingBottom="15dp"
>
         <Button
        android:layout_width="30dp"
        android:layout_height="25dp"
        android:text="+"
             android:textColor="#FFF"

             android:layout_toLeftOf="@+id/numb"
        android:background="@drawable/button_back"/>
<TextView
    android:layout_width="30dp"
    android:layout_height="25dp"
    android:textColor="#000"

    android:text="0"
    android:gravity="center"
    android:layout_toLeftOf="@+id/minus"
    android:id="@+id/numb"
    />
        <Button
        android:layout_width="30dp"
        android:layout_height="25dp"
        android:textColor="#FFF"
            android:id="@+id/minus"
        android:text="-"
            android:background="@drawable/button_back"
         />
        </TableRow>
        <Button
            android:layout_width="30dp"
            android:layout_height="25dp"
            android:text="-)"
            android:background="@drawable/btn_back"
            android:paddingRight="15dp"
            android:layout_alignBottom="@+id/pager"
            android:layout_marginBottom="80dp"
            android:layout_alignRight="@+id/pager"

            android:textColor="#FFF"
            android:onClick="sright"
            android:id="@+id/right"/>

    </RelativeLayout>
    <GridView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numColumns="2"
        android:gravity="center"
        android:columnWidth="185dp"
        android:verticalSpacing="1dp"
        android:horizontalSpacing="1dp"
        android:stretchMode="columnWidth"
        android:id="@+id/grid"
        android:layout_below="@+id/imgbtn"
        >

    </GridView>

</RelativeLayout>
</ScrollView>
<fragment
    android:id="@+id/fragment_navigation_drawer"
    android:name="com.food.foodjugaad.FragmentDrawer"
    android:layout_width="@dimen/nav_drawer_width"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    tools:layout="@layout/fragment_navigation_drawer" />

    </android.support.v4.widget.DrawerLayout>

The output that i get from this code does not apply the scroll view like i want. Grid view and view pager work separately. and also, there occurs a white space at the bottom of the screen.
This is what I am getting -


text:
Q: Accessing WCF service hosted as Windows service over LAN I am beginner to WCF services and Windows services. I've a couple of questions regarding WCF services hosted as Windows services yet I've read some on the articles from MSDN:
1) I have a WCF service hosted in Windows service running on one machine on LAN. I want to make silverlight applications running on other machines over same LAN consume that service. I need this architecture to be implemented across many LAN networks i.e. each LAN will have one machine on which Windows service is running and other machines on the same LAN should be able to access the service. Is it a feasible architecture? What technical issues may come up (e.g. firewall setting may restrict client from accessing service)? Shall I have to make different configurations in client applications for each LAN? As a side note, I want to mention that I want to run the service only when there is no internet connection.
2) What are the ways to make a client on LAN consume WCF service hosted in Windows service other than adding a service reference to project?

A: 1)
- Use Net.Tcp bindings for endpoints. Firewall won't be an issue if client and server are on same network.
- Client configuration will be different. You need to point to diffrent endpoint for accessing WCF service.One for each service hosted.
2) You can create proxy class also on client side using SvcUtil utility.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Regex, applying or operation on target string I'm studying regex.
Is it possible to apply oring operator on target string?
for example, consider POS tagging.
given a sentence like "I like apple",
I want to match it with regex "NP like NNG"
Since there exists part-of-speech for each word in the sentence,
given a regex "NP like NNG",
8 possible target strings can be matched.
(I like apple, NP like apple, NP VV apple, NP VV NNG et al.)
I was wondering, is it possible to treat target string as (I|NP)(like|VV)(apple|NNG) so that
regex "NP like NNG" can be matched at once?

A: You've already written almost the entire regex with (I|NP)(like|VV)(apple|NNG)
Only thing you need to account for is the spaces, you can do this with \s like so:
(I|NP)\s+(like|VV)\s+(apple|NNG)

See also this Debuggex Demo


text:
Q: Is this article obsolete ? Should I use other aproach of aplication architecture nowadays? I was wondering if the next article could be obsolete today. It was written in 2007. Describes MVC Architecture based java beans mimicking properties of the model to the controller. Also uses reflection for each property setted.
Article: http://www.oracle.com/technetwork/articles/javase/mvc-136693.html
Code: http://www.multiupload.com/PFSRSU9ELY

*

*Should I follow the above article or Would be better to use an object aproach ? keeping the properties into collections within the model and so on...

*Should I stop trying to make my own architecture for an application and give a try to Spring Framework or any other fw. ?

A: MVC itself can't be obsoleted; it's a design pattern.
The article specifically targets Swing, which has seen some changes since 2007, but nothing that would specifically negate the article, although perhaps some classes have been changed, tweaked, etc.
There may be easier ways to implement some of the functionality, but it demonstrates one way of using MVC within a Swing app within JSE 6.
Frameworks like Griffon (Groovy-based) take the abstraction level a step further, and might be more appropriate for modern desktop app development, but that's more a matter of preference and convenience.

A: I think you are better off reusing some of the solutions existing out there for MVC implementation (e.g. Spring). People coding those frameworks already faced issues you will find if you implement your own solution. I am sure you will learn a lot by implementing your own MVC solution, but that's the only thing you will get from it.


text:
Q: Classification Precision Optimization towards one class? My dataset has two classes. The one of non-interested takes 90%, and the class of interest is about 10%.
I have already done the resampling, not only once, but a butch of balanced sets (e.g 10 sets). And do the majority vote to get the final prediction results. After compared many models, tree gives the best result. And I have already picked out the most important features based on importance scores.
The overall accuracy is not bad, 75%, but the precision towards the class I am interested is only 30%, which is not good. How to do the optimization towards the precision of the target class? I think the algorithms behind the ctree package in R is to do optimization towards the overall accuracy. I also tried the one-class classification, like svm, but not good. BTW, I used R and python both. But I do not find any relevant packages about my problem. Do I need to write my own tree algorithm which will optimize the precision of the class interested? Thanks.

A: There are plenty of models which give you ability to weight classes. This in general is better than just oversampling as it directly alternates the objective, not artificially tricks the model to overweight. If you use python, and like tree-based approach, Random Forest in scikit-learn has class-weight capabilities, simply overweight your minority class as long as the desired precision is not obtained.


text:
Q: Parsing and Storing the text data from webpage to database I have an web-service, where through URL I get the data in text format.
Is there any way to get the data from website and store it the database through PLSQL?
This how data is available in the website.
DATA format:
locationId|locationName|city|state|postalCode|countryCode|regionId|
 9|DELHI, DEL-BLDG01|DELHI|DEL|111000|IND|1|
Thank you.


text:
Q: JSON deserialization of variable named parameter using DataContract Assuming we have a JSON object similar to:
{
  '12345': 'text string',
  'rel': 'myResource'
}

Constructing a DataContract to map to this type seems fairly simple such as:
[DataContract]
MyResource
{
  [DataMember(Name = "12345")]
  public string SpecialValue { get; set; }

  [DataMember(Name = "rel")]
  public string Rel { get; set; }
}

Now the problem arrives that the name of the property is variable so it not guaranteed to be '12345'.  Since this variable cannot be properly mapped using attributes it won't get picked up when using DataContractJsonSerializer.
If I change the class to support IExtensibleDataObject, I can get the value portion but not the property name which is a problem.  I'm looking to maintain this value during deserialization/serialization in order to be able to send the information on a return request.  I'm not looking to change over to using Json.NET to solve this problem as I want to know if it is possible in some form without resorting to an external dependency.

A: It's a little ugly, but it turns out you can use an IDataContractSurrogate to deserialize the class with the variably named property into a Dictionary<string, object> and then copy the values from the dictionary into your class.  Of course, you will need to add another property to your class to hold the name of the "special" property.
Here is an example surrogate that I was able to get working:
class MyDataContractSurrogate : IDataContractSurrogate
{
    public Type GetDataContractType(Type type)
    {
        if (type == typeof(MyResource))
        {
            return typeof(Dictionary<string, object>);
        }
        return type;
    }

    public object GetDeserializedObject(object obj, Type targetType)
    {
        if (obj.GetType() == typeof(Dictionary<string, object>) &&
            targetType == typeof(MyResource))
        {
            Dictionary<string, object> dict = (Dictionary<string, object>)obj;
            MyResource mr = new MyResource();
            foreach (PropertyInfo prop in GetInterestingProperties(typeof(MyResource)))
            {
                DataMemberAttribute att = prop.GetCustomAttribute<DataMemberAttribute>();

                object value;
                if (dict.TryGetValue(att.Name, out value))
                {
                    prop.SetValue(mr, value);
                    dict.Remove(att.Name);
                }
            }

            // should only be one property left in the dictionary
            if (dict.Count > 0)
            {
                var kvp = dict.First();
                mr.SpecialName = kvp.Key;
                mr.SpecialValue = (string)kvp.Value;
            }
            return mr;
        }
        return obj;
    }

    public object GetObjectToSerialize(object obj, Type targetType)
    {
        if (obj.GetType() == typeof(MyResource) &&
            targetType == typeof(Dictionary<string, object>))
        {
            MyResource mr = (MyResource)obj;
            Dictionary<string, object> dict = new Dictionary<string, object>();
            dict.Add(mr.SpecialName, mr.SpecialValue);
            foreach (PropertyInfo prop in GetInterestingProperties(typeof(MyResource)))
            {
                DataMemberAttribute att = prop.GetCustomAttribute<DataMemberAttribute>();
                dict.Add(att.Name, prop.GetValue(mr));
            }
            return dict;
        }
        return obj;
    }

    private IEnumerable<PropertyInfo> GetInterestingProperties(Type type)
    {
        return type.GetProperties().Where(p => p.CanRead && p.CanWrite &&
                       p.GetCustomAttribute<DataMemberAttribute>() != null);
    }

    // ------- The rest of these methods are not needed -------
    public object GetCustomDataToExport(Type clrType, Type dataContractType)
    {
        throw new NotImplementedException();
    }

    public object GetCustomDataToExport(MemberInfo memberInfo, Type dataContractType)
    {
        throw new NotImplementedException();
    }

    public void GetKnownCustomDataTypes(System.Collections.ObjectModel.Collection<Type> customDataTypes)
    {
        throw new NotImplementedException();
    }

    public Type GetReferencedTypeOnImport(string typeName, string typeNamespace, object customData)
    {
        throw new NotImplementedException();
    }

    public System.CodeDom.CodeTypeDeclaration ProcessImportedType(System.CodeDom.CodeTypeDeclaration typeDeclaration, System.CodeDom.CodeCompileUnit compileUnit)
    {
        throw new NotImplementedException();
    }
}

To use the surrogate, you'll need to create an instance of DataContractJsonSerializerSettings and pass it to the DataContractJsonSerializer with the following properties set.  Note that since we require the UseSimpleDictionaryFormat setting, this solution will only work with .Net 4.5 or later.
var settings = new DataContractJsonSerializerSettings();
settings.DataContractSurrogate = new MyDataContractSurrogate();
settings.KnownTypes = new List<Type> { typeof(Dictionary<string, object>) };
settings.UseSimpleDictionaryFormat = true;

Note also that in your class you should NOT mark the "special" properties with a [DataMember] attribute, since they are handled specially in the surrogate.
[DataContract]
class MyResource
{
    // Don't mark these with [DataMember]
    public string SpecialName { get; set; }
    public string SpecialValue { get; set; }

    [DataMember(Name = "rel")]
    public string Rel { get; set; }
}

Here is a demo:
class Program
{
    static void Main(string[] args)
    {
        string json = @"
        {
            ""12345"": ""text string"",
            ""rel"": ""myResource""
        }";

        var settings = new DataContractJsonSerializerSettings();
        settings.DataContractSurrogate = new MyDataContractSurrogate();
        settings.KnownTypes = new List<Type> { typeof(Dictionary<string, object>) };
        settings.UseSimpleDictionaryFormat = true;

        MyResource mr = Deserialize<MyResource>(json, settings);

        Console.WriteLine("Special name: " + mr.SpecialName);
        Console.WriteLine("Special value: " + mr.SpecialValue);
        Console.WriteLine("Rel: " + mr.Rel);
        Console.WriteLine();

        json = Serialize(mr, settings);
        Console.WriteLine(json);
    }

    public static T Deserialize<T>(string json, DataContractJsonSerializerSettings settings = null)
    {
        using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
        {
            if (settings == null) settings = GetDefaultSerializerSettings();
            var ser = new DataContractJsonSerializer(typeof(T), settings);
            return (T)ser.ReadObject(ms);
        }
    }

    public static string Serialize(object obj, DataContractJsonSerializerSettings settings = null)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            if (settings == null) settings = GetDefaultSerializerSettings();
            var ser = new DataContractJsonSerializer(obj.GetType(), settings);
            ser.WriteObject(ms, obj);
            return Encoding.UTF8.GetString(ms.ToArray());
        }
    }
}

Output:
Special name: 12345
Special value: text string
Rel: myResource

{"12345":"text string","rel":"myResource"}


text:
Q: Split TRY and CATCH EXCEPTION across different .php include files Is there any way in PHP to split try and catch across two different "include files", putting the try in one file and the catch in another?
Something like:
<?php
    include('begin_try.php');
      ...
      //some code goes here
      ...
    include('end_try_and_catch_exceptions.php');
?>

//filename: begin_try.php:
<?php
    header('Content-type: application/json');
    try {
?>

//filename: end_try_and_catch_exceptions.php:
<?php
    } catch (Exception $e) {
      echo json_encode(array(
          'error' => array(
              'code' => $e->getCode(),
              'message' => $e->getMessage()
          )
      ));
    }
?>

A: It's not syntactically possible to use try-catch like that, but you can use the set_exception_handler function to register a function that will catch all exceptions that are not otherwise caught:
set_exception_handler(function ($e) {
    echo json_encode(array(
        'error' => array(
            'code' => $e->getCode(),
            'message' => $e->getMessage()
        )
    ));
});


text:
Q: How to write convert string to Document object I have a string that's has xml content in it like this:
String xml = "<item_list>" +
                "<category id='2' name='categoryName'>" +
                   "<item id='41' name='item1' />" +
                "</category>" +
             "</item_list>)";

I want to convert this to an Document object. Here my code for doing this:
Document doc = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
StringReader sr = new StringReader(xml);
InputSource is = new InputSource(sr);
doc = builder.parse(is);

When I run this I get the next error:
org.xml.sax.SAXParseException: Unexpected token (position:TEXT )@1:139 in java.io.InputStreamReader@40fa7860)

What am I doing wrong?

A: Change your xml string as:
String xml = "<?xml version='1.0' encoding='UTF-8'?>" +
                "<item_list>" +
                "<category id='2' name='categoryName'>" +
                   "<item id='41' name='item1' />" +
                "</category>" +
             "</item_list>";

Currently you are missing xml document header <?xml version='1.0' encoding='UTF-8'?> in your string
for more help how we create xml doc in android see this tutorial :
http://xjaphx.wordpress.com/2011/10/27/android-xml-adventure-create-write-xml-data/

A: "</item_list>)";
That parenthesis shouldn't be there.


text:
Q: Make "Open in Terminal" use Xterm I've seen this question, and this one, and neither one is addressing my question. I have already used sudo update-alternatives to set Xterm as my default terminal. I much prefer Xterm as a terminal application, as it loads faster than gnome-terminal.
How can I get the right-click action "Open in Terminal", located in the Files application, to use Xterm? Changing the above defaults did not change this behavior, though I would have thought it should.
Thanks for your time!

A: The "Open in terminal" right-click menu is provided by a nautilus extension, and hard coded to open gnome-terminal through dbus, so you cannot directly change that menu item.
There are a couple of approaches you could try:

*

*Ubuntu 20.04: Install nautilus-extensions-fma. That was formerly known as "Nautilus actions". It allows you to add custom actions to the right-click menu. Ubuntu 18.04: You have to add a PPA.

*Create a nautilus script. Nautilus scripts are scripts in the ~/.local/share/nautilus/scripts folder. They appear under a "Scripts" entry in the right-click menu. You can assign a shortcut key to such script that will work from within nautilus.

*If you are sufficiently skilled with python, you may write a nautilus python script or change an existing one. nautilus-open-any-terminal supports a lot of terminal emulators, but xterm is not one of them.
To remove the existing right-click menu for "Open in terminal", remove the package nautilus-extension-gnome-terminal.

A: How to OPEN TERMINAL HERE in Ubuntu 20.04
For the sake of informing other users that may search for my same question ( I have landed here googling for the question How to OPEN TERMINAL HERE in Ubuntu 20.04 )
It is built in in Nautilus
Just browse to the directory you want in Nautilus and right click on the background of the window
In the context menu you'll find the needed command


text:
Q: How to create hdfs directory for user in Linux at the same time? I can create directory in HDFS under current user directory
hdfs dfs -mkdir /user/john.doe/data

Above command executed without issue. However data directory was not created under /home/john.doe directory in Linux
what is the best way to create hdfs directory in associated linux directory?

A: Are you expecting a directory with name data under the directory /home/john.doe? then the expectation is wrong.
HDFS directories are never materialized to the disk (They are never created on local filesystem). Namenode builds this directory mappings and this datastructure is synced to filesystem periodically.
But files/blocks are materialized to disk. You can see them under the configured location. Read this post for more info.
Where HDFS stores data


text:
Q: Hibernate manytomany object filter I am a newbie in Java and am stuck in a simple problem. I have a class named UserProfile and another named Company. Both are related by ManyToMany relation. Their definitions are as follows:

// User Profile
@Entity
@Table(name="SEC_USER_PROFILES")
@JsonSerialize(using=UserSerializer.class)
public class UserProfile implements Serializable{
    Long userId;
    .
    ...

    private List<Company> companiesList;

    public UserProfile() {
        this.companiesList = new ArrayList<Company>();
    }

    @ManyToMany(fetch=FetchType.EAGER)
    @JoinTable(
            name="SEC_USERS_COMPANIES",
            joinColumns=@JoinColumn(name="USERID"),
            inverseJoinColumns=@JoinColumn(name="COMPANYID")
            )
    //@JsonIgnore
    public List<Company> getCompaniesList() {
        return companiesList;
    }
    public void setCompaniesList(List<Company> companies) {
        this.companiesList = companies;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "USERID")
    public Long getUserId() {
        return userId;
    }
    public void setUserId(Long userId) {
        this.userId = userId;
    }
    // other getters and setters
}

And the Company class:
@Entity
@Table(name="SEC_COMPANIES")
public class Company implements Serializable{
    Long companyId;
    String companyName;
    String companyAddress;
    String companyDesc;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "COMPANYID")
    public Long getCompanyId() {
        return companyId;
    }
    public void setCompanyId(Long companyId) {
        this.companyId = companyId;
    }
    // other getters setters
}

And now I need to filter userprofiles with companyId=3 and other criteria like firstName="John" and so on. I did not see any obvious solution using criteria. You need not worry about any other underlying implementations and setup. I just want a way to filter userprofile in an easy way.
How can I achieve that?
Thank you.


text:
Q: AltBeacon : onBeaconServiceConnect not called when BeaconConsumer Binded From DidEnterRegion BootstrapNotifier callback I'm writing an Android App custom Class that utilises AltBeacon's Android-Beacon-Library.
Instead of posting the class, I am reproducing the problem using the reference implementation samples provided with the library.
If I activate both monitoring (by implementing a RegionBootstrap) and ranging beaconManager.bind(new BeaconConsumer()...) directly in onCreate(), everything works perfectly.
I would like however to start ranging only when a Beacon enters region, so in didEnterRegion(Region arg0) callback of the RegionBootstrap, but when I do so, onBeaconServiceConnect() is never called. I believe doing it this way would be more efficient in terms of battery consumption.
I have tried force executing on the main thread as well as using delayed timers but it didn't work.
Anyone could get this to work ? Any help appreciated!
public class BeaconReferenceApplication extends Application implements BootstrapNotifier {

    private static final String TAG = "AndroidProximityReferenceApplication";
    private RegionBootstrap regionBootstrap;
    private BackgroundPowerSaver backgroundPowerSaver;
    BeaconManager beaconManager;
    Context context = this;

    public void onCreate() {
        super.onCreate();
        beaconManager = org.altbeacon.beacon.BeaconManager.getInstanceForApplication(this);
        // Setup beacon layout - should be done once only
        List<BeaconParser> bp = beaconManager.getBeaconParsers();
        bp.add(new BeaconParser().setBeaconLayout("m:0-3=4c000215,i:4-19,i:20-21,i:22-23,p:24-24"));

        Region region = new Region("backgroundRegion", null, null, null);
        regionBootstrap = new RegionBootstrap(this, region);
        backgroundPowerSaver = new BackgroundPowerSaver(this);

        // THIS WORKS
        bindBeaconConsumer();
    }

    public void bindBeaconConsumer() {
        beaconManager.bind(new BeaconConsumer() {
            @Override
            public void onBeaconServiceConnect() {
                // ISSUE : Does not pass here when bindBeaconConsumer() is called from didEnterRegion

                // Set Range Notifier and start ranging
            }

            @Override
            public Context getApplicationContext() {
                return context;
            }

            @Override
            public void unbindService(ServiceConnection serviceConnection) {
                context.unbindService(serviceConnection);
            }

            @Override
            public boolean bindService(Intent intent, ServiceConnection serviceConnection, int i) {
                return context.bindService(intent, serviceConnection, i);
            }
        });
    }

    @Override
    public void didEnterRegion(Region arg0) {
        Log.d(TAG, "did enter region.");

        // THIS DOESN'T WORK : onBeaconServiceConnect() never called
        // bindBeaconConsumer();
    }

    @Override
    public void didExitRegion(Region region) {
    }

    @Override
    public void didDetermineStateForRegion(int state, Region region) {
    }
}

A: The reason calling bindBeaconConsumer() doesn't work in the monitoring callback is because by the time it executes, the class is already bound to the service.  If you look at LogCat, you will see a warning message about this.  Since it is already bound, the code does not get a callback to onBeaconServiceConnect().
Why is it already bound?  Because of the line below:
regionBootstrap = new RegionBootstrap(this, region);

The RegionBootsrap class does a bind operation behind the scenes, which executes in a second or so.
The easiest way to fix this is to remove the call to bindBeaconConsumer() in the didEnterRegion method and instead just call beaconManager.startRangingBeaconsInRegion(...).  You don't need to bind again because by that point, the service is already bound.


text:
Q: Python used the decorator TypeError: bilolgy() missing 1 required positional argument: 'self' I've tried to define a decorator in a base class,and used it in a subclass,but when I ran it, then came out the wrong message. here is the code:
class Base(object):
    """
    base class
    """
    def bilolgy(self, pre):
        def animal(func):
            def color(a):
                print(pre)
                print("Today is a good day")
                func(a)

            return color

        return animal

class Sub(Base):
    """
    subclass
    """
    @Base.bilolgy(pre="Cats")
    def cat(self, name):
        print("This is a " + name)

if __name__ == '__main__':
    sub = Sub()
    sub.cat("cat")

here is the wrong message:
Traceback (most recent call last):
  File "/home/kevin/test/sklearn/test2.py", line 18, in <module>
    class Sub(Base):
  File "/home/kevin/test/sklearn/test2.py", line 22, in Sub
    @Base.bilolgy(pre="Cats")
TypeError: bilolgy() missing 1 required positional argument: 'self'

when I added a self into code like this:
@Base.bilolgy(self, pre="Cats")

another wrong message came out as :
Traceback (most recent call last):
  File "/home/kevin/test/sklearn/test2.py", line 18, in <module>
    class Sub(Base):
  File "/home/kevin/test/sklearn/test2.py", line 22, in Sub
    @Base.bilolgy(pre="Cats")
TypeError: bilolgy() missing 1 required positional argument: 'self'

Thanks for your help!


text:
Q: Rails - Does mysql temporary table available between different http request I have written a code to create temporary table on every http request. For the very first request table is created successfully however on the second request it gives me error as Table 'xxx' already exists. when i restarted my local machine server(thin web server) and hit the http request  then again temporary table is created without error.
Does this mean that temporary tables are shared between different http request and are destroyed automatically when machine or server is restarted??
Thanks,

A: As far as I know temporary table exists until connection to the database is closed. In Rais you have a pool of connections to the database and different requests can use different connections.
So if you create temporary table in the first http request, second request can use the same connection and you can receive a SQL error when is trying to create it again, but in second request use another connection temporary table will not exist yet.


text:
Q: alternative to std::this_thread::sleep_for() I have a loop and I want to ensure that it runs for an (approximately) fixed amount of time for each loop.
I am using sleep_for to achieve this behavior but I also want the program to be able to compile on environments that do not include full support of the standard thread library. Right now I have something like this:
using namespace std;
using namespace std::chrono;

//
while( !quit )
{
    steady_clock::time_point then = steady_clock::now();

    //...do loop stuff

    steady_clock::time_point now = steady_clock::now();
#ifdef NOTHREADS
    // version for systems without thread support
    while( duration_cast< microseconds >( now - then ).count() < 10000 )
    {
        now = steady_clock::now();
    }

#else
    this_thread::sleep_for( microseconds{ 10000 - duration_cast<microseconds>( now - then ).count() } );
#endif

}

While this allows the program to compile in environments that do not support standard threads, it is also very CPU-intensive as the program checks continually for the time condition rather than waiting until it is true.
My question is: Is there a less resource-intensive way to enable this "wait" behavior using only standard C++ (i.e. not boost) in an environment that does not fully support threads?

A: There are many time based functions, it very much depends on the Operating system you're using.
Microsoft API offers Sleep() (capital S) which gives you a millisecond sleep.
Under Unix (POSIX) you have nanosleep().
I think that these two functions should get you running on most computers.
The implementation would be to use the same loop, but sleep a little inside the while() loop. That will still be a pool like thing, but faster much less CPU intensive.
Also, as n.m. mentioned, select() has that capability. Just a bit more convoluted to implement, but it is expected to return once the time elapsed.


text:
Q: How to get the selected value of a dropdown in C# How do I get the selected value in the dropdown
HTML Code:
<select  name="appealStatusId" class="form-control input-sm">
  <option value="1">
      Pending
  </option>

  <option value="2">
      Overall Appeal Approved
  </option>

  <option value="3" selected="selected">
      Overall Appeal Not Approved
  </option>

A: To get the selected value in the dropdown you have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

*

*Using CssSelector:
SelectElement status = new SelectElement(driver.FindElement(By.CssSelector("select[name='appealStatusId']")));
IWebElement selected = status.SelectedOption;
Console.Write(selected.Text);

*Using XPath:
SelectElement status = new SelectElement(driver.FindElement(By.XPath("//select[@name='appealStatusId']")));
IWebElement selected = status.SelectedOption;
Console.Write(selected.Text);

*Using Name:
SelectElement status = new SelectElement(driver.FindElement(By.Name("appealStatusId")));
IWebElement selected = status.SelectedOption;
Console.Write(selected.Text);

A: You can select the element based on it's Value, Text or Id in dropdown options.
By using text:
IWebDriver driver = new ChromeDriver();

driver.Navigate().GoToUrl("your_URL");

driver.Manage().Window.Maximize();

IWebElement element_name = driver.FindElement(By.Name("appealStatusId"));

SelectElement statusId = new SelectElement(element_name);

// To print all available options
Console.WriteLine(statusId.Options);

// To iterate over the dropdown options and select the one which matches with the text you want to select
foreach(IWebElement  element in statusId.Options)
     {
          if(element.Text == "Overall Appeal Not Approved")
          {
               element.Click();
          }
     }

Or by using SelectByValue:
IWebDriver driver = new ChromeDriver();

driver.Navigate().GoToUrl("your_URL");

driver.Manage().Window.Maximize();

IWebElement element_name = driver.FindElement(By.Name("appealStatusId"));

SelectElement statusId = new SelectElement(element_name);

statusId.SelectByValue("3");


text:
Q: How to join (merge) data frames by different variables for each observation Suppose I have two data frames like the following:
df1 <- data.frame(
    X = c(1,2,2),
    Y = c("a","b","c"),
    Z = c(10,20,30)
)

df2 <- data.frame(
  X = c(1,2,2,4),
  Y = c(NA,"b","c","d"),
  W = c(-1,-2,-3,-4)
)

I would like to left join df1 on df2 using both X and Y. But for the first observation I'd only use X. In the end I'd like to get:
df3 <- data.frame(
  X = c(1,2,2,4),
  Y = c(NA,"b","c","d"),
  W = c(-1,-2,-3,-4),
  Z = c(10,20,30,NA)
)

Couldn't do it using left_join or full_join.

A: Not the most elegant-looking, but I don't know how to do (well) conditional joins:
full_join(df2, df1, by = c("X", "Y")) %>%
  filter(!is.na(W)) %>%
  group_by(grp = is.na(Y)) %>%
  do({
    dat <- .
    if (is.na(dat$Y[1])) {
      left_join(dat, select(df1, -Y), by = "X") %>%
        mutate(Z = coalesce(Z.x, Z.y)) %>%
        select(-starts_with("Z."))
    } else dat
  }) %>%
  ungroup() %>%
  select(-grp) %>%
  arrange(X, Y)
# # A tibble: 4 x 4
#       X Y         W     Z
#   <dbl> <chr> <dbl> <dbl>
# 1     1 <NA>     -1    10
# 2     2 b        -2    20
# 3     2 c        -3    30
# 4     4 d        -4    NA

A: You can do this in two steps. First, left join df2 on df1 using X and Y. Second, replace any missing value in Z with the corresponding value in df1 based on X only. But this will only work if there are no duplicates in X.
df4 <- merge(df2, df1, all.x=TRUE); df4
#  X    Y  W  Z
#1 1 <NA> -1 NA # <-- this guy could not match, since Y was NA
#2 2    b -2 20
#3 2    c -3 30
#4 4    d -4 NA

ind <- df4$X[is.na(df4$Z)] # returns the indices 1 4
df4$Z[ind] <- df1$Z[ind]
df4
#  X    Y  W  Z
#1 1 <NA> -1 10
#2 2    b -2 20
#3 2    c -3 30
#4 4    d -4 NA

If df2$Y contains NA for any X that is duplicated, then the solution is indeterminate.


text:
Q: parallelization of events notification in case of file creation I am using "Inotify" to logs event when a file or folder is created in a directory ( tmp here) . The example here does the job in as serial process. Meaning, All file creation are treated one after the other, in a sequential way.
import logging

import inotify.adapters

_DEFAULT_LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'

_LOGGER = logging.getLogger(__name__)

def _configure_logging():
    _LOGGER.setLevel(logging.DEBUG)

    ch = logging.StreamHandler()

    formatter = logging.Formatter(_DEFAULT_LOG_FORMAT)
    ch.setFormatter(formatter)

    _LOGGER.addHandler(ch)

def _main():
    i = inotify.adapters.Inotify()

    i.add_watch(b'/tmp')

    try:
        for event in i.event_gen():
            if event is not None:
                (header, type_names, watch_path, filename) = event
                _LOGGER.info("WD=(%d) MASK=(%d) COOKIE=(%d) LEN=(%d) MASK->NAMES=%s "
                             "WATCH-PATH=[%s] FILENAME=[%s]",
                             header.wd, header.mask, header.cookie, header.len, type_names,
                             watch_path.decode('utf-8'), filename.decode('utf-8'))
    finally:
        i.remove_watch(b'/tmp')

if __name__ == '__main__':
    _configure_logging()
    _main()

I would like to introduce parallelization of the events notification in case of several files are uploaded by importing threading, should I add a threading as loop ?
Second concern, I am not sure where it would make sens to put the thread function.

A: The below scripts handles multiples events in case of multiples sessions. So in my case, this is enough. I Added the multiprocessing  option instead of threading. I found multiprocessing faster than threading.
 import logging
 import threading
 import inotify.adapters
 import multiprocessing

 _DEFAULT_LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'

 _LOGGER = logging.getLogger(__name__)

 def _configure_logging():
     _LOGGER.setLevel(logging.DEBUG)

     ch = logging.StreamHandler()

     formatter = logging.Formatter(_DEFAULT_LOG_FORMAT)
     ch.setFormatter(formatter)

     _LOGGER.addHandler(ch)

 def PopUpMessage (event):
     if event is not None:
         (header, type_names, watch_path, filename) = event
         _LOGGER.info("WD=(%d) MASK=(%d) COOKIE=(%d) LEN=(%d) MASK->NAMES=%s "
             "WATCH-PATH=[%s] FILENAME=[%s]",
             header.wd, header.mask, header.cookie, header.len, type_names,
             watch_path.decode('utf-8'), filename.decode('utf-8'))

 def My_main(count):
     i = inotify.adapters.Inotify()
     DirWatcher=i.add_watch(b'/PARA')
     try:
         while True:
             for event in i.event_gen():
                 m = multiprocessing.Process(target=PopUpMessage, args=(event,))
                 m.start()

     finally:
         i.remove_watch(b'/PARA')

 if __name__ == '__main__':
     _configure_logging()
     N = multiprocessing.Process(target=My_main)
     N.start()


text:
Q: Render link for association I have an Order model which has one Cart model. In orders#edit form I want to have a link to the carts#show page of the belonging cart.
The documentation mentions several UI elements which can be rendered, but I don't see things which can render links.
My current setup is:
class OrdersController < ApplicationController
  active_scaffold :order do |conf|
    conf.columns = [:name, :cart]

A: You can Do this in two ways
get "orders#edit", :to=> "cart#show"

or, just type rake routes in your terminal and you might see something like order_edit and cart_show,then do this
get order_edit_path,:to=> cart_show_path


text:
Q: hg + remove bookmark and all changes I would like to abandon all changes in my bookmark and delete the bookmark itself.
I tried the instructions under: Mercurial - How to discard all local changes including to unversioned files?
i.e hg --revert .
In addition, I looked at Bookmarks where it says that the delete feature still leaves changed files. How do I go to a state where I can start afresh from the contents of the remote repository?

A: A bookmark is separate from the changes in the changeset. You can modify or delete the bookmark, and it keeps the changeset untouched. A physical bookmark is a good analogy: you can move it from page to page or remove it completely without altering the book contents - it's just a pointer to a page.
If you have committed the changes already into a changeset, you want to either back them out or strip them.
If you just want to start from the remote, delete your repository and re-clone it.


text:
Q: How would I achieve encryption/decryption for users, while also having the ability to decrypt everything serverside I'm not entirely sure if I should be encrypting data server side or client side to begin with. The data is a json object of some user input. What I need to be able to do:
a) encrypt data at rest [in dynamoDB]
b) decrypt data and send it back to the user when they request it
c) decrypt the entire database to run analytics and ML
First Approach
1)Send the newly inputted user data through HTTPS, then encrypt it server side before it hits the database (in a lambda function). Now the data is encrypted at rest.
2) When a user makes a GET request, have a lambda function that decrypts it before returning it to the user
3) simply run a decryption on the database with the same technique
I'm not sure if this is good or bad, what type of encryption to use, etc.
EDIT: I will be doing server side encryption. If anyone has any suggestions/guides on a simple but good way to do it, perhaps using some npm package, that would be great.

A: Question 1: Encrypt server side or client side?
The only advantage of client-side encryption would be performance: remove the burden of your server from doing this work, pass it off to the end user machine.
However, there is a very big disadvantage: security.  If you are encrypting everybody's data with the same key, then now everybody has access to that key, because it needs to be delivered to the client for decryption.  You have entirely defeated the purpose of the security, because the cryptographic key now lives everywhere.
What about encrypting every user's data with different keys?  That's a can-of-worms question, because you need to then consider where you are storing all the cryptographic keys.  If it is in the same database as the data, you have again defeated the purpose of encryption -- putting the keys and data together is a no-no.  You can come up with arbitrary solutions around this, but I assure you there are many considerations and you are inviting a lot of complexity.
Question 2: Is your approach reasonable?
Yes it is, but you need to understand what you are protecting against.  Encryption at rest mainly protects a database (including backups) provided that the encryption key never gets put in the same place as the database.  Managing the encryption key is something that needs to be carefully considered.  There is good guidance on that if you care to research it, but it really is the task of a security architect to design this right.

A: You can use AES encryption using cryptojs.
Hit the server to get key for using in encryption process.
        let AES = CryptoJS.AES()

        // AES encryption
        let encryptedUsername:String! = AES.encrypt(secretMessage: (username_tf.text)!, secretKey: REQUESTKEY!)
        let encryptedPassword:String! = AES.encrypt(secretMessage: (password_tf.text)!, secretKey: REQUESTKEY!)


text:
Q: How can I revert multiple Git commits? I have a Git repository that looks like this:
A <- B <- C <- D <- HEAD

I want the head of the branch to point to A, i.e., I want B, C, D, and HEAD to disappear and I want head to be synonymous with A.
It sounds like I can either try to rebase (doesn't apply, since I've pushed changes in between), or revert. But how do I revert multiple commits? Do I revert one at a time? Is the order important?

A: Similar to Jakub's answer, this allows you to easily select consecutive commits to revert.
# Revert all commits from and including B to HEAD, inclusively
git revert --no-commit B^..HEAD
git commit -m 'message'

A: The easy way to revert a group of commits on shared repository (that people use and you want to preserve the history) is to use git revert in conjunction with git rev-list. The latter one will provide you with a list of commits, the former will do the revert itself.
There are two ways to do that. If you want the revert multiple commits in a single commit use:
for i in `git rev-list <first-commit-sha>^..<last-commit-sha>`; do git revert --no-commit $i; done

this will revert a group of commits you need, but leave all the changes on your working tree, you should commit them all as usual afterward.
Another option is to have a single commit per reverted change:
for i in `git rev-list <first-commit-sha>^..<last-commit-sha>`; do git revert --no-edit -s $i; done

For instance, if you have a commit tree like
 o---o---o---o---o---o--->
fff eee ddd ccc bbb aaa

to revert the changes from eee to bbb, run
for i in `git rev-list eee^..bbb`; do git revert --no-edit -s $i; done

A: I'm so frustrated that this question can't just be answered.  Every other question is in relation to how to revert correctly and preserve history.  This question says "I want the head of the branch to point to A, i.e. I want B, C, D, and HEAD to disappear and I want head to be synonymous with A."
git checkout <branch_name>
git reset --hard <commit Hash for A>
git push -f

I learned a lot reading Jakub's post, but some guy in the company (with access to push to our "testing" branch without a Pull-Request) pushed like five bad commits, trying to fix and fix and fix a mistake he made five commits ago.  Not only that, but one or two pull requests were accepted, which were now bad.  So forget it; I found the last good commit (abc1234) and just ran the basic script:
git checkout testing
git reset --hard abc1234
git push -f

I told the other five guys working in this repository that they better make note of their changes for the last few hours and wipe/rebranch from the latest testing.  End of the story.

A: First be sure that your working copy is not modified.
Then:
git diff --binary HEAD commit_sha_you_want_to_revert_to | git apply

And then just commit. Don't forget to document what the reason is for the revert.

A: None of those worked for me, so I had three commits to revert (the last three commits), so I did:
git revert HEAD
git revert HEAD~2
git revert HEAD~4
git rebase -i HEAD~3 # pick, squash, squash

Worked like a charm :)

A: Clean way which I found useful
git revert --no-commit HEAD~3..
git commit -m "your message regarding reverting the multiple commits"

This command reverts last 3 commits with only one commit.
Also doesn't rewrite history, so doesn't require a force push.
The .. helps create a range. Meaning HEAD~3.. is the same as HEAD~3..HEAD

A: In my opinion a very easy and clean way could be:
go back to A
git checkout -f A

point master's head to the current state
git symbolic-ref HEAD refs/heads/master

save
git commit

A: Probably less elegant than other approaches here, but I've always used get reset --hard HEAD~N to undo multiple commits, where N is the number of commits you want to go back.
Or, if unsure of the exact number of commits, just running git reset --hard HEAD^ (which goes back one commit) multiple times until you reach the desired state.

A: For doing so you just have to use the revert command, specifying the range of commits you want to get reverted.
Taking into account your example, you'd have to do this (assuming you're on branch 'master'):
git revert master~3..master

or git revert B...D or git revert D C B
This will create a new commit in your local with the inverse commit of B, C and D (meaning that it will undo changes introduced by these commits):
A <- B <- C <- D <- BCD' <- HEAD

A: Using Git Restore
You can also use the restore command:
A <- B <- C <- D <- HEAD

Let's say you want HEAD to look exactly like A. Make sure you've pulled the latest master. Then cut a new branch.
git switch -c feature/flux-capacitor  # synonymous with checkout -b
git restore --source A .
git add .
git commit
git push

The restore command changes everything (.) to what it was at the --source commit. Then you commit that to your local branch and push it to the origin. You can then open a PR against it.
This has the benefit of not changing any history that others might have based work on. It also leaves a useful history for folks in the future.
Docs: git restore

A: This is an expansion of one of the solutions provided in Jakub's answer.
I was faced with a situation where the commits I needed to roll back were somewhat complex, with several of the commits being merge commits, and I needed to avoid rewriting history.  I was not able to use a series of git revert commands because I eventually ran into conflicts between the reversion changes being added.  I ended up using the following steps.
First, check out the contents of the target commit while leaving HEAD at the tip of the branch:
git checkout -f <target-commit> -- .

(The -- makes sure <target-commit> is interpreted as a commit rather than a file; the . refers to the current directory.)
Then, determine what files were added in the commits being rolled back, and thus need to be deleted:
git diff --name-status --cached <target-commit>

Files that were added should show up with an "A" at the beginning of the line, and there should be no other differences.  Now, if any files need to be removed, stage these files for removal:
git rm <filespec>[ <filespec> ...]

Finally, commit the reversion:
git commit -m 'revert to <target-commit>'

If desired, make sure that we're back to the desired state:
git diff <target-commit> <current-commit>

There should be no differences.

A: I found myself needing to revert a long range of commits and then re-revert them to help a team present a clear pull request without having to force-push over their target branch (which was committed directly to)
# checkout the branch that should be targeted
git checkout $branch_target

# revert the commits in $branch_target to some $count where
#   $count is the number of commits to revert
#   cut is used to slice just the commit hash field from each line of output
#   xargs runs the command once for each line of input, reversing the commits!
git log --oneline -n $count | cut -d' ' -f1 | xargs git revert

# check out the branch which should be the source of the pull request
git checkout -b $branch_for_pull

# revert the revert commits
# $count is that same number of commits being reverted (again)
git log --oneline -n $count | cut -d' ' -f1 | xargs git revert

# push branches up and go off to create PR in whatever web UI
git push --set-upstream origin $branch_for_pull  # it's new!
git checkout $branch_target
git push  # if this branch wasn't pushed, just fix the issue locally instead..

Because this reverts all of the commits from HEAD to git log -n $count in reverse order, it'll work well and cleanly with any number of commits
View from $branch_target at this state
% git log --oneline origin/$branch_target
ffff006 (origin/$branch_target, $branch_target) Revert "first commit"
ffff005 Revert "second commit"
ffff004 Revert "third commit"
ffff003 third commit
ffff002 second commit
ffff001 first commit

View from $branch_for_pull at this state
% git log --oneline origin/$branch_for_pull
ffff009 (origin/$branch_for_pull, $branch_for_pull) Revert "Revert "third commit""
ffff008 Revert "Revert "second commit""
ffff007 Revert "Revert "first commit""
ffff006 (origin/$branch_target, $branch_target) Revert "first commit"
ffff005 Revert "second commit"
ffff004 Revert "third commit"
ffff003 third commit
ffff002 second commit
ffff001 first commit

If the intention was to create N branches with changesets, but they were all committed to the same branch, you can still revert all of them back to the base commit, then only revert the reverts needed as the changesets should be ordered logically (try saying that 5x fast)
Using a syntax like HEAD~7..HEAD~5 may help with describing the ranges to precisely split the revert-revert branches
Here, it would make sense when reverting the last 7 commits (git log -n 7), but restoring 5 with in one branch (git log -n 5) and 2 then the top-most 2 in another git log HEAD~12..HEAD~10 (12 is 7 commits + 5 commits, assuming the new PR branch is based off either the branch "before" it, or the result of a FF (non-squashed) merge the branch "before" it into the original target branch)

A: Expanding what I wrote in a comment
The general rule is that you should not rewrite (change) history that you have published, because somebody might have based their work on it.  If you rewrite (change) history, you would make problems with merging their changes and with updating for them.
So the solution is to create a new commit which reverts changes that you want to get rid of.  You can do this using git revert command.
You have the following situation:

A <-- B  <-- C <-- D                                  <-- master <-- HEAD

(arrows here refers to the direction of the pointer: the "parent" reference in the case of commits, the top commit in the case of branch head (branch ref), and the name of branch in the case of HEAD reference).
What you need to create is the following:

A <-- B  <-- C <-- D <-- [(BCD)-1]                   <-- master <-- HEAD

where [(BCD)^-1] means the commit that reverts changes in commits B, C, D.  Mathematics tells us that (BCD)-1 = D-1 C-1 B-1, so you can get the required situation using the following commands:
$ git revert --no-commit D
$ git revert --no-commit C
$ git revert --no-commit B
$ git commit -m "the commit message for all of them"

Works for everything except merge commits.

Alternate solution would be to checkout contents of commit A, and commit this state.  Also works with merge commits.  Added files will not be deleted, however.  If you have any local changes git stash them first:
$ git checkout -f A -- . # checkout that revision over the top of local files
$ git commit -a

Then you would have the following situation:

A <-- B  <-- C <-- D <-- A'                       <-- master <-- HEAD

The commit A' has the same contents as commit A, but is a different commit (commit message, parents, commit date).

Alternate solution by Jeff Ferland, modified by Charles Bailey builds upon the same idea, but uses git reset.  Here it is slightly modified, this way WORKS FOR EVERYTHING:
$ git reset --hard A
$ git reset --soft D # (or ORIG_HEAD or @{1} [previous location of HEAD]), all of which are D
$ git commit

A: git reset --hard a
git reset --mixed d
git commit

That will act as a revert for all of them at once. Give a good commit message.

A: I really wanted to avoid hard resets, this is what I came up with.
A -> B -> C -> D -> HEAD

To go back to A (which is 4 steps back):
git pull                  # Get latest changes
git reset --soft HEAD~4   # Set back 4 steps
git stash                 # Stash the reset
git pull                  # Go back to head
git stash pop             # Pop the reset
git commit -m "Revert"    # Commit the changes

A: If you

*

*have a merged commit and

*you are not able to revert, and

*you don't mind squashing the history you are to revert,

then you can
git reset --soft HEAD~(number of commits you'd like to revert)
git commit -m "The stuff you didn't like."
git log
# copy the hash of your last commit
git revert <hash of your last (squashed) commit>

Then when you want to push your changes remember to use the -f flag because you modified the history
git push <your fork> <your branch> -f

A: If you want to temporarily revert the commits of a feature, then you can use the series of following commands.
Here is how it works
git log --pretty=oneline | grep 'feature_name' | cut -d ' ' -f1 | xargs -n1 git revert --no-edit


text:
Q: Mix container-fluid with two backgrounds I want to get the effect from below pic.
1,2,3 sections is div class=container but I have no idea

A: As far as I understood your post, there are two ways to achieve the structure of your image.

*

*To use -offset- classes in order to have paddings:

A

B

C

Here is the fiddle: http://jsfiddle.net/johannesMt/fnj286ew/1/

*Apply container and  container-fluid classes to the sections according to their width. If you want to have padding from the left and right sides then use container and if you want to have full-width then use container-fluid.

Something like this:

A

B

C

D

E

F

G

H

I

J

Here is working example:

if your screen is not large then stretch the window in jsfiddle to see
  the effect.

http://jsfiddle.net/johannesMt/BMY36/125/


text:
Q: JSP/R Error: java.lang.NoClassDefFoundError : org/rosuda/JRI/Rengine Please, I need your help.
I have this java class
package com.stephen.crawler;

import org.rosuda.JRI.Rengine;

public class JRI_Interface {

    Rengine r;
    String str_globalPath="/home/pavel/workspace/opendata/r_script/";

public JRI_Interface (String str_fuente) {
    r = new Rengine(new String[] { "--no-save" }, false, null);
    r.eval("source(\""+str_globalPath+str_fuente+"\")");
}

public void exec_RProcedure(String str_procedure) {
    r.eval(str_procedure);
}

public String[] exec_RFunction (String str_procedure) {

    return r.eval(str_procedure).asStringArray();
}

}

And it works perfectly if I execute :
package com.stephen.crawler;

public class JRI_Start_1 {
    public static void main(String[] args)
    {

        JRI_Interface j = new JRI_Interface("staticdata.r");
        j.exec_RProcedure("loadParametersOD()");
        String obj[]=j.exec_RFunction("getLoadedParametersOD()");
        System.out.println (obj.length);

    }
}

However, when I execute using jsp with Tomcat :
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
%>
<%@ page import="com.stephen.crawler.*" %>
<%@ page import="org.rosuda.JRI.*" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>My Title</title>
</head>
<%
JRI_Interface j = new JRI_Interface("staticdata.r");
j.exec_RProcedure("loadParametersOD()");
String obj[]=j.exec_RFunction("getLoadedParametersOD()");
%>

<body>

</body>
</html>

I get the following message:
> org.apache.jasper.JasperException: Ha sucedido una excepción al
> procesar la página JSP /Inicio.jsp en línea 14
>
> 11: <title>My Title</title>
> 12: </head>
> 13: <%
> 14: JRI_Interface j = new JRI_Interface("staticdata.r");
> 15: j.exec_RProcedure("loadParametersOD()");
> 16: String obj[]=j.exec_RFunction("getLoadedParametersOD()");
> 17: %>
>
> Stacktrace:
>   org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:574)
>   org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:461)
>   org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
>   org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
>   javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
>   org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
> causa raíz
>
> javax.servlet.ServletException: java.lang.NoClassDefFoundError:
> org/rosuda/JRI/Rengine
>   org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:909)
>   org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:838)
>   org.apache.jsp.Inicio_jsp._jspService(Inicio_jsp.java:146)
>   org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
>   javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
>   org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
>   org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
>   org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
>   javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
>   org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
> causa raíz
>
> java.lang.NoClassDefFoundError: org/rosuda/JRI/Rengine
>   com.stephen.crawler.JRI_Interface.<init>(JRI_Interface.java:12)
>   org.apache.jsp.Inicio_jsp._jspService(Inicio_jsp.java:124)
>   org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
>   javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
>   org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
>   org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
>   org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
>   javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
>   org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
> causa raíz
>
> java.lang.ClassNotFoundException: org.rosuda.JRI.Rengine
>   org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1333)
>   org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1167)
>   com.stephen.crawler.JRI_Interface.<init>(JRI_Interface.java:12)
>   org.apache.jsp.Inicio_jsp._jspService(Inicio_jsp.java:124)
>   org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
>   javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
>   org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
>   org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
>   org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
>   javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
>   org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

Do I miss something?. I think I have configure everything.... .
Many thanks.

A: For Tomcat 6, all unpacked classes and resources in the /WEB-INF/classes directory of your web application, plus classes and resources in JAR files under the /WEB-INF/lib directory of your web application, are made visible to this web application, but not to other ones.
The server environment is initialized in this order:

*

*Bootstrap classes of your JVM

*System class loader classes (fi, '$JAVA_HOME/jre/lib/ext')

*/WEB-INF/classes of your web application

*/WEB-INF/lib/*.jar of your web application

*Common class loader classes (if you've no other option)
('common.loader' property in $CATALINA_BASE/conf/catalina.properties)

Your servlet/webappX/jsp likely needs the class(es) or jar(s) in the bold directory(s).  Your server seems properly configured for Tomcat/jsp since it's showing errors in your code/config.  Your code that runs the REngine properly is allowed to use the command-line or env CLASSPATH but it's not that simple from Tomcat or other web server.  Hopefully it's just a matter of copying the REngine jar though you may have to tweak its config.
GL


text:
Q: WPF: Hiding object causes brief flash before disappearing I have a simple button style which has data trigger which binds to a bool property and if property is false it hides the button using simple fade out animation and vice-versa.
But for some unknown reason, for the first time when I perform some task which sets the bool value to false. It gives a brief flash before fading out. Upon setting it to true everything is as expected.
My style is
 <Style x:Key="CustomButtonStyle" TargetType="{x:Type Button}" >
    <Style.Triggers>
        <DataTrigger Binding="{Binding IsButtonVisible}" Value="true">
            <DataTrigger.EnterActions>
                <BeginStoryboard>
                    <Storyboard Storyboard.TargetProperty="Opacity" >
                        <DoubleAnimation Duration="0:0:0.2" To="1"/>
                    </Storyboard>
                </BeginStoryboard>
            </DataTrigger.EnterActions>
            <DataTrigger.ExitActions>
                <BeginStoryboard>
                    <Storyboard Storyboard.TargetProperty="Opacity" >
                        <DoubleAnimation Duration="0:0:0.2" To="0"/>
                    </Storyboard>
                </BeginStoryboard>
            </DataTrigger.ExitActions>
        </DataTrigger>
        <Trigger Property="Opacity" Value="0">
            <Setter Property="Visibility" Value="Collapsed"></Setter>
        </Trigger>
        <Trigger Property="Opacity" Value="1" >
            <Setter Property="Visibility" Value="Visible"></Setter>
        </Trigger>
    </Style.Triggers>
    <Style.Setters>
        <Setter Property="Height" Value="93"/>
        <Setter Property="Width" Value="93"/>
        <Setter Property="Opacity" Value="0"/>
     </Style.Setters>
</Style>

Note:-
Default value of IsButtonVisible is true

A: Why do you have two DataTrigger? Try this solution, maybe it solves your problem.
        <Style x:Key="DefaultButtonStyle" TargetType="{x:Type Button}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding IsVisible}" Value="true">
                <DataTrigger.EnterActions>
                    <BeginStoryboard>
                        <Storyboard FillBehavior="HoldEnd" Storyboard.TargetProperty="Opacity">
                            <DoubleAnimation Duration="0:0:0.2"  To="1"/>
                        </Storyboard>
                    </BeginStoryboard>
                </DataTrigger.EnterActions>
                <DataTrigger.ExitActions>
                    <BeginStoryboard>
                        <Storyboard Storyboard.TargetProperty="Opacity" >
                            <DoubleAnimation Duration="0:0:0.2"  To="0" />
                        </Storyboard>
                    </BeginStoryboard>
                </DataTrigger.ExitActions>
            </DataTrigger>
            <Trigger Property="Opacity" Value="0">
                <Setter Property="Visibility" Value="Collapsed"></Setter>
            </Trigger>
            <Trigger Property="Opacity" Value="1">
                <Setter Property="Visibility" Value="Visible"></Setter>
            </Trigger>
        </Style.Triggers>
        <Style.Setters>
            <Setter Property="Height" Value="93"/>
            <Setter Property="Width" Value="93"/>
            <Setter Property="Opacity" Value="0"/>
        </Style.Setters>
    </Style>

Edit:

XAML

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApplication1"
    mc:Ignorable="d"
    Title="MainWindow" Height="279.716" Width="279.784"
    DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Window.Resources>
    <Style x:Key="ButtonStyleTrue" TargetType="{x:Type Button}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding VisibleTrue}" Value="true">
                <DataTrigger.EnterActions>
                    <BeginStoryboard>
                        <Storyboard FillBehavior="HoldEnd" Storyboard.TargetProperty="Opacity">
                            <DoubleAnimation Duration="0:0:0.2"  To="1"/>
                        </Storyboard>
                    </BeginStoryboard>
                </DataTrigger.EnterActions>
                <DataTrigger.ExitActions>
                    <BeginStoryboard>
                        <Storyboard Storyboard.TargetProperty="Opacity" >
                            <DoubleAnimation Duration="0:0:0.2"  To="0" />
                        </Storyboard>
                    </BeginStoryboard>
                </DataTrigger.ExitActions>
            </DataTrigger>
            <Trigger Property="Opacity" Value="0">
                <Setter Property="Visibility" Value="Collapsed"></Setter>
            </Trigger>
            <Trigger Property="Opacity" Value="1">
                <Setter Property="Visibility" Value="Visible"></Setter>
            </Trigger>
        </Style.Triggers>
        <Style.Setters>
            <Setter Property="Height" Value="93"/>
            <Setter Property="Width" Value="93"/>
            <Setter Property="Opacity" Value="0"/>
        </Style.Setters>
    </Style>
    <Style x:Key="ButtonStyleFalse" TargetType="{x:Type Button}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding VisibleFalse}" Value="true">
                <DataTrigger.EnterActions>
                    <BeginStoryboard>
                        <Storyboard FillBehavior="HoldEnd" Storyboard.TargetProperty="Opacity">
                            <DoubleAnimation Duration="0:0:0.2"  To="1"/>
                        </Storyboard>
                    </BeginStoryboard>
                </DataTrigger.EnterActions>
                <DataTrigger.ExitActions>
                    <BeginStoryboard>
                        <Storyboard Storyboard.TargetProperty="Opacity" >
                            <DoubleAnimation Duration="0:0:0.2"  To="0" />
                        </Storyboard>
                    </BeginStoryboard>
                </DataTrigger.ExitActions>
            </DataTrigger>
            <Trigger Property="Opacity" Value="0">
                <Setter Property="Visibility" Value="Collapsed"></Setter>
            </Trigger>
            <Trigger Property="Opacity" Value="1">
                <Setter Property="Visibility" Value="Visible"></Setter>
            </Trigger>
        </Style.Triggers>
        <Style.Setters>
            <Setter Property="Height" Value="93"/>
            <Setter Property="Width" Value="93"/>
            <Setter Property="Opacity" Value="0"/>
        </Style.Setters>
    </Style>
</Window.Resources>
<Grid>
    <Button Content="Button" HorizontalAlignment="Left" Margin="187,11,0,0" VerticalAlignment="Top" Width="75" Click="Button_OnClick"/>
    <Button Style="{StaticResource ButtonStyleFalse}" Content="Button" HorizontalAlignment="Left" Margin="47,66,0,0" VerticalAlignment="Top" Width="75"/>
    <TextBlock x:Name="textBlock_true" HorizontalAlignment="Left" Margin="193,68,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"/>
    <Button Style="{StaticResource ButtonStyleTrue}" Content="Button" HorizontalAlignment="Left" Margin="47,143,0,0" VerticalAlignment="Top" Width="75"/>
    <TextBlock x:Name="textBlock_false" HorizontalAlignment="Left" Margin="193,145,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"/>
</Grid>

Code Behind

using System.ComponentModel;
using System.Windows;

namespace WpfApplication1
{
public partial class MainWindow : Window, INotifyPropertyChanged
{

    /// <summary>
    /// Initalvalue is true;
    /// </summary>
    public bool VisibleTrue
    {
        get { return _VisibleTrue; }
        set
        {
            if (_VisibleTrue == value) return;
            _VisibleTrue = value;
            textBlock_true.Text = value ? "True" : "False";
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("VisibleTrue"));
        }
    }
    private bool _VisibleTrue = true;

    /// <summary>
    /// Initialvalue is false
    /// </summary>
    public bool VisibleFalse
    {
        get { return _VisibleFalse; }
        set
        {
            if (_VisibleFalse == value) return;
            _VisibleFalse = value;
            textBlock_false.Text = value ? "True" : "False";
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("VisibleFalse"));
        }
    }
    private bool _VisibleFalse;

    public MainWindow()
    {
        InitializeComponent();

        textBlock_true.Text = "Application started";
        textBlock_false.Text = "Application started";
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void Button_OnClick(object sender, RoutedEventArgs e)
    {
        VisibleTrue = !VisibleTrue;
        VisibleFalse = !VisibleTrue;
    }
}
}

Preview

A: To prevent setting your bound property IsButtonVisible while animation performs you could add the following to your ViewModel:
private bool _animationInProgress = false;
private readonly object _animationLock = new object();
private bool _isButtonVisible = true;

public bool IsButtonVisible {
    get { return _isButtonVisible; }
    set {
        lock (_animationLock) {
            if (value == _isButtonVisible || _animationInProgress) return;
            _animationInProgress = true;
        }
        _isButtonVisible = value;
        OnPropertyChanged();
        Timer animationDoneTimer = new Timer {Interval = 200, Enabled = true, AutoReset = false};
        animationDoneTimer.Elapsed += (sender, args) => {
                                          lock (_animationLock) {
                                              _animationInProgress = false;
                                          }
                                      };

    }
}

As second thing I would remove the Trigger:
<Trigger Property="Opacity" Value="1" >
    <Setter Property="Visibility" Value="Visible"></Setter>
</Trigger>

For the behaviour, that you'd like to set Visibility to Collapsed on Opacity == 0 and Visibility to Visible on Opacity =! 0 you should do it this way:
    ...
        <Trigger Property="Opacity" Value="0">
            <Setter Property="Visibility" Value="Collapsed" />
        </Trigger>
        <!-- Trigger removed -->
    </Style.Triggers>
    <Style.Setters>
        <!-- Visibilities value if Trigger Opacity == 0 does not fire  -->
        <Setter Property="Visibility" Value="Visible" />

        <Setter Property="Height" Value="93"/>
        <Setter Property="Width" Value="93"/>
        <Setter Property="Opacity" Value="0"/>
    </Style.Setters>
</Style>


text:
Q: ZSH not sourcing zprofile I'm running zsh 5.1.1 on Ubuntu 16.04.  It seems that ~/.zprofile isn't sourced at login nor new terminal.  ~/.zshrc is sourced however.
I am running oh-my-zsh.
Any ideas on why this is or how I can fix it?

A: ~/.zprofile is only sourced when zsh is run as login shell, e.g. when logging in on the console or via SSH.
It will not be sourced by zsh when opening a new terminal or starting a new zsh session from within a running session. Anything you need in all interactive sessions, should be set in ~/.zshrc. Anything you need in all zsh sessions, including scripts, should be set in ~/.zshenv.
You can find additional information in the zshall manpage and on this site.
~/.zshprofile will (usually) also not be parsed by any other tools. So any environment variables set in ~/.zprofile will usually not be available in an X11 session. If you need some environment variable to be available globally in your session, you might want to have a look at man pam_env.

A: I had the same issue and found out that while ~/.zprofile seems to be ignored, ~/.profile still gets sourced.
Not sure why this is the case, but simply moving things from .zprofile to .profile solved the problem for me...


text:
Q: Is gcc compile time proportional to number of executions or lines of code? I am using gcc 4.8.5 to compile a c++98 code. My c++ code statically initializes unordered_map of unoredred_maps with ~20,000 total key-value pairs, and overloaded function which will take ~450 different types. This program will be executed on a continuous stream of data, and for every block of data, overloaded function will return an output.
The problem is, gcc takes too long to compile due to initializing  ~20,000 key-value pairs.
The nested unordered_map has a structure of map< DATATYPE, map< key, value >>, and only one of the overloaded function gets called for each data input. In other words, I do not need to statically initialize the entire nested map, but I can instead dynamically define map<key, value> for the corresponding datatype when needed. For example, I can check for the definition of a map and when it is undefined, I can later populate it in run time. This will result a map with ~45 average key-value pairs.
However, I know that dynamic initialization will require longer code. For a simple execution described above (statically initializing entire map), will other method such as dynamic initialization significantly reduce time? My understanding is, whatever alternative I take, I still need to write a code to populate entire key-value pairs. Also, overhead and actual computation that goes behind populating an unordered_map (hashmap) should not differ asymptotically in most cases, and should not show significant difference than running same number of loops to increment a value.
For reference, I am writing a python script that reads in multiple json files to print out the c++ code, which then gets compiled using gcc. I am not reading json directly from c++ so whatever I do, c++ source will need to insert key-value one by one because it will not have access to json file.
// below is someEXE.cpp, which is a result from python script.
// Every line is inside python's print"" (using python 2.7)
// so that it can write complete c++ that should  compile.

someEXE.cpp

// example of an overloaded function among ~450
// takes in pointer to data and exampleMap created above
void exampleFunction(DIFFERENT_TYPE1*data,
std::unorderd_map<std::string, std::unordered_map<std::string, std::string>> exampleMap) {
   printf("this is in specific format: %s", exampleMap["DATATYPE1"]
   [std::to_string(data->member_variable)].c_str();
   //... more print functions below (~25 per datatype)
};

int main() {

   // current definition of the unordered_map (total ~20,000 pairs)
   std::unordered_map<std::string, std::unordered_map<std::string,
   std::string>> exampleMap = {
       {"DATATYPE1", {{"KEY1", "VAL1"}, {"KEY2", "VAL2"}, /*...*/}}
   };

   // create below test function for all ~450 types
   // when I run the program, code will printf values to screen
   DIFFERENT_TYPE1 testObj = {0};
   DIFFERENT_TYPE1 *testObjPointer = &testObj;
   exampleFunction(testObjPointer, exampleMap);

   return 0;
}

EDIT: My initial question was "Is CMAKE compile time proportional to...". Changed the term "CMAKE" with actual compiler name, gcc 4.8.5 with the help from the comments.

A: With the further code you posted, and Jonathan Wakely's answer on the specific issue with your compiler, I can make a suggestion.
When writing my own codegen, if possible, I prefer generating plain old data and leaving logic and behaviour in non-generated code. This way you get a small(er) pure C++ code in data-driven style, and a separate block of dumb and easy-to-generate data in declarative style.
For example, directly code this
// GeneratedData.h
namespace GeneratedData {
  struct Element {
    const char *type;
    const char *key;
    const char *val;
  };

  Element const *rawElements();
  size_t rawElementCount();
}

and this
// main.cpp
#include "GeneratedData.h"

#include <string>
#include <unordered_map>

using Map = std::unordered_map<std::string, std::string>;
using TypeMap = std::unordered_map<std::string, Map>;

TypeMap buildMap(GeneratedData::Element const *el, size_t count)
{
  TypeMap map;
  for (; count; ++el, --count) {
    // build the whole thing here
  }
}
// rest of main can call buildMap once, and keep the big map.
// NB. don't pass it around by value!

and finally generate the big dumb file
// GeneratedData.cpp
#include "GeneratedData.h"

namespace {
  GeneratedData::Element const array[] = {
    // generated elements here
  };
}

namespace GeneratedData {
  Element const *rawElements { return array; }
  size_t rawElementCount() { return sizeof(array)/sizeof(array[0]); }
}

if you really want to, you can separate even that logic from your codegen by just #includeing it in the middle, but it's probably not necessary here.

Original answer

Is CMAKE

CMake.

... compile time

CMake configures a build system which then invokes your compiler. You haven't told us which build system it is configuring for you, but you could probably run it manually for the problematic object file(s), and see how much of the overhead is really CMake's.

... proportional to number of executions or lines of code?

No.
There is some overhead per-execution. Each executed compiler process has some overhead per line of code, but probably much more overhead per enabled optimization, and some optimizations may scale with cyclomatic complexity or other metrics.

statically initializes unordered_map of unoredred_maps with ~20,000 total key-value pairs

You should try to hide your giant initialization as much as possible - you haven't shown any code, but if it's only visible in one translation unit, only one object file will take a very long time to compile.
You could also probably use a codegen tool like gperf to build a perfect hash.
I can't give you a lot more detail without seeing at least a fragment of your actual code and some hint as to how your files and translation units are layed out.

A: Older versions of GCC take a very long time to compile large initializer-lists like this:
unordered_map<string, unordered_map<string, string>> exampleMap = {
    {"DATATYPE1", {{"KEY1", "VAL1"}, {"KEY2", "VAL2"}, /*...*/}}
};

The problem is that every new element in the initializer-list causes more code to be added to the block being compiled, and it gets bigger and bigger, needing to allocate more and more memory for the compiler's AST. Recent versions have been changed to process the initializer-list differently, although some problems still remain. Since you're using GCC 4.8.5 the recent improvements won't help you anyway.

However, I know that dynamic initialization will require longer code. For a simple execution described above (statically initializing entire map), will other method such as dynamic initialization significantly reduce time?

Splitting the large initializer-list into separate statements that insert elements one-by-one will definitely reduce the compile time when using older versions of GCC. Each statement can be compiled very quickly that way, instead of having to compile a single huge initialization that requires allocating more and more memory for each element.


text:
Q: Show all records of a MySQL field in a Select HTML Good day, I am making a system for the university of the reservation of some mini-auditors, One (01) user can make several reservations and after booking the user must inform the payment by uploading a pdf.
To the user I show a form to inform the payment by uploading the pdf with the reservation number and the mini-audit, but if I have several reservations I need to show them all so that he selects which of all the reservations he made paid and wants to inform, as I have the code now only shows me the first reservation and I hope that when I click on the "select" HTML I will display all the reservation numbers that it has together with the mini-audit associated with that reservation. Then I leave the code (I apologize, I'm learning and I probably have many errors, Im sorry for my bad english too):
This is an example that how looks now https://i.imgur.com/XvRdRTe.gif

<?php
session_start();
 include '/login/funcs/funcs.php';
 include_once 'config.inc.php';

 if(!isset($_SESSION["id_usuario"])){ //Si no ha iniciado sesión redirecciona a index.php
  header("Location: index.php");
 }

 $idUsuario = $_SESSION['id_usuario'];

  $db=new Conect_MySql();
  $sql2 = "SELECT `idsolicitudes`, `id`, `nombre_sala` FROM solicitudes WHERE `id`=$idUsuario";
  $query2 = $db->execute($sql2);
  $datos=$db->fetch_row($query2);

  $sql3 = "SELECT `id`, `usuario`, `nombre`, `apellido` FROM usuarios WHERE `id`=$idUsuario";
  $query3 = $db->execute($sql3);
  $datos2=$db->fetch_row($query3);

   echo $datos['usuario'];
?>

<!DOCTYPE html>

  <?php

if (isset($_POST['subir'])) {
    $nombre = $_FILES['archivo']['name'];
    $tipo = $_FILES['archivo']['type'];
    $tamanio = $_FILES['archivo']['size'];
    $ruta = $_FILES['archivo']['tmp_name'];
    $destino = "archivos/" . $nombre;
    if ($nombre != "") {
        if (copy($ruta, $destino)) {
            $titulo= $_POST['titulo'];
            $descri= $_POST['descripcion'];
   $solicitud = $_POST ['solicitud'];
            $db=new Conect_MySql();
            $sql = "INSERT INTO tbl_documentos(idsolicitud, id, titulo,descripcion,tamanio,tipo,nombre_archivo) VALUES('$solicitud','$idUsuario','$titulo','$descri','$tamanio','$tipo','$nombre')";
            $query = $db->execute($sql);
            if($query){
    echo '';

   /*
                echo "";*/

            }
        } else {
            echo "Error";
        }
    }
}
?>

Informános tu pago

Sube tu comprobante de deposito o transferencia solo despues de haber reservado

   <form method="post" action="" enctype="multipart/form-data">

                        Miniauditorio

        <select id="disabledSelect" name="titulo"  style="WIDTH: 228px; HEIGHT: 40px"  class="form-control" placeholder="<?php echo $datos['nombre_sala']; ?>">
       <option placeholder="<?php echo $datos['idsolicitud']; ?>"><?php echo $datos['nombre_sala']; ?></option>

        </select>

Nombre Titular

<input style="WIDTH: 250px; HEIGHT: 35px"  class="form-control" style="color:black" name="descripcion" disabled value="<?php echo $datos2['nombre']; ?> <?php echo $datos2['apellido']; ?>">

Número de Solicitud

        <select id="disabledSelect" name="titulo"  style="WIDTH: 228px; HEIGHT: 40px"  class="form-control" placeholder="<?php echo $datos['nombre_sala']; ?>">
       <option placeholder="<?php echo $datos['idsolicitud']; ?>"><?php echo $datos['idsolicitudes']; ?></option>

        </select>

      <input type="file" name="archivo">

<input align="center" class="btn btn-success" type="submit" value="Subir" name="subir">

Antes de enviarnos su información, verifique que su archivo este guardado en formato PDF

            </form>

This is my connection functions

<?php

class Conect_MySql {
     var $obj = array ( "dbname" => "login",
                       "dbuser"  => "root"  ,
                       "dbpwd"  => ""  ,
                       "dbhost"  => "localhost" );

     var $q_id ="";
     var $ExeBit ="";
     var $db_connect_id = "";
     var $query_count   = 0;
    private function connect(){
  $this->db_connect_id = mysqli_connect($this->obj['dbhost'],$this->obj['dbuser'],$this->obj['dbpwd'],$this->obj['dbname']);
             if (!$this->db_connect_id)
              {
                echo (" Error no se puede conectar al servidor:".mysqli_connect_error());
       }
  }

function execute($query) {
        $this->q_id = mysqli_query($this->db_connect_id,$query);
        if(!$this->q_id ) {
            $error1 = mysqli_error($this->db_connect_id);
            die ("ERROR: error DB.
 No Se Puede Ejecutar La Consulta:
 $query
MySql Tipo De Error: $error1");
            exit;
        }
 $this->query_count++;
 return $this->q_id;
    }

  public function fetch_row($q_id = "") {
     if ($q_id == "") {
      $q_id = $this->q_id;
      }
        $result = mysqli_fetch_array($q_id);
        return $result;
    }

 public function get_num_rows() {
        return mysqli_num_rows($this->q_id);
    }

public function get_row_affected(){
    return mysqli_affected_rows($this->db_connect_id);
}

public function get_insert_id() {
    return mysqli_insert_id($this->db_connect_id);
}

public  function free_result($q_id) {
     if($q_id == ""){
      $q_id = $this->q_id;
  }
 mysqli_free_result($q_id);
    }

public function close_db(){
        return mysqli_close($this->db_connect_id);
    }

public function more_result() {
  return mysqli_more_results($this->db_connect_id);
 }
public function next_result() {
  return mysqli_next_result($this->db_connect_id);
 }

  public function __construct(){
        $this->connect();
    }

}
?>

A: mysqli_fetch_raw($results)

and
mysqli_fetch_array($results)

will give you information about only one raw. and use,
$datos = mysqli_fetch_all($query2)

you can get all output results by adding for loop.
for example.
if you want get all outputs,
    <select id="disabledSelect" name="titulo"  style="WIDTH: 228px; HEIGHT: 40px"  class="form-control">
<?php
    for ($i=0 ; $i<=(count($result)-1);$i++){
if ($i==0){$selected="select";} else {$selected=""}
    echo '<option value="'. $result[$i][0].'" '.$selected.'>'.$result[$i][2].'</option>';
    }
?php
</select>

sorry for my bad English too..


text:
Q: Can the energy/power required to mix two fluids together be calculated? Given two fluids; say for example oxygen and nitrogen gases.
By simply introducing, again for example 1 liter of each gas into a closed container, the process of diffusion alone will eventually cause the gases to reach a homogeneous mixture throughout the container. And I believe the time it takes to accomplish heterogeneity (to some specified percentage) can be estimated using a diffusion model, knowing the gas temperatures,fluid, and container properties (as a partial differential equation)
But what if mechanical work is involved? Say for example a paddle wheel is introduced into the container that can be rotated. Is there a way to calculate how long it would take to reach homogeneity in this case?
I suspect I might need to know the speed of the wheel and its surface area/geometry. But can it more easily simplified in terms of work input? So then a function that provides mix percentage as a function of time, work input, temperature and initial conditions.
Or is this type of problem just so complex that it requires empirical reduction?

A: To give you the idea of the complexity of this problem, consider that the dynamics of a single fluid is governed by the Navier-Stokes equation, which is already impractical to solve.
$$\frac {\partial}{\partial t} (\rho  u) + \nabla \cdot (\rho u \otimes u + p I)  =  \nabla \cdot \boldsymbol \tau + \rho g$$
Then this equation is coupled to probably three diffusion equations, one for the temperature, and one for the diffusion of each gas.
$$\frac{\partial\phi(\mathbf{r},t)}{\partial t} = \nabla \cdot \big[ D(\phi,\mathbf{r}) \ \nabla\phi(\mathbf{r},t) \big]$$
And don't forget you need to solve these equations on varying boundary conditions, as a result of the paddle wheel. This is the kind of problem that gets researched in computational fluid dynamics labs, or maybe companies that need to understand in detail the dynamics of certain chemical reactions.


text:
Q: Создать папку в папке Music Подскажите пожалуйста как создать папку в стандартной папке Music в памяти телефона? Мой код создает папку testdir в папке Music не в корне а в папке Android/data/app/files/Music/testdir.
File direct = new File(getContext().getExternalFilesDir(Environment.DIRECTORY_MUSIC) + File.separator + "testdir");


text:
Q: Copy matches of recursive search to a new location I want to search a directory recursively and copy all XML files to a new location.  I can identify the files with:
ls -R | grep .xml$

or with full paths with:
find . -name \*.xml

Results of normal ls calls can be passed to cp like so:
cp `ls` ./newdir

But I can't seem to get this approach working with recursive searches – cp misreads the resulting grep string and creates lots of empty files.  The closest looking SU question – using locate – fails to move any files.

Edit:
Alternative method:
find . -name \*.xml > xml_list.txt
while read p; do   cp $p ./newdir; done <xml_list.txt

.. results in a list of errors (longer than number of lines) in format:
cp: pathfilenamesegment: No such file or directory

.. where pathfilenamesegment are segments of file/path strings that happen to be separated by spaces.  Bash is apparently not applying the strings as wholes but in segments.  The iterator is however working properly as substituting echo 1 prints the same number of times as rows in xml_list.txt.
Any way to force bash to recognise lines as whole strings?

A: Use find:
find . -name "*.xml" -exec cp -vt /newdir {} +

This searches for all files ending with .xml. Then find executes cp -vt /newdir on them. With the + character find runs the cp command as few invocations as possible, stringing together as many arguments as the shell allows.
Edit: if your cp hasn't the -t option, use this:
find . -name "*.xml" -exec cp -v {} /newdir/ \;


text:
Q: jspdf autotable make header as first column instead of top row I'm making use of JSDF autotable but when i generate the PDf file then header is coming as top row but I want the header as the first column instead of top row, Please help
My code below:
const { jsPDF } = require("jspdf");
require('jspdf-autotable');
var result = [
    {
        name: "Gautam Sharma",
        age: 32,
        country: "India",
    },
    {
        name: "John Williamson Latham",
        age: 31,
        country: "New Zealand",
    },
    {
        name: "Adam Nicholls",
        age: 31,
        country: "South Africa",
    },
];
let info = []
result.forEach((element, index, array) => {
    info.push([element.name, element.age, element.country])
});

var doc = new jsPDF();
doc.autoTable({
    head: [["Name", "Age", "Country"]],
    body: info
});
doc.save("table.pdf");

Output pdf file as below:

Expected PDF file I want header in first column:
Please help


text:
Q: Conservative extension of a theory Given a theory $$ T= \{¬p ∨ ¬q\}\ over \ P = \{p, q\} $$
and theory $$ T' =\{p→r∧q, (q→r)→¬q\}\  over \  P' = \{p,q,r\} $$
I want to find if:
a) Is T' an extension of T?
b) Is T' conservative extension of T?
My attempt was the following:
a) T' is an extension of T since $ M(T')=\{\{0,0,1\},\{0,1,1\}\} $ and $ M(T)=\{\{0,1\},\{1,0\},\{0,0\}\} $, by definition T' is an extension of T iff all models of T' are models of T meaning $ M(T') ⊆ M(T) $ and also $ P ⊆ P' $. Since both of those hold we can say T' is an extension of T.
b) By definition T' is a conservative extension of T if $M(T)$ can be expanded to $M(T')$. So let's expand T by adding formulae $ φ = p → q ∧ p $ and let's call such theory $T*$ so $ T* = \{¬p ∨ ¬q, p → q ∧ p\} $ then we get that $M(T*)=M(T)$ and thus T' is conservative extension of T.
Is my reasoning correct? And if so can I add something else here? I have to say I am not sure about any of my answers since for some reason extensions seem to confuse me.
Any help and useful tricks(if there is any) to quickly identify if T' is extension of T or not as well as simply find an extension of theory T will be appreciated.


text:
Q: how to make double summary statistics thread safe? DoubleSummaryStatistics summaryStats = mTransactionSet.stream()
                    .mapToDouble(this::getPrice).summaryStatistics();
I have above code but javadoc says that DoubleSummaryStatistics is not thread safe.
So how do i ensure that multiple threads when act on mTransactionSet will work properly ?
Any pointers would be much appreciated . Thank you

A: DoubleSummaryStatistics is intended to be used in streams, in particular in code of form:
DoubleSummaryStatistics stats = stream.collect(Collectors.summarizingDouble());

or, when you have a DoubleStream:
DoubleSummaryStatistics stats = stream.summaryStatisitics();

This works for both sequential and parallel streams. The parallel streams will not use a single DoubleSummaryStatistics object to collect the data, it will use a different instance in each thread and later combine the data with DoubleSummaryStatistics::combine.
If you want to use DoubleSummaryStatistics in a stream, you don't have to think about all this stuff. Java does it for you. If you want to use it yourself in a multithreaded environment, use the same approach as parallel streams: each thread should use its own DoubleSummaryStatistics object, and in the end, all data are combined.
Or you synchronize all access to the object of course, but that will probably will be very slow.


text:
Q: Set theory: Function proof question Let $f:C \to A$ and $g:B \to A$ be functions and assume that $g$ is bijective. Prove the following.
(a) There exists a function $h: C \to B$ such that $f=g \circ h$ if and only if $ran(f) \subset ran(g)$.
(b) Show that such an $h$ is unique.
For (a) I have proved the left to right side.
let $a \in A$ such that $f(c)=a$
$f(c)=(g \circ h)(c)$
since $h$ is a function, there exists some $b$ such that $h(c)=b$
$(g \circ h)(c)=g(b)=a$.
Thus $a \in ran(g)$
I have no clue on how to prove the reverse way and (b). Could you help me with this?

A: For converse of (a), let $c\in C$ then $f(c)\in A=g(B)$ so there exists a unique $b\in B$ such that $g(b)=f(c)$. Define $h:C\rightarrow B$ as $h(c)=b$. This is a well defined map because of the uniqueness of $b$. Then $g(h(c))=g(b)=f(c)$ so $gh=f$. To show uniqueness, let there be another $j:C\rightarrow B$ such that $gj=f$. Then $gj=gh\Rightarrow j=h$ because $g$ is bijective.