text:
Q: React Native Background Geolocation - iOS I am trying to build an app that tracks a user's location while they are driving their car. I am able to get the user's location while it is the main app running (in the foreground) by using react-native-geolocation, but am trying to figure out how to use it in the background so that they don't need to be using the app to track them (sort of like a running app or even other Map apps.
I am using the library @mauron85/react-native-background-geolocation. I set up the permissions properly (I believe), but am experiencing a weird error. For the sake of being short, I won't paste the entire file that I am using, but I am essentially using the code used in this example: https://gist.github.com/jonasgroendahl/c4fad8fa48f955b993d928e1c36d76f7
The issue comes when I call BackgroundGeolocation.start() inside the BackgroundGeolocaiton.checkStatus() call. The event listeners 'foreground', 'background', and 'stop' all work. The check status produces the following values: status.isRunning -> false, status.locationServicesEnabled -> true, status.authorization -> 99.
When I call start(), the app immediately exits and crashes. No errors are thrown, so it is tough to pinpoint what the issue is. When I reopen the app, it crashes as soon as I reach the page that the start() method is called in. The 'foreground' and 'background' events trigger properly (when it is in each respective state).
Things I have tried:

*

*Setup Info.plist properties

*Enabled Background Modes: Location Updates in Xcode.

Potential issues that I am trying to maneuver:

*

*Using React Native Geolocation library in another part of the app to grab location once. If I can figure this library out, I can replace other library (react-native-geolocation) with react-native-background-geolocation to do everything.

A: Turns out that you can't do background tasks with an iOS simulator. Calling start() crashed the iOS simulator because it uses a background task API in order to tell the phone to continue running it if it goes into the background. Calling this background task caused the app to crash, from my understanding of this.


text:
Q: how I Backing Up SQL Server database? I am new to SQL Server Admin and am hoping to get some help? I have a database that only contains views of data from another database. It has no tables at all.
Is there a way to backup the data in the views?
Thanks in advance.

A: Once you have taken steps to backup the other database that contains the real data, you could also backup the views from your views only database, by scripting them out using SQL Server Management Studio
From SQL Server Management Studio
Via Object Explorer

*

*Expand the database you wish to backup views for

*Right click on the database and select Tasks -> Generate Scripts

*Choose "Select specific database objects"

*Check views or just the views you want to backup

*Select Next

*Choose Save to new query window

*Choose next and then next again

*Click on finish and the view or views you selected will be scripted to a new window

redpajama_set_name: RedPajamaStackExchange


text:
Q: Difference between static and local variable inside a function scope I am trying to find the number of digits in the input integer.
But it always prints "no. of digits: 1".
In place of getting integer i from function, if I use "static int i = 0;" inside the function it works perfectly.
And I can't understand this behavior.
#include <stdio.h>

int func(int a, int i)
{
    if (a != 0)
    {
        i++;
        func(a / 10, i);
    }

    return i;
}

int main()
{
    int a, c;
    printf("Enter the No:");
    scanf("%d", &a);
    c = func(a, 0);
    printf("No. of digits: %d", c);
    return 0;
}

A: Your recursion repeatedly refreshes the memory for your function at every call.
ts the same, it is like the same question between global variable and local variable. When you do not use static, every call to your function will refresh your variable i and initialize it again. When you use static, the variable i will be the same as a global variable with just once statement.

A: Regarding your question about static:
It is unclear where you want to use static int i = 0;  as alternative.
Inside the function, (and removing the function arg i) it becomes a variable that is kept in memory even after the function exits. See this question for reference. If it is outside of a function look at this question for reference.
Regarding your code:
Your code is not using the result of your recursive function call. It is neither stored inside the local variable i, nor returned directly. It is simply lost. See a code example below, that might be want you want.
EDIT: The variable i in the original answer was unnecessary, so I'll remove it.
#include <stdio.h>

int func(int a) {
    if (a == 0) {
        return 0;
    }
    return 1 + func(a / 10);
}

int main() {
    int a, c;
    printf("Enter the No:");
    scanf("%d", &a);
    c = func(a, 0);
    printf("%d", c);
    return 0;
}


text:
Q: Functor class using member variable struct test
{
  bool operator()(const test &lhs, const test &rhs)
  {
    if(flag)
    {
      // do stuff
    }
  }

  bool flag;
};

std::priority_queue<test, std::vector<test>, test> pq;

In this functor class here (constructed for the purpose of being a custom comparator for the prior, it uses a flag variable, but it's not clear to me which object's flag variable it is using. Is the behavior undefined here?

A: Yes, it is undefined. This line of code:
std::priority_queue<test, std::vector<test>, test> pq;

Is equivalent to
std::priority_queue<test, std::vector<test>, test> pq{test()};

You can instead pass your own instance of test:
std::priority_queue<test, std::vector<test>, test> pq{test{false}};

A: flag is undefined in your case. Moreover, the declaration of bool flag in the struct is having no effect as it is out of scope.


text:
Q: C# Xml Parse SelectNodes I have the next xml code:
<Start>
       <MetricValue>
                    <Name>Name1</Name>
                    <Value>1</Value>
       </MetricValue>
       <MetricValue>
                    <Name>Name1</Name>
                    <Value>1</Value>
       </MetricValue>
       <Test>
             <MetricValue>
                          <Name>Name1</Name>
                          <Value>1</Value>
             </MetricValue>
             <MetricValue>
                          <Name>Name1</Name>
                          <Value>1</Value>
             </MetricValue>
       </Test>
</Start>

I am trying to parse only the first 2 metric values and not that from between 'Test' tags.
XmlNodeList nlMetricValues = xmlDoc.SelectNodes("//Start//MetricValue");
foreach (XmlNode nMetricValue in nlMetricValues)
{
        Console.WriteLine("\Name: " + nMetricValue.SelectSingleNode(".//Name").InnerText);
        Console.WriteLine("\tValue: " + nMetricValue.SelectSingleNode(".//Value")).InnerText);
}

But this foreach is parsing all metric values. What should i do to solve this problem?

A: Your XPath should be "./Start/MetricValue" as "//" means it will search the node tree for any match below the previous node.
Link to syntax cheatsheet: W3Schools - XPath Syntax

A: You can use the method Elements() of XElement class. It will load only the MetricValue elements that are the children of Start element:
var xml = @"
<Start>
    <MetricValue>
        <Name>Name1</Name>
        <Value>1</Value>
    </MetricValue>
    <MetricValue>
        <Name>Name1</Name>
        <Value>1</Value>
    </MetricValue>
    <Test>
        <MetricValue>
            <Name>Name1</Name>
            <Value>1</Value>
        </MetricValue>
        <MetricValue>
            <Name>Name1</Name>
            <Value>1</Value>
        </MetricValue>
    </Test>
</Start>";

var metricValues = XElement.Parse(xml).Elements("MetricValue");


text:
Q: Changes to Pixel Shader aren't being Saved I'm working on a DirectX program (I'm not using any wrappers). I'm trying to make a Pixel Shader. I made some changes to the Pixel Shader, it is not reflecting in the code when it is running.
This is the code I wrote for the Pixel Shader. (It is just returning the colour to white).
float4 main(PS_INPUT input) : SV_Target
{
    //float4 baseTexture = txDiffuse.Sample(samLinear, input.Tex);

    return float4(1.0f, 1.0f, 1.0f, 1);
}

Before I changed my code to this, my pixel shader was returning the colour from the vertex.
When I'm running my graphics debugger I see this pixel shader running. (The old code)
The graphics debugger running
I'm making my HLSL into a .csh.
Also, I'm making my PIxel Shader like this
hr = m_Device->CreatePixelShader(PS_Mesh, sizeof(PS_Mesh), nullptr, &m_PixelShader[PIXEL_SHADER_TYPE::ENUM::PS_MESH].p);

Why are the changes not reflecting? I have tried to give all the information. Please ask any other questions you need to. I have been stuck on this problem for quite some time.
Build settings for the project..


text:
Q: Disble facebook login button while logging in I want to disable facebook login button while logging in with facebook. Is there any ways to do that ?
Here is my code
<script>
$(document).ready(function(){
window.fbAsyncInit = function(){

                FB.init({appId: 'MY_APP_ID', status: true, cookie: true, xfbml: true});

                FB.Event.subscribe('auth.authResponseChange', function(response) {

                    if (response.status === 'connected'){
                        FB.api('/me', processFBToken);
                    }
                    else if(response.status === 'not_authorized'){
                        FP.login();
                    }
                    else{
                        FB.login();
                    }
                });
            };

            $.ajaxSetup({ cache: true });
            $.getScript(document.location.protocol + '//connect.facebook.net/en_US/all.js');

            //process the callback response
            function processFBToken(response){
                if(response && response.authResponse && response.authResponse.accessToken){

                    var token = response.authResponse.accessToken;
                    $.post('/user/login', {facebookToken : token}, function(data){

                    })
                }
            }
        })
    </script>

And in my html
    <fb:login-button size="large">
              Login with Facebook
    </fb:login-button>

I also have another button for normal login.
<button type = 'submit' class = 'btn btn-primary' id = 'login-submit-btn'>Login</button>

How can I disable that button also when i click 'login with facebook' button. Really appreciate for your help


text:
Q: I have a view pager and I try to nest a fragment for a map within the main fragment. Why do I keep getting " Error inflating class fragment"? I have been working on this particular problem since the beginning of the week. I have read blogs and suggested answers on stack overflow. I have tried different solutions and even used some of the accepted answers from here but my app still keeps crashing. I also tried the mapview and it did not work. I need some help solving this. I have implemented a map before and I did not have any problems but that was in an activity. I am facing issues with implementing in the fragment and the app always crashes at view = inflater.inflate(R.layout.fragment_serv__base_data, container, false);
 init();
Below is my manifest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.application.sweetiean.stlmaintenance" >

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTENAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!--
     The following two permissions are not required to use
     Google Maps Android API v2, but are recommended.
-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.application.sweetiean.permission.MAPS_RECEIVE" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />
<meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="AIzaSyA5ULk7TurdcL5PqVOjJ1ZDf9wiZJIwgZc" />

<permission
    android:name="com.application.sweetiean.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/supertechlogo"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".SplashActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar" >
    </activity>
    <activity
        android:name=".MaintenanceActivity"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.application.sweetiean.stlmaintenance.MainActivity" />
    </activity>
    <activity
        android:name="com.application.sweetiean.stlservicing.ServicingActivity"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.application.sweetiean.stlmaintenance.MainActivity" />
    </activity>
    <activity android:name=".DisplayOverviewActivity" >
    </activity>
    <activity
        android:name="com.application.sweetiean.stlservicing.STLSignatureActivity"
        android:label="STL Signature">
    </activity>
    <activity android:name="com.application.sweetiean.stlservicing.ClientSignatureActivity"
        android:label="Client Signature">
    </activity>
</application>

Here is the xml:
...
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="500dp"
        android:orientation="vertical"
        android:layout_marginBottom="10dp">

        <fragment
            android:id="@+id/map"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            class="com.google.android.gms.maps.SupportMapFragment" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginBottom="10dp">

        <Button
            android:id="@+id/getLocationButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/getlocation"
            android:background="@drawable/blue_button"
            style="@style/button_text_small"/>

        <TextView
            android:id="@+id/locationTextView"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textSize="12sp"/>

    </LinearLayout>
...

Below is the fragment.java:
public class Serv_BaseDataFragment extends Fragment {

View view;
EditText sysaid, customer, siteId, address;
TextView locationCoordinates;
Spinner taskSpinner, regionSpinner;
Button sign_STL, sign_client, location;
GoogleMap googleMap;

public Serv_BaseDataFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    view = inflater.inflate(R.layout.fragment_serv__base_data, container, false);
    init();
    return view;

}

public void init(){

    googleMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

    sysaid = (EditText)view.findViewById(R.id.sysaidIdEditText);
    customer = (EditText)view.findViewById(R.id.customerEditText);
    siteId = (EditText)view.findViewById(R.id.siteIdEditText);
    address = (EditText)view.findViewById(R.id.addressEditText);
    locationCoordinates = (TextView)view.findViewById(R.id.locationTextView);

    taskSpinner = (Spinner)view.findViewById(R.id.taskTypeSpinner);
    ArrayAdapter<CharSequence> taskAdapter = ArrayAdapter.createFromResource(this.getActivity(), R.array.taskTypeArray, android.R.layout.simple_spinner_item);
    taskAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    taskSpinner.setAdapter(taskAdapter);

    regionSpinner = (Spinner)view.findViewById(R.id.regionSpinner);
    ArrayAdapter<CharSequence> regionAdapter = ArrayAdapter.createFromResource(this.getActivity(), R.array.regionArray, android.R.layout.simple_spinner_item);
    regionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    regionSpinner.setAdapter(regionAdapter);

    sign_client = (Button)view.findViewById(R.id.clientSignatureButton);
    sign_client.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), ClientSignatureActivity.class);
            startActivityForResult(intent, 1);
        }
    });

    sign_STL = (Button)view.findViewById(R.id.STLSignatureButton);
    sign_STL.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), STLSignatureActivity.class);
            startActivityForResult(intent, 1);
        }
    });

    location = (Button)view.findViewById(R.id.getLocationButton);
    location.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

}

}
and finally the error log:
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime: FATAL EXCEPTION: main
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime: Process: com.application.sweetiean.stlmaintenance, PID: 5398
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime: android.view.InflateException: Binary XML file line #157: Error inflating class fragment
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:719)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.LayoutInflater.rInflate(LayoutInflater.java:769)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at com.application.sweetiean.stlservicing.Serv_BaseDataFragment.onCreateView(Serv_BaseDataFragment.java:50)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1965)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1078)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1259)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1624)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.support.v4.view.ViewPager.populate(ViewPager.java:1106)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.support.v4.view.ViewPager.populate(ViewPager.java:952)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1474)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.View.measure(View.java:17327)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5363)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:610)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:677)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.View.measure(View.java:17327)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5363)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.View.measure(View.java:17327)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5363)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1410)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.View.measure(View.java:17327)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5363)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.View.measure(View.java:17327)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5363)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1410)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.View.measure(View.java:17327)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5363)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2548)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.View.measure(View.java:17327)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2277)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1391)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1590)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1249)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6529)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:812)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.Choreographer.doCallbacks(Choreographer.java:612)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.Choreographer.doFrame(Choreographer.java:582)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:798)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:733)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:95)
11-13 12:04:26.099 5398-5398/com.application.sweetiean.stlmaintenance E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:146)

A: Make sure the <meta-data android:name="com.google.android.maps.v2.API_KEY"
    android:value="AIzaSyA5ULk7TurdcL5PqVOjJ1ZDf9wiZJIwgZc" /> is inside of the <application> element. If you decide to use a mapview you can follow  Boss's answer at this link. Also there are other great suggestions in the comments under the question.
Let me add that when I was testing the mapview example mContext = getActivity();did not work for me so I commented it out. Moreover there was no use of mContextin the code block.


text:
Q: How to update the django model when it does not detect changes? I encounter an error on my Django application, I cannot update my models thanks to makemigrations
It returns "No changes detected"
My database is in postgresql
My app is well saved in my settings.py file and I have the migrations folder inside the app, I don't see where the problem can come from.
Do you have any idea what it could be?
Models.py
from django.db import models

class Gestflotte (models.Model):
    id = models.IntegerField(primary_key=True),
    name = models.CharField(max_length=100),
    nb_engins = models.IntegerField(max_length=50),
    type_fichier = models.CharField(max_length=255),
    calculateur = models.CharField(max_length=255),

Update
The problem was the ',' at the end of the fields
Thank you all

A: You need to use makemigrations only when modifying your models fields/attributes, if you just change the methods of your models.py class (like overriding models methods or creating new ones) you don't need to use makemigrations.
And if you don't have your changes updated in your database, did you think of using migrate after making your migrations ?


text:
Q: How to check a column's type of a dataframe using iloc? How can I write a for loop to check types of columns in a dataframe one by one?
For example, for below df:

Any help would be great!

A: Edit based on comment
A simpler version based on @NewbieAF's comment: df.dtypes

This should do it
{c: df[c].dtype for c in df.columns}
Example:
import pandas as pd
data = [{'age': 20, 'name': 'james', 'gpa': 18.5},
        {'age': 21, 'name': 'anna', 'gpa': 19.6},
        {'age': 18, 'name': 'sam', 'gpa': 17.0}]

df = pd.DataFrame(data)
print({c: df[c].dtype for c in df.columns})

Result:
{'age': dtype('int64'), 'name': dtype('O'), 'gpa': dtype('float64')}


text:
Q: Silverlight GetElementById IE6 I have an odd error that you guys will hopefully be able to help me out with.
I have this code in my silverlight app:
private void MainGrid_SizeChanged(object sender, SizeChangedEventArgs e)
{
double actualHeight = this.MainGrid.ActualHeight;
HtmlPage.Document.GetElementById("silverlightControlHost").SetStyleAttribute("height", string.Format("{0}px", actualHeight));
}

This basically resizes my container div so that it fits in the browser. This is working fine in IE7+, Firefox and Chrome. The problem is that in IE6 this is not working. And im not sure why.
Page markup:

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

        <object data="data:application/x-silverlight-2," type="application/x-silverlight-2"
            width="100%" height="100%">
            <param name="enablehtmlaccess" value="true"/>
            <param name="source" value="../ClientBin/myAppXap.xap" />
            <param name="onError" value="onSilverlightError" />
            <param name="background" value="white" />
            <param name="minRuntimeVersion" value="3.0.40624.0" />
            <param name="autoUpgrade" value="true" />

        </object>

</asp:Content>

Does anyone have any ideas how i can get this working as desired?
Thanks,
Simon

A: You have to resize your object tag as well, i just had the same problem, i had signed the onsizechanged event and changed the height and width of the container div, however in IE6 that didn't worked, so a co-worker told me that in IE6 you need to resize the object as well, so place an ID on your  tag and use it on this
HtmlPage.Document.GetElementById("objectID").SetStyleAttribute("height", string.Format("{0}px", actualHeight));


text:
Q: Send #hash from href to div in the same page I'm working on football website and i have an idea but i don't know if it possible.
I show all players of teams in a page and i wanna create a
 that will show all statistics about a specific player clicking on the name.
If i click on the name i wanna show a
 with information about that player in the same page (i will use z-index). This problem will be solved, but i wanna send id-player from href using hash to extract stats from db.
Clicking on player 201 can
 read #201 and process it to search in the db?
(The idea is like infobox in Fantasy Premier League website. Someone know it??)
Thank you,
N

A: You can include a div as
player 201
...

Player1 details

But this work on same page. If you are going to use in different pages
player 201
test.html

Player1 details


text:
Q: how to add Page curl effect for pdf/images/layout in Android? checked the entire https://android-arsenal.com website but no proper library support available that works right now.
if anyone has anything related to that I can follow and achieve this effect?
page curl effect example : https://www.youtube.com/watch?v=Yg04wfnDpiQ
tried previous solutions give in the site but those are too old and not working:
Implement page curl on android?
How to do page flip/turn/curl effect in android


text:
Q: Moving the image in canvas in user defined path I need to move the image in the canvas. The image should not follow a linear or circle or elliptical path. I know this can be achieved by using the COS and SIN functions. But here I need to get the image traversed in a 4 different path like I have shown in the below snapshot. Please help me if there is anyway to achieve this. It should be fine even If I get any idea to achieve this .
snapshot:

A: I'd try the android animation package first - you should be able to define a few points and get this to smooth the path between the points.
See here: http://developer.android.com/guide/topics/graphics/view-animation.html


text:
Q: reading and writing from hive tables with spark after aggregation We have a hive warehouse, and wanted to use spark for various tasks (mainly classification). At times write the results back as a hive table. For example, we wrote the following python function to find the total sum of original_table column two, grouped by original_table column one. The function works, but we are worried that it is inefficient, particularly the maps to convert to key-value pairs, and dictionary versions. Functions combiner, mergeValue, mergeCombiner are defined elsewhere, but work fine.
from pyspark import HiveContext

rdd = HiveContext(sc).sql('from original_table select *')

#convert to key-value pairs
key_value_rdd = rdd.map(lambda x: (x[0], int(x[1])))

#create rdd where rows are (key, (sum, count)
combined = key_value_rdd.combineByKey(combiner, mergeValue, mergeCombiner)

# creates rdd with dictionary values in order to create schemardd
dict_rdd = combined.map(lambda x: {'k1': x[0], 'v1': x[1][0], 'v2': x[1][1]})

# infer the schema
schema_rdd = HiveContext(sc).inferSchema(dict_rdd)

# save
schema_rdd.saveAsTable('new_table_name')

Are there more efficient ways of doing the same thing?

A: ...perhaps this was not possible when the question was written, but doesn't it make sense now (post 1.3) to use the createDataFrame() call?
After getting your first RDD, it looks like you could make the call, then run a simple SQL statement against the structure to get the whole job done in one pass. (Sum and Grouping) Plus, the DataFrame structure can infer schema directly upon creation if I'm reading the API doc correctly.
(http://spark.apache.org/docs/1.3.1/api/python/pyspark.sql.html#pyspark.sql.HiveContext)

A: This error can solved by setting hive.exec.scratchdir to the folder where user has access

A: What version of spark you are using ?
This answer is based on 1.6 & using the data frames.
val sc = new SparkContext(conf)
val sqlContext = new org.apache.spark.sql.SQLContext(sc)

import sqlContext.implicits._
val client = Seq((1, "A", 10), (2, "A", 5), (3, "B", 56)).toDF("ID", "Categ", "Amnt")

    import org.apache.spark.sql.functions._
    client.groupBy("Categ").agg(sum("Amnt").as("Sum"), count("ID").as("count")).show()

+-----+---+-----+
|Categ|Sum|count|
+-----+---+-----+
|    A| 15|    2|
|    B| 56|    1|
+-----+---+-----+

Hope this helps !!


text:
Q: radare2 load register map I'm reversing some stm32f030 code I downloaded from the chip. I do understand the stm32s and arm assembly but I'm completely new to radare2.
There are many special registers e.g. 0x40021000 is RCC_CR, 0x40021004 is RCC_CFGR, 0x48000000 is GPIOA_MODER an so on. s. https://www.st.com/resource/en/reference_manual/dm00091010-stm32f030x4x6x8xc-and-stm32f070x6xb-advanced-armbased-32bit-mcus-stmicroelectronics.pdf
Is there a way to import register definitions in some format so that the code analysis can automatically flag them? Or another way so that all referenzes to them are named?

A: From the Radare manual on symbols, you can read a dwarf file.  So, you can make a dwarf with external definitions for the register at the absolute addresses and it may be able to use them in the disassembler of a second binary.
With bin-utils, you can merge a binary with the symbols.  Radare looks to have lots of utilities which can probably do the same thing; if it is not able to merge symbols from a separate DWARF file.. and this step is entirely un-needed.


text:
Q: How to execute some code before Hibernate Bootstrap in Wildfly in a web application? In a web application that

*

*deployed as a single war file

*runs on the Wildfly 20

*uses Hibernate as its persistence layer(Wildfly builtin mosule)

*

I have some code that must be executed before than Hibernate Bootstrap.
what is best practice for doing this task??


text:
Q: SQL Query to count the number of each element in an object I have a database table like this:
Room Name     ||     Animal
----------------------------
Room1 || Cat
Room1 || Dog
Room1 || Dog
Room2 || Cat
Room2 || Cat
Room2 || Dog
Room2 || Dog

I want to read this table with a SQL query and as result I want to count the number of each animal in the room:
Room1: 1 cat 2 dog
Room2: 2 cats 2 dog

(The output format doesn't matter)
Is there a SQL query that can help? Or should I read the whole table and filter it programatically?
Thank you for any help

A: SELECT [Room Name], [Animal], COUNT(*) FROM TableName GROUP BY [Room Name], [Animal]

This would return
Room 1 | Cat | 1
Room 1 | Dog | 2
Room 2 | Cat | 2
Room 2 | Dog | 2

A: select room_name, animal, count(*)
from table
group by room_name, animal


text:
Q: OLEDB Cannot load data from excel after publishing I am using OLEDb to load table from a local .xls file in C# .Net. The table is loaded and showed correctly when I view the webpage "View in Browser". But when I publish, the table is not shown on the webpage (URL that I publish to) but other parts of the webpage are shown correctly.
Is there a reason why the excel file can be loaded when debugging but cannot load when published?
Here is the code in C# that load the Excel:
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=//Dfs.local/I/Test Copy.xls;Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
OleDbConnection OleConn = new OleDbConnection(strConn);
OleConn.Open();
String sql1 = "SELECT * FROM  [Sheet1$]";
OleDbDataAdapter OleDaExcel1 = new OleDbDataAdapter(sql1, OleConn);

My first idea was that the excel spreadsheet could not be access by webpage. But I have another link on the webpage that would open this excel when clicked. And it's working on the webpage after publishing.
Here is the code for the link:
<script language="JavaScript" type="text/javascript">
 Out = '<a href="file://Dfs.local/I/Test Copy.xls">Report<\/a>';
 document.writeln(Out);
</script>

I tried many different ways of publishing but could still not load the excel table when opening from URL.
Please help! Thank you!

A: *

*Local file links only work in Internet Explorer and not Chrome or Firefox.

*When published, the web server runs under a different UserID than the person looking at the web page. Ensure THAT process has proper access/permissions to the excel output file and directory/share. (Typically this account is called W3SVC.)


text:
Q: How can I get postgres JDBC working in Scala Mac OS? I'm trying to do a tutorial to connect to Postgres from scala, using the JDBC drivers
https://mackler.org/LearningSlick2/
However, i'm getting this error message:
[info] Starting scala interpreter...
[info]
Welcome to Scala version 2.10.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_65).
Type in expressions to have them evaluated.
Type :help for more information.

scala>  import org.postgres
<console>:7: error: object postgres is not a member of package org
        import org.postgres

I'm using MacOSX with postgress installed via http://postgresapp.com/
What am I missing to properly use the jdbc connection?

A: It looks like your postgres jars are not on your class path. Try:
$ scala -classpath postgres.jar

Where postgres.jar is hypothetical example.
You may need to add all jars using something like pathToPostGresLib/*.jar while starting your REPL session.


text:
Q: Typescript nested generics How do I nest the same type that uses generics?
interface programConfig<T extends Record<string, any>> {
  // other types removed; not relevant to the question
  commands?: { [key: string]: programConfig<???> }; // how do I type this?
}

More complete ts playground example that shows what I'm trying to accomplish

A: You can specify a second generic to encompass the sub elements of the programConfig, in this example I constrained the inner ones to not allow a 3rd level of nesting since supporting arbitrary nesting would be annoying and hopefully not necessary
playground

interface BaseProgramConfig<T extends Record<string, unknown> >{
  options?: {
    [K in keyof T]: {
      validator?: () => T[K]
    }
  },
  handler?: (data: T) => void
}
interface programConfigWithCommands<T extends Record<string, unknown>, Sub extends Record<string, Record<string, unknown>>> extends BaseProgramConfig<T> {
  commands?: {[K in keyof Sub]: BaseProgramConfig<Sub[K]>}
}

class Program<T extends Record<string, unknown>, Comms extends Record<string, Record<string, unknown>>> {
  constructor(config: programConfigWithCommands<T,Comms>) { }
}

const foo = new Program({
  options: {
    'fruit': { validator: () => 'asdf' },
    'animal': { validator: Number },
  },
  handler: ({ fruit, animal, thing }) => { // fruit and animal are properly typed based on options above
    console.log(fruit, animal)
  },
  commands: {
    foo: {
      options: {
        'tree': { validator: () => 'asdf' },
        'person': {},
      },
      handler: ({ tree, person, thing }) => { // tree is typed as string, person is typed as unknown
        console.log(tree, person)
      },
    }
  }
});

A: You just need to call new Program again, like here:
type programConfig<T extends Record<string, any> = Record<string, any>> = {
  options?: {
    [K in keyof T]: {
      validator?: () => T[K]
    }
  },
  handler?: (data: T) => void,
  commands?: { [key: string]: Program<Record<string,unknown>> }; // here use sub-programs that have nothing to do with T
}

class Program<T extends Record<string, any> = Record<string, any>> {
  constructor(config: programConfig<T>) { }
}

const foo = new Program({
  options: {
    'fruit': { validator: () => 'asdf' },
    'animal': { validator: Number },
  },
  handler: ({ fruit, animal, thing }) => { // fruit and animal are properly typed based on options above
    console.log(fruit, animal)
  },
  commands: {
    foo: new Program({
      options: {
        'tree': { validator: () => 'asdf' },
        'person': {},
      },
      handler: ({ tree, person, thing }) => { // tree and person are typed in the same way and Program of any type is accepted in commands
        console.log(tree, person)
      },
    })
  }
});

Playground


text:
Q: How to store user input as a keyword argument in python I have a program of this sort:
func1(**kwargs):

  for name, value in kwargs.items():

      print ("{} = {}".format(name, value))

I want the user to input the arguments.
Something like this:
d={}
x = input("enter key and value separated by a space ")
y = x.split(' ')
d[y[0]] = y[1]

I tried storing the input as a dictionary and then passing it as an argument, -  func1(d)  - but it recognized the dictionary as one positional argument.
Does anyone have any ideas on how to do this?


text:
Q: Weblogic 12.2.1.3 from Moxy to Jackson I would like to change the JSON parser from Moxy to Jackson, and I have followed the shared library approach, but without any result, Moxy is still used.
Note: the shared library is not necessary!!!
The shared library
I have created a maven project with the following dependencies and descriptors.
pom.xml
 <properties>
    <jackson.annotations.release>2.8.6</jackson.annotations.release>
    <jersey.version>2.22.4</jersey.version>
 </properties>

 <dependencies>
    <dependency>
        <groupId>com.fasterxml.jackson.module</groupId>
        <artifactId>jackson-module-jaxb-annotations</artifactId>
        <version>${jackson.annotations.release}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.jaxrs</groupId>
        <artifactId>jackson-jaxrs-json-provider</artifactId>
        <version>${jackson.annotations.release}</version>
    </dependency>

    <!-- Jersey dependencies -->
    <dependency>
        <groupId>org.glassfish.jersey.containers</groupId>
        <artifactId>jersey-container-servlet</artifactId>
        <version>${jersey.version}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-client</artifactId>
        <version>${jersey.version}</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-multipart</artifactId>
        <version>${jersey.version}</version>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.media</groupId>
        <artifactId>jersey-media-json-jackson</artifactId>
        <version>${jersey.version}</version>
    </dependency>
</dependency>

weblogic.xml
 <container-descriptor>
    <prefer-application-packages>
        <!-- apis -->
        <package-name>javax.ws.rs.*</package-name>

        <!-- guava -->
        <package-name>com.google.common.*</package-name>

        <!-- jersey providers -->
        <package-name>org.glassfish.jersey.*</package-name>
        <package-name>jersey.repackaged.*</package-name>

        <!-- hk2 -->
        <package-name>org.jvnet.hk2.*</package-name>
        <package-name>org.jvnet.hk2.tiger_types.*</package-name>
        <package-name>org.glassfish.hk2.*</package-name>
        <package-name>javassist.*</package-name>

        <!-- media providers -->
        <!--<package-name>org.eclipse.persistence.jaxb.rs.*</package-name>-->
        <package-name>com.fasterxml.jackson.*</package-name>

        <!-- wls -->
        <package-name>weblogic.jaxrs.api.client.*</package-name>
        <package-name>weblogic.jaxrs.internal.api.client.*</package-name>
        <package-name>weblogic.jaxrs.dispatch.*</package-name>
        <package-name>weblogic.jaxrs.monitoring.util.*</package-name>
    </prefer-application-packages>
</container-descriptor>

MANIFEST.MF
Manifest-Version: 1.0
Implementation-Title: Jackson Weblogic
Implementation-Version: 1.0
Specification-Title: Jackson Weblogic
Extension-Name: jackson-weblogic
Specification-Version: 1.0

Web Application
I add the web.xml and the weblogic.xml.
web.xml
<servlet>
    <servlet-name>com.dummy.MyApplication</servlet-name>
        <init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider</param-value>
        </init-param>
</servlet>

<servlet-mapping>
    <servlet-name>com.dummy.MyApplication</servlet-name>
    <url-pattern>/api/*</url-pattern>
</servlet-mapping>

weblogic.xml
<?xml version="1.0" encoding="UTF-8"?>
<weblogic-web-app xmlns="http://xmlns.oracle.com/weblogic/weblogic-web-app">
    <library-ref>
        <library-name>jstl</library-name>
        <specification-version>1.2</specification-version>
        <implementation-version>1.2</implementation-version>
        <exact-match>false</exact-match>
    </library-ref>
    <library-ref>
        <library-name>jackson-weblogic</library-name>
        <specification-version>1.0</specification-version>
        <exact-match>false</exact-match>
    </library-ref>
</weblogic-web-app>

Then I reference in the weblogic.xml the shared library, but Moxy is still used. Have I done something wrong?
Update: I have added the web.xml and the weblogic.xml of the web application.
Solution
I have checked the folder oracle_common\modules and I have found all the Jackson dependencies needed. So I have preferred to configure Jersey to disable the use of MOXy as follows:
import javax.ws.rs.core.Application;
public class MyApplication extends Application
{
    @Override
    public Map<String, Object> getProperties()
    {
        Map<String, Object> proprties = new HashMap<>();
        proprties.put("jersey.config.server.disableMoxyJson", true);

        return proprties;
    }
}

Pay attention:

*

*that the method getProperties() comes with javax.ws.rs 2.0;

*no specific shared library is necessary for Jackson, but just for jstl and jax-rs 2.0;

*no info inside web.xml is required;

*as reported by @abbas JAX-RS 2.0 comes by default with Weblogic 12.2.1.3.0 in my case I has a transitive dependency on javax.ws.rs:jsr311-api so the method getProperties() was not invoked.

Final weblogic.xml
<?xml version="1.0" encoding="UTF-8"?>
<weblogic-web-app xmlns="http://xmlns.oracle.com/weblogic/weblogic-web-app">

    <context-root>/web-app</context-root>
    <container-descriptor>
        <prefer-application-packages>
            <package-name>org.apache.commons.net.*</package-name>
        </prefer-application-packages>
    </container-descriptor>

    <library-ref>
        <library-name>jstl</library-name>
        <specification-version>1.2</specification-version>
        <implementation-version>1.2</implementation-version>
        <exact-match>false</exact-match>
    </library-ref>
</weblogic-web-app>

A: Mention JAX-RS 2.0 as a dependency in your pom.xml
<dependency>
    <groupId>javax.ws.rs</groupId>
    <artifactId>javax.ws.rs-api</artifactId>
    <version>2.0.1</version>
    <scope>provided</scope>
</dependency>

In WebLogic 12.2.1 you do not need to deploy it as a shared library.


text:
Q: Existences of enough integers which can be properly represented by a primitive binary quadratic form Let $F = ax^2 + bxy + cy^2$ be a binary quadratic form over $\mathbb{Z}$.
We say $D = b^2 - 4ac$ is the discriminant of $F$.
It is easy to see that $D \equiv 0$ (mod $4$) or $D \equiv 1$ (mod $4$).
If $D$ is not a square integer and gcd($a, b, c) = 1$, we say $F$ is primitive.
Let $m$ be an integer.
If $m = ax^2 + bxy + cy^2$ has a solution in $\mathbb{Z}^2$, we say $m$ is represented by $F$.
If $m = ax^2 + bxy + cy^2$ has a solution $(s, t)$ such that gcd$(s, t) = 1$,
we say $m$ is properly represented by $F$.
My question
Is the following proposition true?
If yes, how do we prove it?
Proposition
Let $D$ be a non-square integer such that $D \equiv 0$ (mod $4$) or $D \equiv 1$ (mod $4$).
Let $F = ax^2 + bxy + cy^2$ be a primitive binary quadratic form of discriminant $D$.
Let $m \neq 0$ be an integer.
There exists an integer $n$ which is properly represented by $F$ and gcd($n, m) = 1$.

A: The answer to your question is YES.
Put $Q(x,y)=ax^2+bxy+cy^2$. Let $p_1,p_2, \ldots ,p_r$ be the prime divisors of $m$. Note that
$$
Q(1,0)=a,\ Q(0,1)=c, \ Q(1,1)=a+b+c
$$
If $Q$ is primitive, those three numbers are not all divisible by $p_i$. So for each $i$, there are two integers $x_i$ and $y_i$ such that $Q(x_i,y_i) \not\equiv 0 \ ({\sf mod} \ p_i)$ (and in fact, we can take $(x_i,y_i)$ to be one of the three $(0,1),(1,0),(1,1)$).
By the Chinese remainder theorem, there is an integer $x$ such that $x\equiv x_i \ ({\sf mod} \ p_i)$ for all $i$, and an integer $y$ such that $y\equiv y_i \ ({\sf mod} \ p_i)$ for all $i$.
Then
$$
\forall i,\ Q(x,y) \equiv Q(x_i,y_i) \not\equiv 0 \ ({\sf mod} \ p_i)
$$
So $n=Q(x,y)$ is divisible by none of the $p_i$ and is therefore coprime to $m$.
Finally, to ensure that the representation is proper, replace $(x,y)$ with $(x',y')=(\frac{x}{g},\frac{y}{g})$ where $g=gcd(x,y)$. Then $Q(x',y')=\frac{Q(x,y)}{g^2}$ is  still  coprime to $m$.


text:
Q: Java split regular expression If I have a string, e.g.
setting=value

How can I remove the '=' and turn that into two separate strings containing 'setting' and 'value' respectively?
Thanks very much!

A: Two options spring to mind.
The first split()s the String on =:
String[] pieces = s.split("=", 2);
String name = pieces[0];
String value = pieces.length > 1 ? pieces[1] : null;

The second uses regexes directly to parse the String:
Pattern p = Pattern.compile("(.*?)=(.*)");
Matcher m = p.matcher(s);
if (m.matches()) {
  String name = m.group(1);
  String value = m.group(2);
}

The second gives you more power. For example you can automatically lose white space if you change the pattern to:
Pattern p = Pattern.compile("\\s*(.*?)\\s*=\\s*(.*)\\s*");

A: You don't need a regular expression for this, just do:
String str = "setting=value";
String[] split = str.split("=");
// str[0] == "setting", str[1] == "value"

You might want to set a limit if value can have an = in it too; see the javadoc


text:
Q: Ignoring invalid data from file in Java I'm trying to create a program that reads in a list of integers from a file, and adds them all together and displays to the user. I can get this program to work properly but what I want to do is have it so if there is an invalid entry in the file (say, a word or anything that isn't a number) it will alert the user and ignore the invalid data and skip to the next available number. Here is my code so far:
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;

public class IntegerReadIn {

    public static void main(String[] args) {

        int sum = 0;

        try {

            File myFile = new File("IntegerReadIn.txt");
            Scanner scan = new Scanner(myFile);

            while (scan.hasNextInt()) {
                sum = sum + scan.nextInt();
            }

            System.out.println("Total = " + sum);
            scan.close();
        } catch (FileNotFoundException e) {
            System.err.println("No such file name");
        } catch (InputMismatchException e) {
            System.err.println("Invalid entry found - integers only.");
        }
    }
}

A: First use nextLine() to read the entire line. after that Use Integer.parseInt() method to validate the integer input.
Scanner scan = new Scanner(myFile);
String s = scan.nextLine();

try{
    Integer.parseInt(s);
}
catch(NumberFormatException ex){
    System.out.println("Error....");
}

A: Perhaps instead of using your while for only hasNextInt() you should loop for haxNext()
That way you can explicitly check if you get an integer or not (and thus you can provide feedback to the user)
while (scan.hasNext()) {
   if (scan.hasNextInt()) {
       sum = sum + scan.nextInt();
   } else {
       System.out.println("Invalid Entry: " + scan.next());
   }
}

Having this in consideration you will not be needing the InputMismatchException


text:
Q: Passing 2d array from C++ to Java and back to C++ How can I pass a 2d array from C++ to Java and return back to C++ using JNI?
Sample2.java
public static int[][] intArrayMethod(int[][] n){
    for (int i = 0; i < 10; i++){
        for (int j = 0; j < 10; j++){
            n[i][j] = 2;
        }
    }
    return n;
}

CppSample.cpp
int main(){
    JavaVMOption options[1];
    JNIEnv *env;
    JavaVM *jvm;
    JavaVMInitArgs vm_args;
    long status;
    jclass cls;
    jmethodID mid;

    options[0].optionString = "-Djava.class.path=.";
    memset(&vm_args, 0, sizeof(vm_args));
    vm_args.version = JNI_VERSION_1_2;
    vm_args.nOptions = 1;
    vm_args.options = options;
    status = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);

    jint cells[10][10]; // my 2d array
    for (int i = 0; i < 10; i++){
        for (int j = 0; j < 10; j++){
            cells[i][j] = 1;
        }
    }

    if (status != JNI_ERR){
        cls = env->FindClass("Sample2");
        if (cls != 0){
            mid = env->GetStaticMethodID(cls, "intArrayMethod", "(I)I");
            if (mid != 0){
                cells = env->CallStaticIntMethod(cls, mid, cells);
                for (int i = 0; i < 10; i++){
                    for (int j = 0; j < 10; j++){
                        printf("%d", cells[i][j]);
                    }
                }
            }
        }
        jvm->DestroyJavaVM();
        return 0;
    }
    else{
        return 1;
    }
}

I'm not sure what is the correct way to pass a 2d array between c++ and java.
Hope you can guide me along, Thanks!

A: This is not so much difficult as tedious. The general problem is that arrays in Java are completely unlike arrays in C++ and (sort of) more comparable to non-resizeable vectors. It is not possible to pass a C++ array to Java directly1 because Java has no idea what to do with it. So we'll need conversion functions such as:
Converting the 2D array from C++ to Java
// The template bit here is just to pick the array dimensions from the array
// itself; you could also pass in a pointer and the dimensions.
template<std::size_t OuterDim, std::size_t InnerDim>
jobjectArray to_java(JNIEnv *env, int (&arr)[OuterDim][InnerDim]) {
  // We allocate the int array first
  jintArray    inner = env->NewIntArray   (InnerDim);
  // to have an easy way to get its class when building the outer array
  jobjectArray outer = env->NewObjectArray(OuterDim, env->GetObjectClass(inner), 0);

  // Buffer to bring the integers in a format that JNI understands (jint
  // instead of int). This step is unnecessary if jint is just a typedef for
  // int, but on OP's platform this appears to not be the case.
  std::vector<jint> buffer;

  for(std::size_t i = 0; i < OuterDim; ++i) {
    // Put the data into the buffer, converting them to jint in the process
    buffer.assign(arr[i], arr[i] + InnerDim);

    // then fill that array with data from the input
    env->SetIntArrayRegion(inner, 0, InnerDim, &buffer[0]);
    // and put it into the outer array
    env->SetObjectArrayElement(outer, i, inner);

    if(i + 1 != OuterDim) {
      // if required, allocate a new inner array for the next iteration.
      inner = env->NewIntArray(InnerDim);
    }
  }

  return outer;
}

From Java to C++
// Note that this function does not return an array but a vector of vectors
// because 2-dimensional Java arrays need not be rectangular and have
// dynamic size. It is not generally practical to map them to C++ arrays.
std::vector<std::vector<int> > from_java(JNIEnv *env, jobjectArray arr) {
  // always on the lookout for null pointers. Everything we get from Java
  // can be null.
  jsize OuterDim = arr ? env->GetArrayLength(arr) : 0;
  std::vector<std::vector<int> > result(OuterDim);

  for(jsize i = 0; i < OuterDim; ++i) {
    jintArray inner = static_cast<jintArray>(env->GetObjectArrayElement(arr, i));

    // again: null pointer check
    if(inner) {
      // Get the inner array length here. It needn't be the same for all
      // inner arrays.
      jsize InnerDim = env->GetArrayLength(inner);
      result[i].resize(InnerDim);

      jint *data = env->GetIntArrayElements(inner, 0);
      std::copy(data, data + InnerDim, result[i].begin());
      env->ReleaseIntArrayElements(inner, data, 0);
    }
  }

  return result;
}

As you can see, they're pretty straightforward; one really only has to know what JNI functions to call (or, indeed, where to find the documentation).
Calling the Java function
As for calling the Java function, you nearly have it right. Two things need changing:
mid = env->GetStaticMethodID(cls, "intArrayMethod", "(I)I");

would work if intArrayMethod were int intArrayMethod(int). As it is, you need
mid = env->GetStaticMethodID(cls, "intArrayMethod", "([[I)[[I");

In these signature strings, I stands for int, [I for int[] and [[I for int[][]. In general, [type stands for type[].
And here:
cells = env->CallStaticIntMethod(cls, mid, cells);

Two things:

*

*As mentioned in the very beginning, cells cannot be passed as-is because Java doesn't understand what it is; it needs to be converted to a Java array first (with, for example, the conversion function above), and

*intArrayMethod is not an IntMethod; it does not return an int but a complex data type. The correct call has to use CallStaticObjectMethod and cast the jobject it returns to the actually useful JNI type.

A correct way to do it is:
jobjectArray java_cells = static_cast<jobjectArray>(env->CallStaticObjectMethod(cls, mid, to_java(env, cells)));

This gives you a jobjectArray that you can convert to a C++ vector of vectors with the other conversion function:
std::vector<std::vector<int> > cpp_cells = from_java(env, java_cells);

This can then be used like any vector.
There are some style issues I could mention (such as relying on the array always being 10x10 in the Java code or the use or C functions where there are better (read: typesafe) C++ alternatives -- I'm looking at you, printf), but they don't appear to trigger problems in this particular program.
1 except by pointer to pass it back into native code


text:
Q: SharePoint 2013 App Part and Modal Dialogs I've created a SHP 2013 Sharepoint-Hosted App on visual studio.
On my App.js that's created by default, i have the following lines to show a Modal Dialog
var options = { url: 'http://www.google.com', width: 400, height: 300 };
SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', options);

It works as intended, the little dialog is shown correctly.
After that, i've created a new Client Web Part (App Part) on visual studio, and on the aspx file for my app part i have the same JS lines
<script type="text/javascript">
    var options = { url: 'http://www.google.com', width: 400, height: 300 };
    SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', options);
</script>

But this time it returns an error saying the reference to the property 'execute' is null or undefined.
Is it possible to invoke a modal window from within a App Part? What changes from invoking it from the Default page of my app?
Thanks in advance.

A: you should include Microsoft SP JavaScript API in order to use SP.SOD.
<script type="text/javascript" src="../Scripts/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>

And also check in you Default.aspx page if there is code that you have not included in your App Part page.
edit : If you want to access objets and function of the page containing the iFrame, you can type parent. before your call. e.g. parent.SP.SOD.execute('...'); I hope this will work.

A: I am not sure the above accepted solution works but the working solution is below.
First we need to add the below script tags in the apppart page.
<SharePoint:ScriptLink ID="ScriptLink1" Name="init.js" runat="server" OnDemand="false" LoadAfterUI="true" Localizable="false" />
<SharePoint:ScriptLink ID="ScriptLink2" Name="sp.init.js" runat="server" OnDemand="false" LoadAfterUI="true" Localizable="false" />
<SharePoint:ScriptLink ID="ScriptLink3" Name="sp.runtime.js" runat="server" OnDemand="false" LoadAfterUI="true" Localizable="false" />
<SharePoint:ScriptLink ID="ScriptLink4" Name="sp.core.js" runat="server" OnDemand="false" LoadAfterUI="true" Localizable="false" />
<SharePoint:ScriptLink ID="ScriptLink5" Name="sp.js" runat="server" OnDemand="false" LoadAfterUI="true" Localizable="false" />
<SharePoint:ScriptLink ID="ScriptLink7" Name="sp.ui.dialog.js" runat="server" OnDemand="false" LoadAfterUI="true" Localizable="false" />

Then in the app.js or any script file where your code exists, we need to call the functions as below.
$.getScript(scriptbase + 'SP.Runtime.js', function() {
    $.getScript(scriptbase + 'SP.js', function() {
        $.getScript(scriptbase + 'SP.RequestExecutor.js', function() {
            popup();
        });
    });
});

function popup()
{
    var url = "http:\\www.google.com";
    var options = SP.UI.$create_DialogOptions();
    options.title = "Google";
    options.width = 800;
    options.height = 600;
    options.url = url;
    options.dialogReturnValueCallback = CloseDialogCallback;
    SP.SOD.execute('sp.ui.dialog.js','SP.UI.ModalDialog.showModalDialog',options);
}

function CloseDialogCallback() {
    SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.commonModalDialogClose', 1);
}

The above execution worked for me.


text:
Q: Meaning of floor symbols in $f(x) = \dfrac{1}{2 \lfloor x \rfloor - x + 1}$ The context, from Enumerating the Rationals:

My favourite enumeration of the (non-negative) rationals was discovered by Moshe Newman, and is a simple recurrence relation. More specifically, it is a very basic function f such that the sequence {0, f(0), f(f(0)), f(f(f(0))), …} contains each non-negative rational precisely once.
$f(x) = \dfrac{1}{2 \lfloor x \rfloor - x + 1}$
If you're not amazed by this, you should be. It generates the sequence {0/1, 1/1, 1/2, 2/1, 1/3, 3/2, 2/3, 3/1, 1/4, 4/3, 3/5, 5/2, 2/5, 5/3, …}, which can be proved to hit every non-negative rational exactly once...

How does this work? I am not familiar with the use of the left and right floor symbols and can't find an explanation online.

EDIT
Alternatively we could recursively define the sequence of rational numbers $q: \mathbb{N}\to \mathbb{Q}$ such that:

$q(0) = 0/1$
$\forall x \in \mathbb{N}:[q(x+1) = \dfrac{1}{2 \lfloor q(x) \rfloor - q(x) + 1}]$

Then we would have:
$q(0) = 0/1$
$q(1) = 1/1$
$q(2) = 1/2$
$q(3) = 2/1$
$q(4) = 1/3$
$\vdots$

A: The notation $\lfloor x \rfloor$ (known as 'the floor function') denotes the largest integer less than or equal to $x \in \mathbb{R}$. Examples include $\lfloor7\rfloor$ = $7$, $\lfloor2.5\rfloor$ = $2$, $\lfloor\pi\rfloor$= $3$ and  $\lfloor−2.5\rfloor$ = $-3$.
I'll mention this anyway even though it isn't part of your question. There is another similar function that is the 'counterpart' to the floor function:
The notation $\lceil x \rceil$ (known as 'the ceiling function') denotes the smallest integer greater than or equal to $x \in \mathbb{R}$. So using the same  examples as before $\lceil7$⌉ = $7$, $\lceil2.5\rceil$ = $3$, $\lceil\pi\rceil$= $4$ and  $\lceil−2.5\rceil$ = $-2$.


text:
Q: Send data from Android app to web service I have an Android application with a SQLite database from which I want to send some data to a webservice to store it in a database there.
How would I go about doing this? Is there a smart way of doing it?
I've thought about just extracting the data from the SQLite database and create an XML file to hold and then send the XML file to the webservice, but is there a easier/better way of doing this?

A: JSON is generally seen as a more efficient data format for transferring to and from mobile devices. Check out this post about how to do it. You will, of course, need a web service that can accept and interpret JSON objects.


text:
Q: mutate columns with dynamic names using for loop in R I'm writing a For-loopto mutate columns k_et'm' with dynamic names. k_et did not exist before. b001 b002 b003 ... b012 are 12 variables that are already in the dataframe.
b001 b002 b003 ... b012
-2    2    0   ...   1
-1    1    0   ...   0
 1    1   -1   ...  -2

I put them into a dataframe called b. (But it causes that I generate them again. I feel like it's redundant but cannot think of any other way.)
month <- c("001","002","003","004","005","006","007","008","009","010","011","012")

for(m in 1:length(month)) {
  b <- c(paste0("b",m))
  k_et[m] <- paste0("k_et",month[m])
  df[,k_et[m]] <- ifelse(b[m]==1, 1, 0)
}

I expect to see:
b001 b002 b003 ... k_et001 k_et002 k_et003
-2    2    0   ...   0       0        0
-1    1    0   ...   0       1        0
 1    1   -1   ...   1       1        0

However, all my k_et results are 0. What is the problem?

A: You don't need a loop for this. Do it all at once.
## get the values. ifelse() keeps the dimensions
results = ifelse(df == 1, 1, 0)
## fix the names, replacing "b" with "k_et"
colnames(results) = sub(pattern = "b", replacement = "k_et", x = colnames(results))
## stick them together
df = cbind(df, results)


text:
Q: WP REST API v2 and Angular $http POST request I am trying to add a comment to my WordPress blog with WP-REST API v2 and AngularJS's http. With GET requests everything works properly.
If I use the POST request this way (adding the parameters to the URL) everything works properly and the comment is added with the data.
$http({
  method: 'POST',
  url: 'http://myblog.com/json/wp-json/wp/v2/comments?author_name=Myself&content=Hello guys',
  headers: {
    'Content-Type': undefined
  }
}).then(function (res) {
  console.info('[REST] POST request sent to "' + route + '"');
  d.resolve(res);
}, function (err) {
  console.error('[REST] POST request failed. Error message: ', err);
  d.reject(err);
});

But if I use it this way, with the "data" parameter for $http.get (according to the documentation), the comment is added to WordPress but it's empty. Without content or name.
$http({
  method: 'POST',
  url: 'http://myblog.com/json/wp-json/wp/v2/comments',
  headers: {
    'Content-Type': undefined
  },
  data: {
    author_name: 'Myself',
    content: 'Hello guys'
  }
}).then(function (res) {
  console.info('[REST] POST request sent to "' + route + '"');
  d.resolve(res);
}, function (err) {
  console.error('[REST] POST request failed. Error message: ', err);
  d.reject(err);
});

Why does it not work the second way? Or should I do it with the parameters queried to the URL?
Regards.

A: I solved it. I had to use the application/x-www-form-urlencoded Content-Type and use Angular's $httpParamSerializerJQLike on the data.
$http({
  method: 'POST',
  url: self.address + route,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  data: $httpParamSerializerJQLike(params)
}).then(function (res) {
  console.info('[REST] POST request sent to "' + route + '"');
  d.resolve(res);
}, function (err) {
  console.error('[REST] POST request failed. Error message: ', err);
  d.reject(err);
});


text:
Q: Constants in OpalRB I'm wondering about something in a project of mine with OpalRB (the Ruby-to-JavaScript compiler): when you make a constant in Opal, like so:
ONE = 1

... is that essentially the same thing as saying this is JavaScript?:
const ONE = 1;

The reason that I ask this question is that the const keyword in JS in not always properly supported in each browser and, due to that, I'm somewhat wary about using constants with Opal.

A:
... is that essentially the same thing as saying this is JavaScript?

No it's not. const in JavaScript makes a variable that ignores any re-assignments and keeps its original value. In Ruby, constants complain with a warning when re-assigned, but actually do get re-assigned.
Here is how  ONE=1 in Ruby gets compiled by Opal:
$opal.cdecl($scope, 'ONE', 1);

As you can see, constants aren't stored as variables the way local variables are, they're stored internally inside the scope object.
The cdecl function can do whatever it wants if ONE is already declared. The developers of Opal however, seemed to choose to not show a warning when constants are reassigned. Try this (it's always fun to play around with this webpage and see how the compiler works).
Therefore, constants in Opal-compiled Ruby aren't.


text:
Q: DoctrineCacheBundle: I cannot undersatand the documentation for using it with redis As I was looking the documentation in order to figure out how to use it in order to Cache APi results.
I cannot understand how to setup the configuration in order to make it work with either redis or predis.
I tried the following con figuration:
doctrine_cache:
    aliases:
      my_cache:  'redis'

    providers:
        redis:
          host: '%redis_host%'
          port: '%redis_port%'
          aliases:
            - my_cache

But as I was tryint to debug my container with:
php bin/console debug:container doctrine

I got the error:

"host" is an unrecognized Doctrine cache driver.

I also tried the following configuration:
doctrine_cache:
    aliases:
      my_cache:  'redis'

    providers:
        redis:
          type: 'redis'
          host: '%redis_host%'
          port: '%redis_port%'
          aliases:
            - my_cache

With the very same error. Also on documentation is not very clear how to pass the configaration option. Futhermore as said there both redis and predis are natively provided with the bundle.

A: First setup configuration for redis.
doctrine_cache:
    aliases:
        cache: "%cache_provider%"
    providers:
        redis_cache:
            namespace: "%redis_cache_keyspace%"
            redis:
                host: "%redis_cache_host%"
                port: "%redis_cache_port%"
       array_cache:
            type: array

Then, set parameters.yml:
cache_provider: array_cache
redis_cache_host: localhost
redis_cache_port: 6379
redis_cache_keyspace: [your_keyspace]

I created a RedisService:
<?php

namespace AppBundle\Service;

use Doctrine\Common\Cache\Cache;

class RedisService
{
    private $cache;
    /**
    * RedisService constructor.
    * @param Cache $cache
    */
    public function __construct(Cache $cache)
    {
        $this->cache = $cache;
    }

    public function insert($key, $value, $lifetime = null)
    {
        return $this->cache->save($key, $value, $lifetime);
    }

    public function get($key)
    {
        return $this->cache->fetch($key);
    }

    public function delete($key)
    {
        return $this->cache->delete($key);
    }

}

Add this lines services.yml
redis_service:
    class: AppBundle\Service\RedisService
    arguments: ["@doctrine_cache.providers.redis_cache"]

And you can use it everywhere. Sample;
<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

/**
* @package AppBundle\Controller
* @Route("/")
*/
class RedisApiController extends Controller
{

    /**
    * @return object
    */
    public function getRedisService()
    {
        return $this->get('redis.service');
    }

    /**
    * @Route("/insert", name="insert")
    */
    public function insertAction(){
        $this->getRedisService()->insert('website', 'http://mertblog.net', 3600);
    }

    /**
    * @Route("/get", name="get")
    */
    public function getAction(){
        $webSite = $this->getRedisService()->get('website');
    }

    /**
    * @Route("/delete", name="delete")
    */
    public function deleteAction(){
        $this->getRedisService()->delete('website');
    }
}


text:
Q: Is there a dependency manager for VC++? Our organization has lots of C# and C++ code that we have to integrate. With C#, NuGet is a great option because it manages the build process by adding/updating references in the project files. Is there something similar for Visual C++ that can manage the dependencies between C++ projects? Also, is there something that integrates dependencies between C# and C++?

A: www.cppdepend.com/, cppdepend can analyze the project dependencies in VC ++,,  it is not free. It has a trial version, you can check it out


text:
Q: Typehint addition of lists in python mypy where the lists have different structures Example:
# check.py
x = [("a", "b"), ("c", "d")]
y = [("x", [("1", "2"), ("3", "4")])]
z = x + y

where mypy check.py returns:
check.py:5: error: Unsupported operand types for + ("List[Tuple[str, str]]" and "List[Tuple[str, List[Tuple[str, str]]]]")  [operator]
Found 1 error in 1 file (checked 1 source file)

I know that this addition works though - I don't understand why it's "Unsupported", or what I should do to typehint this.


text:
Q: Laravel query builder - re-use query with amended where statement My application dynamically builds and runs complex queries to generate reports. In some instances I need to get multiple, somewhat arbitrary date ranges, with all other parameters the same.
So my code builds the query with a bunch of joins, wheres, sorts, limits etc and then runs the query. What I then want to do is jump into the Builder object and change the where clauses which define the date range to be queried.
So far, I have made it so that the date range is setup before any other wheres and then tried to manually change the value in the relevant attribute of the wheres array. Like this;
$this->data_qry->wheres[0]['value'] = $new_from_date;
$this->data_qry->wheres[1]['value'] = $new_to_date;

Then I do (having already done it once already)
$this->data_qry->get();

Doesn't work though. The query just runs with the original date range. Even if my way worked, I still wouldn't like it though as it seems to be shot through with a precarious dependence (some sort of coupling?). Ie; if the date wheres aren't set up first then it all falls apart.
I could set the whole query up again from scratch, just with a different date range, but that seems ott as everything else in the query needs to be the same as the previous time it was used.
Any ideas for how to achieve this in the correct / neatest way are very welcome.
Thanks,
Geoff

A: The suggestion from @lukasgeiter using clone is definitely the way to go; the reason is that an Eloquent\Builder object contains an internal reference to a Query\Builder that needs to be duplicated.
To keep the flow of your app and get back to a more functional style, you can use Laravel's with() helper, which simply returns the object passed in:
$result1 = with(clone $this->data_qry)->where('from', $from1)->where('to', $to1)->get();
$result2 = with(clone $this->data_qry)->where('from', $from2)->where('to', $to2)->get();

A: You can use clone to duplicate the query and then run it with different where statements. First, build the query without the from-to constraints, then do something like this:
$query1 = $this->data_qry;
$query2 = clone $query1;

$result1 = $query1->where('from', $from1)->where('to', $to1)->get();
$result2 = $query2->where('from', $from2)->where('to', $to2)->get();

A: For the people who want a simpler and shorter syntax, you can daisy chain the clone() method on the query builder.
$result1 = $this->data_qry->clone()->where('from', $from1)->where('to', $to1)->get();
$result2 = $this->data_qry->clone()->where('from', $from2)->where('to', $to2)->get();


text:
Q: How to differentiate between date formats? I have two date formats :
"yyyy-MM-dd", "dd-MM-yyyy"

But when I am trying to parse the date :"11-05-2021" , it is not throwing exception for "yyyy-MM-dd" format. Below is the thing which I am trying to do :
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
    sdf.parse(d);
} catch (Exception e) {
    e.printStackTrace();
}

Why it is not giving the exception for "yyyy-MM-dd" format . How it can be differentiated between the two formats ?
Thanks


text:
Q: Store number of molecules and elements from a compound(input) in a dictionary I am creating a program in python to take a chemical compound as an input and return the atoms and its number in a dictionary. Most of the work has been done but i cant seem to code how to add to to the number number of atoms if the element is repeated. For example CH3COOH (Acetic acid).
this is the code
element = input("Enter an element: ")
count = {}
string = "";
x = 0
something = "";
something_number = 0
if "(" in  element:
    something = element[element.index("(")+1 : element.index(")")];
    something_number = int(element[element.index(")")+1])
for i in element:
    try:
        if string in something:
            count[string] = int(i) * something_number
            string = "";
            x += 1;
        else:
            count[string] = int(i);
            string = "";
            x += 1;

    except ValueError:
        if i != "(" and i!= ")":
            string += i;
        else:
            pass
        try:
            if element[element.index(i)+1] == element[element.index(i)+1].upper() and element[element.index(i)+1] not in "123456789":
                if string in something:
                    count[string] = something_number
                    string = "";
                    x += 1;
                else:
                    count[string] = 1
                    string = "";
                    x += 1;
        except IndexError:
            if string in something:
                    count[string] = something_number
                    string = "";
                    x += 1;
            else:
                count[string] = 1
                string = "";
                x += 1;
    except:
        print("error")
try:
    for i in enumerate(count):
        if i[1] == "":
            del count[i[1]]
except RuntimeError:
    pass

print(count);

A: I'm not sure if this is what you are looking for, but there are built-in that do what you are looking for. Check counter which is similar to a dictionary,
You need to first expand the molecule
from collections import Counter

def expand_molecule(molecule):
    expand = ""
    for num, val in enumerate(molecule):
        if val.isnumeric():
            expand +=  molecule[num-1]*int(val)
        else:
            expand += val
    return expand

molecule_expand = expand_molecule("CH3COOH")
molecule = Counter(molecule_expand)
print(molecule)

the output is
Counter({'H': 5, 'C': 2, 'O': 2})


text:
Q: Error during batchUpdate of Google Spreadsheets API following https://developers.google.com/sheets/api/guides/batchupdate#example
  sheets.spreadsheets.batchUpdate({
  auth: authClient,
  spreadsheetId: contents.spreadsheetId,
  resource: {
    requests: [
      {
        'insertDimension': {
          'range': {
            'dimension': 'ROWS',
            'endIndex': 2,
            'startIndex': 1,
            'sheetId': 0
          }
        }
      }
    ]
  }
}...

Gives me Error: Must specify at least one request.


text:
Q: Thinking behind decision of database connection pool size i am working on opensource java based application i.e xwiki. Inside hibernate.cfg.xml i can see  value of parameters connection.pool_size and
statement_cache.size as 2 (for each). My application will be having maximum load of 100 users at point of time. Now my question is what should be ideal connection pool size for this. To me  size 2 looks very less. If 100 users connect at a time 98 users have to wait for getting the connection released? Should i keep the connection pool size as 100 in my case?
i am using microsoft sql server.
Apart from this is there a limit on max connection pool size. Does it depend on webserver(tomcat in my case) or datastore vendor(ms sql server)?

A: You should evaluate the application's concurrency requirement, the database operation time, and also the how many connections the server(or db vender) can support.
So 100 users don't means you need a connection pool with size 100.

A: Beware that the pool may cost memory for nothing if unused.
The pool configuration highly depends on where your bottleneck is:
CPU, memory, disc, network, complex database queries, high concurrency, ... many of these ?
Default pool size is often 5 up to 10.
First make sure you have a problem with the database.
Try extremes like 2 or 30 under artificial load and see how it behaves.
I think the links provided by @vlad-mihalcea are quite interesting.

A: Sizing a connection pool is not a trivial thing to do. You basically need:

*

*metrics to investigate the connection usage

*failover mechanisms for when there is no connection available

FlexyPool aims to aid you in figuring out the right connection pool size.

A: If a typical request spends 50% of its time doing calculations and 50% on database connectivity you might only need 50 connections in your pool. Of course your application should release the db connection as early as possible.
In general holding a connection is not expensive for a database (while creating a new one is quite expensive). It should be no problem to keep the size high enough.
You can set

*

*maximum pool size to 100

*preferred pool size to 50

*and the idle timeout to 5 minutes for pooled connections.

I am not familiar with microsoft sql server but I think its max pool limit is 100
Tomcat will be fine with this number of pool size.


text:
Q: What to consider when powering multiple devices in parallel? Briefly about my background, which might inform the question. I'm currently self-educating myself on some electrical engineering on-the-job. I'm learning from Art of Electronics and some other resources, and I studied physics in college.
The problem is this, I have several devices that I need to power from a single source. Their maximum power requirements are the following:

*

*24VDC, 1A, 24W

*24VDC, 1.35A, 30W max

*Three with 24VDC, 46mA each

*Two motors, 18VDC, 0.65A each

The total max current through my system is roughly 4.4A. I need to build a circuit that will handle power to all of these devices. My first assumption was that one should just be able to hook these all up in parallel across a 24V supply that will handle the current. What I have done, which is probably mistake number 1, is hook them all up directly to an 18V supply in parallel (the largest table-top supply we have in the lab). The result: something burned. I imagine if I had a 24V supply it would more than burn.
So, now I'm nose deep in Art of Electronics and these forums looking for principles, concepts, and precautions I should consider when trying to power such a system. I would greatly appreciate if you folks could point me in the right direction as I'm lost in the sea of technical literature.
Basically, I'm hoping someone will tell me "Hey, you need to build this standard current buffering circuit to prevent your parallel devices from drawing too much current and burning up the rest of your system" or "Go look up this concept that should lead you in the right direction as to what happens when you're drawing all kinds of currents in parallel like that"
Thanks in advance folks, hope I can be helped here.

A: The book you're studying is very good, however I am not sure it covers in a straightforward manner the parallel connection of different devices (where a device could contain many additional circuits).
Consider just the first five devices you mention:

*

*Device 1: 24V 1A

*Device 2: 24V 1.35A

*Device 3-5: 24V 0.046A (ea.)

Since they require the same voltage, you can connect them in parallel. The power supply will need to be able to supply their sum total current requirements, ~2.5A (plus additional for inrush current).
If these devices are tolerant of lower voltage, they will try to pull more current to compensate (assuming they aren't just resistive loads like heating coils or something).
Recalculating the current to maintain power for the first five devices:

*

*Device 1: 24W, @18V = 1.33A

*Device 2: 32.4W, @18V = 1.8A

*Device 3-5: 1.1W, @18V = 0.061A (ea.)

Adding the two motors:

*

*Device 6-7: 11.7W, @18V = 0.65A (ea.)

Summing all the current requirements results in ~4.6A, which isn't much more than the 4.4A you originally cited as your total requirement.

I thought it might be helpful to go through and add up all of the device requirements, but in this case, I don't think the problem necessarily lies with the power supply (unless it cannot handle >4A) or voltage differences. Per Ron Beyer and Simon B's comments on your question, I'd suggest adding flyback diodes to the motors to protect the other devices, and double-check your wiring to ensure you haven't simply made a mistake.


text:
Q: Как убрать рамку у canvas при использовании tkinter? canvas = Canvas(top, width=1000, height=600, bg = "lightblue", cursor = "circle")

bd или borderwidth, согласно документации, должен работать, но от вставки в строку параметра ничего не меняется вообще (ни в большую ни в меньшую сторону) и ошибку не выдает. Как убрать рамку?

A: from tkinter import *

root = Tk()
canvas_1 = Canvas(root, width=200, height=200, bg='red', highlightthickness=0)
canvas_1.grid(row=0, column=0)

root.mainloop()


text:
Q: Load More Custom Posts On Click Ajax WordPress I'm trying to create a load more button that loads more custom post types on click, however, I keep receiving a 400 (Bad Request) error. Here is the code i'm using.
// Header.php
<!doctype html>
<html <?php language_attributes(); class="no-js">


text:
Q: Add clicky tracking code to wordpress via functions.php I wan to add clicky analytics to my website using functions.php and I used the following but it's not working:
function my_custom_footer_output() {
  ?>

  <?php
}

add_action( 'wp_footer', 'my_custom_footer_output', 99999 );

A: Update: For this to work, use this code:
function my_custom_head_output() {
  ?>
    ...code here...
  <?php
}

add_action( 'wp_head', 'my_custom_head_output', 99999 );

In our case, it would be similar to the below:
function my_custom_head_output() {
  ?>

  <?php
}

add_action( 'wp_head', 'my_custom_head_output', 99999 );

Credit: Kory


text:
Q: How to show an estimator is consistent and solve the asymptotic distribution? Question:
Let $X_1,……,X_n$ be an i.i.d random sample from the distribution with PDF
$f(x;\theta)=\theta(1+\theta)x^{\theta-1}(1-x),0<x<1,\theta>0$
a)Find the method of moments estimator for $\theta$ based on the first moment of $X_i$
b)Show the estimator obtained in part(a) is consistent.Derive its asymptotic distribution."
Confusion:
It's easy to calculate that the answer for part should be $\hat{\theta}=\frac{2\overline{X_n}}{1-\overline{X_n}}$,the question is part b. To prove consistent, we must prove$\frac{2\overline{X_n}}{1-\overline{X_n}}\xrightarrow[]{p}\theta$,since only "$L_P$-Convergence" and "Almost Sure convergence" can led to  "Convergence in Probability", but I've tried these two method, nothing. What's the correct method to solve this problem?

A: By WLLN $\bar{X}_n \xrightarrow{p} \mathbb{E}[X]$. Now, note that $g(x)=2/(1-x)$ is continuous function over $(0,1)$, thus by the continuous mapping theorem
$$
\frac{2}{1-\bar{X}_n} \xrightarrow{p} \frac{2}{1-\mathbb{E}[X]},
$$
thus
$$
\frac{2\bar{X}_n}{1-\bar{X}_n} \xrightarrow{p} \frac{2\mathbb{E}[X]}{1-\mathbb{E}[X]}.
$$
So, you just have to calculate
$$
\mathbb{E}[X]=\int_{(0,1)} xf_X(x;\theta)dx
$$
and plug in the result.


text:
Q: Github insight not been updated i have a repo where 2 friend of mine and I are working together, and I would like to get Insights about every contributor, however Github has stopped to count mine commits for some reason.
I've already read about the criteria used to "approve" commits that will be counted on the insights tab, and I can see from here that my problem is the following:

Have you added the email used to author the commit (some_username_that_is_not_an_email) to your GitHub account?

However some_username_that_is_not_an_email is not an email, and so I cant go to my profile and add that as approved email
So I was wondering, are there other "Insight repo/website/project" that counts contributions also of not approved commits, or are there ways to get Github accepts those commits (preferably without having to change the information of each commit)?

A: From the discussion in the comments, there isn't any (or at least any popular) project/app/plugin that can easily give out statistics and integrate at the same time with GitHub.
But there are plenty of very nice tools and apps that can give us a wide range of git-related statistics, which we can later publish and share.
I suggest using gitstats.
To use it:
# clone
git clone https://github.com/hoxu/gitstats.git
cd gitstats

# run
./gitstats <repo location> <stats output>

# view stats from output dir
firefox index.html

This can provide us with multiple pages of all kinds of people who have commited. Both Github verified and any other users that have validly created a commit will be mentioned in the statistical output.
This does satisfy the requirements with the only downside that it is not integrated with Github, but at least the output can easily be shared and published.


text:
Q: Erro "phonegap run android" Estou tento problemas para executar o comando $phonegap run android.
Dá o seguinte erro:

   C:\Users\maquina05\App_Oliver>phonegap run android
[phonegap] executing 'cordova run android ' ...
ANDROID_HOME=C:\Program Files (x86)\Android\android-sdk
JAVA_HOME=C:\Program Files (x86)\Java\jdk1.8.0_111

Subproject Path: CordovaLib

Unzipping C:\Users\maquina05\.gradle\wrapper\dists\gradle-2.14.1-all\53l0mv9mggp
9q5m2ip574m21oh\gradle-2.14.1-all.zip to C:\Users\maquina05\.gradle\wrapper\dist
s\gradle-2.14.1-all\53l0mv9mggp9q5m2ip574m21oh

Exception in thread "main"
java.lang.RuntimeException: java.util.zip.ZipException: zip file is empty
        at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAcc
essManager.java:78)
        at org.gradle.wrapper.Install.createDist(Install.java:47)
        at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:129)
        at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:48)
Caused by: java.util.zip.ZipException: zip file is empty
        at java.util.zip.ZipFile.open(Native Method)
        at java.util.zip.ZipFile.<init>(ZipFile.java:219)
        at java.util.zip.ZipFile.<init>(ZipFile.java:149)
        at java.util.zip.ZipFile.<init>(ZipFile.java:163)
        at org.gradle.wrapper.Install.unzip(Install.java:160)
        at org.gradle.wrapper.Install.access$400(Install.java:29)
        at org.gradle.wrapper.Install$1.call(Install.java:70)
        at org.gradle.wrapper.Install$1.call(Install.java:47)
        at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAcc
essManager.java:65)
        ... 3 more

Error: cmd: Command failed with exit code 1 Error output:
Exception in thread "main" java.lang.RuntimeException: java.util.zip.ZipExceptio
n: zip file is empty
        at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAcc
essManager.java:78)
        at org.gradle.wrapper.Install.createDist(Install.java:47)
        at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:129)
        at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:48)
Caused by: java.util.zip.ZipException: zip file is empty
        at java.util.zip.ZipFile.open(Native Method)
        at java.util.zip.ZipFile.<init>(ZipFile.java:219)
        at java.util.zip.ZipFile.<init>(ZipFile.java:149)
        at java.util.zip.ZipFile.<init>(ZipFile.java:163)
        at org.gradle.wrapper.Install.unzip(Install.java:160)
        at org.gradle.wrapper.Install.access$400(Install.java:29)
        at org.gradle.wrapper.Install$1.call(Install.java:70)
        at org.gradle.wrapper.Install$1.call(Install.java:47)
        at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAcc
essManager.java:65)
        ... 3 more

Excutando $cordova run android ,da exatamente o mesmo erro.
Como posso resolver este problema?

Denis.
Fiz o seu procedimento e deu o seguinte erro.
C:\Users\maquina05\App_Oliver>cordova build
ANDROID_HOME=C:\Program Files (x86)\Android\android-sdk
JAVA_HOME=C:\Program Files (x86)\Java\jdk1.8.0_111
Subproject Path: CordovaLib
Downloading http://services.gradle.org/distributions/gradle-2.14.1-all.zip
...............................................................................
Unzipping C:\Users\maquina05\.gradle\wrapper\dists\gradle-2.14.1-   all\53l0mv9mggp
9q5m2ip574m21oh\gradle-2.14.1-all.zip to     C:\Users\maquina05\.gradle\wrapper\dist
s\gradle-2.14.1-all\53l0mv9mggp9q5m2ip574m21oh
Starting a new Gradle Daemon for this build (subsequent builds will be   faster).

FAILURE: Build failed with an exception.

* What went wrong:
Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the user guide chapter on the daemon at     https://docs.gradle.org/
2.14.1/userguide/gradle_daemon.html
Please read the following process output to find out more:
-----------------------
Error occurred during initialization of VM
Could not reserve enough space for 2097152KB object heap.

Ja criei o gradle nas variaveis de ambiente e quando eu dou o comando:
$gradle -v

------------------------------------------------------------
Gradle 3.4.1
------------------------------------------------------------

Build time:   2017-03-03 19:45:41 UTC
Revision:     9eb76efdd3d034dc506c719dac2955efb5ff9a93

Groovy:       2.4.7
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          1.8.0_111 (Oracle Corporation 25.111-b14)
OS:           Windows 7 6.1 x86

A: Encontrei essa resposta no StackOverflow em inglês, segundo a mensagem de erro, o arquivo está corrompido.
Apague o conteúdo de C:\Users\maquina05\.gradle\wrapper\dists\gradle-2.14.1-all\53l0mv9mggp9q5m2ip574m21oh e rode o comando cordova build novamente

Error occurred during initialization of VM
Could not reserve enough space for 2097152KB object heap.

Significa que não há memória suficiente para inicializar a VM, dei uma olhada em alguns fórums a solução que encontrei para o segundo problema é criar um arquivo project.properties e adicionar o conteúdo:
org.gradle.jvmargs=-Xmx512m -XX:MaxPermSize=512m

Outra forma de definir esse valor é pela variável de ambiente GRADLE_OPTS, o valor dela deve ser -Dorg.gradle.jvmargs=-Xmx512m