text:
Q: Dynamic sized UIImageView in UIScrollView with some complex conditions How should I configure AutoLayouts if I want to create this kind of layout? Or let me know if it's impossible by only AutoLayout.
[UIView]
  [UIScrollView]
    [UIImageView]
    [UILabel]
    [UIButton]

Conditions I want to realize:

*

*UIImageView:

*

*width:height = 1:1 (Aspect Ratio = 1:1)

*width <= UIView.width (Max Width)

*width >= UIView.width*70% (Min Width)

*If screen size is large enough, UIImageView should expand to Max Width and scrolling is not needed.

*If screen size is not large enough but can be shown in its Min Width without any scrolling, UIImageView should shrink to Min Width and scrolling is not needed (ie. all subviews is shown without any scroll).

*If screen size is not large enough and scrolling is needed even if UIImageView shrinks to Min Width, UIImageView should shrink to Min Width and scrolling is needed (ie. NOT all subviews is shown without any scroll).

A: This might do the trick for you...
Kinda tough to explain everything, but you should be able to follow the constraints in the image. The only thing you cannot see is that the multi-line label must have its Content Compression Resistance Priority set to Required (1000).
The idea is to set constraints with specific Priority values so auto-layout will try to make the image view width - at 998 Priority - as wide as the scroll view, but allow it to shrink to a minimum width of 70% as the content below it grows. When it reaches 70%, it will not get any smaller, and the combined heights of the image view + label + button will force the "content" view to expand vertically, as it has a height constraint of 999.
Here the label has 7 lines of text, with a font size of 18:

And here's how it looks with the font size increased to 28 - notice that the image view is now less-than the full width of the scroll view:

and now, with the font size increased to 36, we see that the image view is at its min width of 70%, and the button has been pushed down past the bottom of the scroll view's frame (so everything will scroll):

Here's the source for the Storyboard - play around with the font-size and/or the amount of text in the label to see it work:
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14460.31" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="eB4-FG-006">
    <device id="retina4_7" orientation="portrait">
        <adaptation id="fullscreen"/>
    </device>
    <dependencies>
        <deployment identifier="iOS"/>
        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14460.20"/>
        <capability name="Safe area layout guides" minToolsVersion="9.0"/>
        <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
    </dependencies>
    <scenes>
        <!--View Controller-->
        <scene sceneID="cKl-8C-enU">
            <objects>
                <viewController id="eB4-FG-006" sceneMemberID="viewController">
                    <view key="view" contentMode="scaleToFill" id="qMY-Qc-gio">
                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                        <subviews>
                            <scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="q6G-7e-kz1">
                                <rect key="frame" x="20" y="60" width="335" height="567"/>
                                <subviews>
                                    <view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="mbq-g1-m6Z" userLabel="ContentView">
                                        <rect key="frame" x="0.0" y="0.0" width="335" height="567"/>
                                        <subviews>
                                            <imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="N7z-eO-cci">
                                                <rect key="frame" x="0.0" y="0.0" width="335" height="335"/>
                                                <color key="backgroundColor" red="0.0" green="0.97680455450000003" blue="0.0" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                                <constraints>
                                                    <constraint firstAttribute="width" secondItem="N7z-eO-cci" secondAttribute="height" multiplier="1:1" id="3Za-Q8-IFq"/>
                                                </constraints>
                                            </imageView>
                                            <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" verticalCompressionResistancePriority="1000" textAlignment="natural" lineBreakMode="tailTruncation" numberOfLines="0" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Pp5-EQ-8Vh" userLabel="Multi-LineLabel">
                                                <rect key="frame" x="142.5" y="343" width="50" height="150.5"/>
                                                <color key="backgroundColor" red="0.99953407049999998" green="0.98835557699999999" blue="0.47265523669999998" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                                <string key="text">Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7</string>
                                                <fontDescription key="fontDescription" type="system" pointSize="18"/>
                                                <nil key="textColor"/>
                                                <nil key="highlightedColor"/>
                                            </label>
                                            <button opaque="NO" contentMode="scaleToFill" verticalCompressionResistancePriority="1000" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="rg8-I7-3hZ">
                                                <rect key="frame" x="144.5" y="501.5" width="46" height="30"/>
                                                <color key="backgroundColor" red="1" green="0.83234566450000003" blue="0.47320586440000001" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                                <constraints>
                                                    <constraint firstAttribute="height" constant="30" id="NZU-hx-0M5"/>
                                                </constraints>
                                                <state key="normal" title="Button"/>
                                            </button>
                                        </subviews>
                                        <color key="backgroundColor" red="1" green="0.14913141730000001" blue="0.0" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                        <constraints>
                                            <constraint firstItem="rg8-I7-3hZ" firstAttribute="top" secondItem="Pp5-EQ-8Vh" secondAttribute="bottom" constant="8" id="6c5-vJ-c8B"/>
                                            <constraint firstItem="rg8-I7-3hZ" firstAttribute="centerX" secondItem="mbq-g1-m6Z" secondAttribute="centerX" id="C6W-uG-Irk"/>
                                            <constraint firstItem="Pp5-EQ-8Vh" firstAttribute="centerX" secondItem="mbq-g1-m6Z" secondAttribute="centerX" id="MDd-eI-O2X"/>
                                            <constraint firstItem="Pp5-EQ-8Vh" firstAttribute="top" secondItem="N7z-eO-cci" secondAttribute="bottom" constant="8" id="Ozv-Hn-EbX"/>
                                            <constraint firstItem="N7z-eO-cci" firstAttribute="top" secondItem="mbq-g1-m6Z" secondAttribute="top" id="Qbn-EK-zhn"/>
                                            <constraint firstAttribute="bottom" relation="greaterThanOrEqual" secondItem="rg8-I7-3hZ" secondAttribute="bottom" constant="8" id="XRT-bz-2bI"/>
                                            <constraint firstItem="rg8-I7-3hZ" firstAttribute="top" secondItem="Pp5-EQ-8Vh" secondAttribute="bottom" constant="8" id="bny-1w-xOv"/>
                                            <constraint firstItem="N7z-eO-cci" firstAttribute="width" relation="greaterThanOrEqual" secondItem="mbq-g1-m6Z" secondAttribute="width" multiplier="0.7" id="bsP-M1-7uP"/>
                                            <constraint firstItem="N7z-eO-cci" firstAttribute="width" secondItem="mbq-g1-m6Z" secondAttribute="width" priority="998" id="fr8-4U-00h"/>
                                            <constraint firstItem="N7z-eO-cci" firstAttribute="centerX" secondItem="mbq-g1-m6Z" secondAttribute="centerX" id="hVh-Ld-mDS"/>
                                        </constraints>
                                    </view>
                                </subviews>
                                <color key="backgroundColor" red="0.0" green="0.47843137250000001" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
                                <constraints>
                                    <constraint firstAttribute="trailing" secondItem="mbq-g1-m6Z" secondAttribute="trailing" id="Fbg-Dx-idJ"/>
                                    <constraint firstAttribute="bottom" secondItem="mbq-g1-m6Z" secondAttribute="bottom" id="Hrx-mL-t1p"/>
                                    <constraint firstItem="mbq-g1-m6Z" firstAttribute="top" secondItem="q6G-7e-kz1" secondAttribute="top" id="La2-Bo-p6J"/>
                                    <constraint firstItem="mbq-g1-m6Z" firstAttribute="leading" secondItem="q6G-7e-kz1" secondAttribute="leading" id="S8w-du-yf0"/>
                                    <constraint firstItem="mbq-g1-m6Z" firstAttribute="height" secondItem="q6G-7e-kz1" secondAttribute="height" priority="999" id="lWB-wI-t5Q"/>
                                    <constraint firstItem="mbq-g1-m6Z" firstAttribute="width" secondItem="q6G-7e-kz1" secondAttribute="width" id="ynr-jB-Phr"/>
                                </constraints>
                            </scrollView>
                        </subviews>
                        <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
                        <constraints>
                            <constraint firstItem="ASm-Jv-0JK" firstAttribute="trailing" secondItem="q6G-7e-kz1" secondAttribute="trailing" constant="20" id="27b-fv-IjT"/>
                            <constraint firstItem="q6G-7e-kz1" firstAttribute="leading" secondItem="ASm-Jv-0JK" secondAttribute="leading" constant="20" id="4sv-oj-8jc"/>
                            <constraint firstItem="q6G-7e-kz1" firstAttribute="top" secondItem="ASm-Jv-0JK" secondAttribute="top" constant="40" id="KKa-P9-1oI"/>
                            <constraint firstItem="ASm-Jv-0JK" firstAttribute="bottom" secondItem="q6G-7e-kz1" secondAttribute="bottom" constant="40" id="b3R-Aw-brw"/>
                        </constraints>
                        <viewLayoutGuide key="safeArea" id="ASm-Jv-0JK"/>
                    </view>
                </viewController>
                <placeholder placeholderIdentifier="IBFirstResponder" id="zh5-Lh-ZPo" userLabel="First Responder" sceneMemberID="firstResponder"/>
            </objects>
            <point key="canvasLocation" x="806" y="-161"/>
        </scene>
    </scenes>
</document>


text:
Q: Sharepoint 2016 compatibility with MS Office 2013 We currently have a SharePoint 2013 single farm solution. We also have all our users on MS Office 2013. Prior to this our users were accessing documents within the SP 2013 site using SP 2010 where we had endless problems with accessibility which was determined to be the difference in platforms of SP and MS Office.
My question is will this be an issue going forward? We are moving from SP2013 to SP2019 but the users will be using MS Office 2016 - will we come up against the same issue with the compatibility with opening documents and creating and accessing InfoPath forms.

A: No you won't face compatibility issues as such , since I have been using the same scenario in my current project.
I am working on both SP2016 and SP2019 with MS Office 2016 .

A: Infopath has not really changed in years (I think what you had in office2013 is same in office2019 maybe apart from some sec updates that affect the whole office). MS wanted to kill many times but faced backslash from large enterprises that use it a lot. You should not face any issues.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to make a generic intent with GPS coordinates? In my application, when I click on a place, I would like to fire the Intent Chooser that would let the user play with GPS coordinates...
I would like the intent to let the user have the choice between Google Maps, Navigation, StreetView, or any installed GPS....
So far, each one of these apps can be launched with a different intent.. like:
Navigation:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=" +mLat+","+mLong));

Google Earth:
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("geo:"
+ "?q="
+ e.latitude
+ ","
+ e.longitude)));

Google Maps:
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("geo:"
+ e.latitude
+ ","
+ e.longitude
+ "?q="
+ e.latitude
+ ","
+ e.longitude)));

StreetView:
Something different
Navigon:
<action android:name="android.intent.action.navigon.START_PUBLIC" />
Location coordinates.
String INTENT_EXTRA_KEY_LATITUDE = "latitude";
String INTENT_EXTRA_KEY_LONGITUDE = "longitude";

Any GPS app:
Is there a way to use a single intent for all these apps and let the user choose?

A:
Is there a way to use a single intent for all these apps and let the user choose?

Presumably not. You are welcome to use PackageManager and queryIntentActivities() to build your own chooser that combines the results of various Intent objects.


text:
Q: Why is it not allowed to define a class object in the same class? Here is my code:
class Link;
class LinkScreen;
class LinkScreen {
    Link* linkScreen1;
    LinkScreen linkScreen2;
};

class Link {};

The make error:
test.cpp:6:16: error: field 'linkScreen2' has incomplete type

Why is this not allowed?

A: A class can't contain an instance of itself because that would make the instances take up an infinite amount of space.
Think about it:  you create a LinkScreen object…  which contains another LinkScreen object…  which contains another LinkScreen object, which contains yet another, and so on.
Or, to look at it another way, what's the size of a LinkScreen object?  Well, it's the size of the variables it contains:  a Link* (typically 4 or 8 bytes) plus the size of a LinkScreen object.  But how big is that?  Well, it's the size of a Link* plus the size of a LinkScreen.  You can see the infinite recursion here.
You can only create an instance of a type that's "complete", which for a class means that the compiler has seen the closing brace of the class definition.  That prevents you from putting an instance within the class itself.  You can create a pointer to an incomplete type, though; it's OK for a LinkScreen object to contain a LinkScreen* variable.

A: Duplicate: why can't we declare object of a class inside the same class?
Because it requires knowing the size of each of the constituent members of the class linkScreen. In your case size of linkScreen2 is not known, since the class is not completely defined at that very moment.

A: Your problem is that your LinkScreen object contains a LinkScreen object, which then contain a LinkScreen object which then contain a LinkScreen object and so on. I guess it should be a pointer instead.

A: Because it is simply illogical:
I suppose you mean LinkScreen * linkScreen2;or LinkScreen& linkScreen2;
If you really want LinkScreen linkScreen2;, then just imagine:  A LinkScreen object is going to contain (not referring to) a LinkScreen object, which in turns contain a LinkScreen object..... It is never going to end.

A bit more on having another class as member.
Unlike having pointer/ref to another class, if you want to contain another class as member, having only forward declaration is not enough.  Compiler needs to know the actual "layout" of your members, so it can "decide" the "layout of memory" of that class.  Therefore you need a complete declaration of the "contained class" available before your class.  Which means, it is never going to be possible to have your class "contains" a member of same type.


text:
Q: Cannot call static method in static class from other classes I have a static class (C#):
public static class PRRoles
{
    public static Dictionary<int, string> Roles
    {
        get
        {
            return DAPRRoles.GetPRRoles();
            //Dictionary<int, string> returnme = new Dictionary<int, string>();

            //returnme = DAPRRoles.GetPRRoles();

            //return returnme;
        }
    }
    public static bool IsPRRole(RoleType RT)
    {
        return Roles.ContainsKey((int)RT);
    }

}

and this is how I call:
if(PRRoles.IsPRRole(RoleType.Contracts))

Here is class DAPRRoles with the method defined:
public class DAPRRoles
{
    public static Dictionary<int, string> GetPRRoles()
    {
        Dictionary<int, string> dicRoles = new Dictionary<int, string>();
        try
        {
            DataTable PRRoles = new WFDataLayer().GetPRRoles();
            foreach (DataRow r in PRRoles.Rows)
            {
                dicRoles.Add(int.Parse(r["roleid"].ToString()), r["description"].ToString());
            }
        }
        catch (Exception ex)
        {
            WriteLog(String.Format("GetPRRoles() threw Exception"));
            WriteLog(String.Format("Message: {0}", ex.Message));
            throw new Exception("JacobsWF.DAPRRoles.GetPRRoles Exception : " + ex.ToString());
        }

        return dicRoles;

    }
}

note that I must type the method name because intellisense does not show it.
This is the enum definition for RoleType above and it is defined outside of any class and is used successfully throughout the code.
public enum RoleType
{
    Undefined = 0,
    //Employee Types
    Employee = 1,
    JobManager = 2,
    Delegate = 3,
    JobManager2 = 4,
    //Purchase Request Buyer Types
    Buyer = 100,
    BusinessAdmin = 101,
    Contracts = 102,
    Admin = 103,
    //Purchase Request Workflow Types
    [Description("Property Manager")]
    PropertyAdmin = 104,
    [Description("Contract Administrator")]
    ContractAdmin = 105,
    [Description("Office Director")]
    OfficeDirector = 106,
    [Description("Program Manager")]
    ProgramManager = 107,
    [Description("Financial Analyst")]
    FinancialAnalyst = 108,
    //Groups
    ADGroup = 1000,
    SharePointGroup = 2000,
    // External
    ExternalContact = 10000

}

IsPRRole is not visible to any other class, pages or methods and the application will not build if there are any calls to the method. Is this because the Roles Property of the class accesses data outside the code?
Is there an easy way to resolve this? Can I create a static method in the static class that would be visible?
One more note: There are multiple instances of calling static methods throughout the rest of the solution - which includes multiple projects - all compile and run successfully. This is the only one that is giving me this issue.
Thanks,
John

A: You call static methods using the class name.  So, if I boil your code down to something that compiles.  I've updated my repro so that it's closer to your code (by including a DAPRRoles class and a RoleType enum).  You should be able to create a simple console or WinForms or WPF app, throw this code in, see it compile and step through it by calling PRRoles.IsPRRole(someInt); :
public static class PRRoles {
    public static Dictionary<int, string> Roles {
        get {
            return DAPRRoles.GetPRRoles();
        }
    }
    public static bool IsPRRole(int i){
        return Roles.ContainsKey(i);
    }
}

public class DAPRRoles {
    public static Dictionary<int, string> GetPRRoles() {
        Dictionary<int, string> dicRoles = new Dictionary<int, string>();
        dicRoles.Add(1, "One");
        dicRoles.Add(5, "five");
        return dicRoles;
    }
}

public enum RoleType {
    Undefined = 0,
    Employee = 1,
    JobManager = 2,
    Delegate = 3,
    JobManager2 = 4,
}

I can call it (from somewhere else in my app) this way: PRRoles.IsPRRole(1); and see true returned, if I pass 2, I see false.


text:
Q: Displaying an SQLite record as part of a TextView (ANDROID) most of my Android questions have been answered from this site, but I have one particular problem that I have not been able to find.  I would like to retrieve various columns of a record from an SQLite database using textview.  For example,
Welcome COLUMN1VALUE, from our records you are living in COLUMN2VALUE and have been living there for COLUMN3VALUE years.
Can anybody point me in the direction of a tutorial or give me an answer for this?  Thanks!
Here is the code:
      private void fillData(Uri uri) {
            String[] projection = { TodoTable.COLUMN_COREBELIEF,
                TodoTable.COLUMN_EXPERIENCE1,
                TodoTable.COLUMN_EXPERIENCE2,
                TodoTable.COLUMN_EXPERIENCE3,
                TodoTable.COLUMN_NEWBELIEF,};

        //    String query = "SELECT COLUMN_NEWBELIEF,COLUMN_COREBELIEF,COLUMN_EXPERIENCE1 FROM TodoTable";

            Cursor cursor = getContentResolver().query(uri, projection, null, null, null);

    //          Cursor cursor = db.rawQuery(query, null);
                if (cursor != null) {
                      cursor.moveToFirst();
                String s = String.format("Welcome %s, from our records you are living in %s and have been living there for %s years.", cursor.getString(cursor.getColumnIndex("COLUMN_NEWBELIEF")),  cursor.getString(cursor.getColumnIndex("COLUMN_COREBELIEF")), cursor.getString(cursor.getColumnIndex("COLUMN_EXPERIENCE1")));
                textView1.setText(s);

              }

//            mCoreBelief.setText(cursor.getString(cursor
//                .getColumnIndexOrThrow(TodoTable.COLUMN_COREBELIEF)));
//            mExperience1.setText(cursor.getString(cursor
//                .getColumnIndexOrThrow(TodoTable.COLUMN_EXPERIENCE1)));
//            mExperience2.setText(cursor.getString(cursor
//                    .getColumnIndexOrThrow(TodoTable.COLUMN_EXPERIENCE2)));
//            mExperience3.setText(cursor.getString(cursor
//                    .getColumnIndexOrThrow(TodoTable.COLUMN_EXPERIENCE3)));
//            mNewBelief.setText(cursor.getString(cursor
//                    .getColumnIndexOrThrow(TodoTable.COLUMN_NEWBELIEF)));

              // Always close the cursor
              cursor.close();
            }

A: You can do so easily by following code:
 String query = "SELECT col1,col2,col3 FROM mytable";
 Cursor c = db.rawQuery(query, null);
 c.moveToFirst();
 String s = String.format("Welcome %s, from our records you are living in %s and have been living there for %s years.", c.getString(c.getColumnIndex("col1")),  c.getString(c.getColumnIndex("col2")), c.getString(c.getColumnIndex("col3")));
 txtView.setText(s);

A: Does your SQLite database already exist or do you need guidance on how to manage the entire lifecycle of a SQLite database in Android?
If your database already exists, then @hrehman's answer is enough otherwise Lar Vogel's tutorial at http://www.vogella.com/articles/AndroidSQLite/article.html is excellent.

A: Fixed!!  I amended your code as follows:
  private void fillData(Uri uri) {
      TextView textView1 = (TextView) findViewById(R.id.textView1);
        String[] projection = { TodoTable.COLUMN_COREBELIEF,
            TodoTable.COLUMN_EXPERIENCE1,
            TodoTable.COLUMN_EXPERIENCE2,
            TodoTable.COLUMN_EXPERIENCE3,
            TodoTable.COLUMN_NEWBELIEF,};
        Cursor cursor = getContentResolver().query(uri, projection, null, null,
            null);
        if (cursor != null) {
          cursor.moveToFirst();
          String s = String.format("Welcome %s, from our records you are living in %s and have been living there for %s years.",
                  cursor.getString(cursor.getColumnIndexOrThrow(TodoTable.COLUMN_NEWBELIEF)),  cursor.getString(cursor.getColumnIndexOrThrow(TodoTable.COLUMN_COREBELIEF)), cursor.getString(cursor.getColumnIndexOrThrow(TodoTable.COLUMN_EXPERIENCE1)));
          textView1.setText(s);
                      }

Thanks!


text:
Q: Proof verification: For isomorphism $\phi: G\to H$, show that $|\phi (a)|=|a|$ for all $a\in G$. Could someone please verify my following proof?

For isomorphism $\phi: G\to H$ of the groups $G$ and $H$, show that $|\phi (a)|=|a|$ for all $a\in G$.

Proof: Let $a\in G$ with $|a|=n$. Then $a^{n}=e_{G}$, the identity of $G$. Let $|\phi(a)|=m$. Then $(\phi (a))^{m}=e_{H}$, the identity of $H$, or $\phi (a^{m})=e_{H}$. Since $\phi(e_{G})=e_{H}$, it must be that $a^{m}=e_{G}$. Then it must be that $m=n$. Therefore, $|\phi (a)|=|a|$ for all $a\in G$.


text:
Q: react-redux-firebase, "You may need an appropriate loader to handle this file type." I am working on a project that integrates react, redux, and firebase. react-redux-firebase seems to be a convenient tool. However, the code is not being complied successfully. Below is the error, webpack.config.js, .babelrc, and index.js. Thanks for help in advance.
Error message:
ERROR in ./~/react-redux-firebase/src/connect.js
Module parse failed:
/Users/xiqianglin/ucsdflyers/node_modules/react-redux-firebase/src/connect.js
Unexpected token (43:24) You may need an appropriate loader to handle this file type.
|     }
|
|     static contextTypes = {
|       store: PropTypes.object.isRequired
|     };
@ ./~/react-redux-firebase/src/index.js 1:0-31  @ ./src/index.js  @ multi ./src/index.js

/****And there are other similar errors, all "...appropriate loader..." ***/

webpack.config.js
var HtmlWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
    template: __dirname + '/src/index.html',
    filename: 'index.html',
    inject: 'body'
});

module.exports = {
entry: [
      './src/index.js'
        ],

module: {
      loaders: [
                  {test: /\.js$/,
                   exclude: /node_modules/,
                   loader:'babel-loader'}
                ]
        },

resolve: {
    extensions: [".js", ".jsx", ".es6"]
},

output: {
      filename: "index_bundle.js",
      path: __dirname + '/dist'
        },

plugins: [HTMLWebpackPluginConfig]
};

.babelrc
{
  "presets": ["react", "es2015"]
}

index.js
/*Other Imports...*/
import { firebaseStateReducer } from 'react-redux-firebase'; //This is the line causing error

ReactDOM.render(
  <Provider>
    <App/>
  </Provider>,
  documeng.getElementById('app')
)

A: Duble check that you npm install-ed all your dependencies.
Then if that doesn't work, try this:
npm install babel-preset-es2015
and add the a query for es2015 after your exclude
{
  test: /\.js$/,
  exclude: /node_modules/,
  loader:'babel-loader',
  query: {
    presets: ['es2015']
  }
}

If you need to include a specific node module, try including your source directory and that specific node module folder to be parsed by babel-loader.
So instead of the exclude: /node_modules/, try
  include: [
    path.resolve(__dirname, "src"),
    path.resolve(__dirname, "node_modules/react-redux-firebase")
  ]


text:
Q: Is there an equivalent to `overflow:scroll` in Flutter web? I'm trying to access the native scrollbar of the browser (check out the thing on the right side here). Normally, if the content of a widget exceeds the viewport, Flutter throws an error like: A RenderFlex overflowed by 445 pixels on the bottom. Is there a setting or something that can tell Flutter web to just make that particular widget scrollable? If we use the Scrollbar widget than it's not draggable, and the DraggableScrollbar widget looks very weird and the implementation code is way over my pay grade. I just want the normal scrollbar that my grandparents are used to.

A: I write the full steps because maybe someone is going to use the DraggableScrollbar widget for the first time.
1. Add this to the pubspec.yaml dependencies:
draggable_scrollbar: ^0.0.4

2. Import the package:
import 'package:draggable_scrollbar/draggable_scrollbar.dart';

3. Define a ScrollController:
final ScrollController _scrollController = ScrollController();

4. Usage:
@override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
          child: DraggableScrollbar.rrect(
            controller: _scrollController,
            heightScrollThumb: 100,
            backgroundColor: Colors.yellow,
            child: ListView.builder(
              controller: _scrollController,
              itemExtent: 150.0,
              itemCount: 50,
              itemBuilder: (context, index) {
                return Container(
                  child: Card(
                    child: Center(
                      child: Text(index.toString()),
                    ),
                  ),
                );
              },
            ),
          ),
        ),
    );
  }


text:
Q: Can I Structure this Data in a More Efficient Way? I'm implementing a list of research_projects with dynamic filtering. I have a bunch of tables in the database representing their many-to-many relationships with fields such as principal investigator and funder.
Because I want the filtering to be dynamic, I am pulling ALL of this data up front and storing it in the browser, then filtering that data with javascript.
Currently, the data I'm pulling has the following structure:
research_projects =
{
    "RPGUID1":
    {
        "title":"blah",
        "summary":"balh",
        "description":"blah",
        etc...
    },
    "RPGUID2":
    {
        "title":"blah2",
        etc...
    },
    ...
}
principal_investigators =
{
    "12345":
    {
        "name":"John D",
        "slug":"john-d",
        "research_projects":["RPGUID2"]
    },
    ...
}
funders =
{
    "aaaa":
    {
        "name":"funder A",
        "slug":"funder-a",
        "research_projects":["RPGUID1", "RPGUID2"]
    },
    ...
}

I chose this arrangement to avoid searching the main research_projects array in linear time.
While this structure is fine for filtering alone, it is rather inefficient for other features I want.
Below is a list of functions, along with their time-complexity in the current structure. I need to restructure this data in a way that optimizes for as many of these functions as possible:

*

*get the title of a research_project given its id

*

*O(1)

*get all research_projects of a given funder

*

*O(1) lookup, linear in the size of funder[research_projects]

*get all funders of a given research_project

*

*linear in the size of funders and funders[research_projects]

*get the slug of a funder given its id

*

*O(1)

*get the id of a funder given its slug

*

*linear in the size of funders
All of these functions are required to run multiple times whenever the user selects a new filter, which is why I'm looking into alternative solutions.
Thanks


text:
Q: Export js file for users Semi-new to the backend world.
In the process of creating a small web app for my work place.
I just want to find out what the best method will be to give the end user a script that they put on their site. i.e. how google give their analytics script.
Simple answers such as which frameworks, tools etc to use is more than fine. Willing to learn! ;)
My hope is to have it published on S3 when they save their configurations.
I've been building the app with Laravel framework.
Originally I was using Wordpress, I created a function that saved a section to a  js file on the server, but it didn't feel practical.
Any help or guidance will be very appreciated.

A:
Simple answers such as which frameworks, tools etc to use is more than fine. Willing to learn! ;)

Your question is too general, there isn't a one right way or a framework/tools that does this task better/worse than others, it just depends on how you want and how you will implement it.
You also mentioned google analytics script but I don't think they offer users to download a js file with the code, all they do is show it in a textarea where the user can copy/paste the generated code. Not sure what your requirements are but why would you want to host users' js files and pay for that (you mentioned S3). If a user is able to include a <script> tag into their site - they are also able to host the .js file or include it inside html.
Anyaway, if you want the users to be able to download the JS files then there are still many was of doing this:

*

*You could use AWS S3 API and upload the generated JS code (no need to save files locally) and show the direct link to the user.

*You could store the generated JS code in a public folder locally and provide the user with direct link.

*You could create a route with unique URLs where the framework handler would generate (or pull from database) the JS code (no need to save files locally) every time. The link would look something like http://example.com/download/<user_id>/<script_id>.js your framework of choice would receive the request, associate it with the user and user's settings and generate the code. This would probably be the best way of doing this assuming that the user will rarely use the link and only to actually download the code and not to hotlink.


text:
Q: How to execute class method in a Java program? In this code, we have to add a method set() which will take two parameters, an int index, and an Integer value, which will set the array element at the specified index to the specified value and the array will grow if an attempt is made to set a value beyond the end of the array by using the method resize().
This is the code I currently have:
public class MyVector {
    protected Integer[] internalArray;
    public MyVector( int initialSize )
    {
        internalArray = new Integer[initialSize];
    }
    public void resize( int newSize )
    {
        if ( newSize != internalArray.length ) {
        Integer[] newArray = new Integer[newSize];
        for (int i=0; i < Math.min(newSize,internalArray.length); i++)
            newArray[i] = internalArray[i];
        internalArray = newArray;
        }
    }
    public Integer get( int index )
    {
        if ( index < internalArray.length )
            return internalArray[index];
        return null;
    }
    public static void main(String[] args)
    {
        MyVector vec = new MyVector(5);
        for ( int i = 0 ; i < 20 ; i++ )
            vec.set(i, i*i );
        for ( int i = 0 ; i < 20 ; i++ )
            System.out.println( "Element" + i + "=" + vec.get(i) );
    }
}

This is the current set()-method I have made. I am not quite sure how to use or execute the set() method. How should I proceed?
public int set(int a, int b){
        a = b;
        if (b>19){
            resize(b);
        }
        return a;
    }

A: Welcome to stackoverflow! I have a feeling this is a homework question, if it is - please try to do your homework on your own since it will greatly assist you in the future.
As you can see in the code you have provided there is currently no function set() for your MyVector class.
In order to make a set() function you have to declare it. This w3schools guide will most likely explain the basics for you: https://www.w3schools.com/java/java_encapsulation.asp
For your code that could be:
public void set(int index, int value) {}

Assuming you don't want a return value from the function.
Then you can just change the value of the array to what you want it to be:
public void set( int index, int value ) {
    internalArray[index] = value;
}

More information if you are interested:
What is an interesting point is that many people discuss the reasoning behind why we in OOP should need a use for setters and getters. In your example it seems like you only want your list to be of size = initialSize which you set to 5. What if someone inputs an index higher than 5? What if they input 10 instead? What will your list look like? If you want to limit those things you can in your set() function add limits to the values and indexes acceptable (which from an OOP standpoint) might be a better idea.
As I tried to explain there might be occasions where you would want to handle events when the index goes beyond. This is an example of what set() can look like if you want to increase the array size if the index is out of bounds. I really suggest you look into array and deep copying though.
public void set( int index, int value ) {
    if (index > internalArray.length - 1) {
        Integer[] newInternalArray = new Integer[internalArray.length + 1];
        for(int i = 0; i < internalArray.length; i++) {
            newInternalArray[i] = internalArray[i];
        }
        newInternalArray[newInternalArray.length-1] = value;
        internalArray = newInternalArray;
    } else {
        internalArray[index] = value;
    }
}

Or by using the resize() function:
public void set( int index, int value ) {
    if (index > internalArray.length -1) {
            resize(index + 1);
    }

    internalArray[index] = value;
}

With this solution you may consider to make the resize() private unless you want others to call it publicly. This is what can be so interesting and what I tried to tell you. By making it private and using it in the set-method you allow for setting values but you are in charge of how the values are changed.

A: Your vector class contains an internal array. There you have to modify the value at the given position. If the given position is outside of the array then you can use the resize method to enlarge the internal array:
public class MyVector {
    protected Integer[] internalArray;
    public MyVector( int initialSize )
    {
        internalArray = new Integer[initialSize];
    }
    public void resize( int newSize )
    {
        if ( newSize != internalArray.length ) {
            Integer[] newArray = new Integer[newSize];
            for (int i=0; i < Math.min(newSize, internalArray.length); i++)
                newArray[i] = internalArray[i];
            internalArray = newArray;
        }
    }
    public Integer get( int index )
    {
        if ( index < internalArray.length )
            return internalArray[index];
        return null;
    }
    public void set( int index, int value )
    {
        if (index > internalArray.length -1) {
            resize(index + 1);
        }

        internalArray[index] = value;
    }
    public static void main(String[] args)
    {
        MyVector vec = new MyVector(5);
        for ( int i = 0 ; i < 20 ; i++ )
            vec.set(i, i*i );
        for ( int i = 0 ; i < 20 ; i++ )
            System.out.println( "Element" + i + "=" + vec.get(i) );
    }
}

$ java MyVector.java
Element0=0
Element1=1
Element2=4
Element3=9
Element4=16
...
Element17=289
Element18=324
Element19=361


text:
Q: Где ошибка кода - не работает функция "loginUser" Опишу ситуацию в 4 этапа. Функция "emptyInputLogin" работает корректно. Подключение к базе тоже работает.

*

*login.php
 <?php
     include_once 'header.php';
 ?>

Log in

     <form action="includes/login.inc.php" method="POST">
         <input type="text" name="uid" placeholder="Username/email">
         <input type="password" name="pwd" placeholder="Password">
         <button type="submit" name="submit">Log In</button>
     </form>
     <?php
         if (isset($_GET["error"])) {
             if ($_GET["error"] == "emptyinput") {
                 echo "
Fill all
";
             }
             elseif ($_GET["error"] == "wronglogin") {
                 echo "
In correct log in
";
             }
         }
     ?>

 <?php
     include_once 'footer.php';
 ?>

*login.inc.php
 <?php
 if (isset($_POST["submit"])) {

     $username = $_POST["uid"];
     $pwd = $_POST["pwd"];

     include_once 'db.inc.php';
     include_once 'function.inc.php';

     if (emptyInputLogin($username, $pwd) !== false) {
         header("location: ../login.php?error=emptyinput");
         exit();
     }

     loginUser($conn, $username, $pwd);

 } else {
     header('location: ../login.php');
     exit();
 }

*function.inc.php - функция loginUser()
 function loginUser($conn, $username, $pwd) {
     $uidExists = uidExists($conn, $username, $username);

     if ($uidExists === false) {
         header("location: ../login.php?error=wronglogin");
         exit();
     }

     $pwdHashed = $uidExists["usersPwd"];
     $checkPwd = password_verify($pwd, $pwdHashed);

     if ($checkPwd === false) {
         header("location: ../login.php?error=wronglogin")
         exit();
     }
     elseif ($checkPwd === true) {
         session_start();
         $_SESSION['userid'] = $uidExists['userId'];
         $_SESSION['useruid'] = $uidExists['usersUid'];
         header("location: ../index.php");
         exit();
     }
 }

*function.inc.php - функция uidExists()
 function uidExists($conn, $username, $email) {
     $sql = "SELECT * FROM users WHERE usersUid = ? OR usersEmail = ?;";

     $stmt = mysqli_stmt_init($conn);

     if (!mysqli_stmt_prepare($stmt, $sql)) {
         header("location: ../signup.php?error=stmtfailed");
         exit();
     }

     mysqli_stmt_bind_param($stmt, "ss", $username, $email);
     // запуск запроса
     mysqli_stmt_execute($stmt);

     $resultData = mysqli_stmt_get_result($stmt);

     if ($row = mysqli_fetch_assoc($resultData)) {
         return $row;
     }
     else {
         $result = false;
         return $result;
     }

     mysqli_stmt_close($stmt);
 }


text:
Q: Facebook comments plugin via Ajax I've Facebook Comments plugin in my website and if I simple refresh the page all works normal, but...

*

*everytime i load a new page via Ajax the plugin blinks and then disapears
(using FB.XFBML.parse(), if not, nothing appears).

I could work around that by removing the .fb_hide_iframes class {left: -10000px;}
but the iframe receives a fixed height value, i.e: style="height:100px;" - so basically, the box is cut in a half and it won't be dynamic as if I reloaded the page)

*

*If I remove the .fb_hide_iframes and set a bigger height value to the Iframe, besides getting the big blank space, the "Load More Comments" of the box won't work.

Important Note: .fb_hide_iframes class doesn't appear if I simple refresh the page - all works normal
i've tried everything, but nothing worked, so i'm asking your help...
is there any other solution you guys can think of?

A: I ran into this issue and was able to solve it by including a separate javascript file with the following:

*

*A function which calls the FB.XFBML.parse() on ajax complete (which you currently seem to have in place already).

*Also include the fb js within the same file, and outside of any document.ready functions (see below).

(function($) {
    // This function is what gets called on ajax complete.
    // Note: ajax complete part is not in this example.
    $.fn.fb_comments_refresh = function(data) {
        if (typeof FB != 'undefined') {
            // Refresh comment box.
            FB.XFBML.parse();
        }
    };
})(jQuery);
// Needed for fb ajax modal to work repeatedly.
(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
    fjs.parentNode.insertBefore(js, fjs);
}(document, "script", "facebook-jssdk"));

This file needs to be called within the ajax-requested page.


text:
Q: trainig lstm keras model on a tpu on colab i get an error: Failed to serialize message i can't train a lstm keras model on tpu of google coab
it run on cpu put it is very slow
'''
    import tensorflow as tf
def create_model():
  model = tf.keras.models.Sequential()
  model.add(tf.keras.layers.Embedding(400001, 50, input_length=100,weights=[emb_matrix], trainable=False))
  model.add(tf.keras.layers.LSTM(100))
  model.add(tf.keras.layers.Dense(50, activation='relu'))
  model.add(tf.keras.layers.Dense(5, activation='softmax'))

  model.compile(
    optimizer='adam',
    loss = 'categorical_crossentropy',
    metrics=['accuracy']
  )
  return model

with tpu_strategy.scope(): # creating the model in the TPUStrategy scope means we will train the model on the TPU
  model = create_model()
model.summary()

model.fit(x=X_train_indices, y=Y_train_oh, validation_split=0.25)

'''
i get this error
---------------------------------------------------------------------------

RuntimeError                              Traceback (most recent call last)

<ipython-input-38-23871a130a73> in <module>()
----> 1 model.fit(x=X_train_indices, y=Y_train_oh, validation_split=0.25)

11 frames

/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/constant_op.py in convert_to_eager_tensor(value, ctx, dtype)
     94       dtype = dtypes.as_dtype(dtype).as_datatype_enum
     95   ctx.ensure_initialized()
---> 96   return ops.EagerTensor(value, ctx.device_name, dtype)
     97
     98

RuntimeError: Failed to serialize message

link to notebook Link


text:
Q: Serve a file for a URL I am trying to serve a file manually for a specific URL.
When I user the res.sendFile function I get the following error in my logs.
Object [object Object] has no method 'sendFile'

Express version : 4.13.3

It seems that this function is not available to use. There is a section about serving static content in the documentation but how would you serve it?
Updated code:
express = require('express');
app = express();

app.set('views', 'cloud/views');  // Specify the folder to find templates
app.set('view engine', 'ejs');    // Set the template engine
app.use(express.bodyParser());    // Middleware for reading request body
app.get('/hi', function(req, res){
  res.sendFile('index.html', function (err) {
    if (err) {
      console.log(err);
    }
    else {
      console.log('File sent!');
    }
  });
});

app.listen();

Error logs
I2015-09-22T07:08:37.766Z]v39 Ran custom endpoint with:
  Input: {"method":"GET","url":"/hi","headers":{"accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8","accept-encoding":"gzip, deflate, sdch","accept-language":"en-US,en;q=0.8,fr;q=0.6,sq;q=0.4","cache-control":"no-cache","host":"......parseapp.com","pragma":"no-cache","upgrade-insecure-requests":"1","user-agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36","version":..........."}}
  Result: Success
I2015-09-22T07:08:37.855Z]TypeError: Object [object Object] has no method 'sendFile'
    at app.js:13:7
    at callbacks (express_router.js:161:37)
    at param (express_router.js:135:11)
    at pass (express_router.js:142:5)
    at Router._dispatch (express_router.js:170:5)
    at Object.router (express_router.js:33:10)
    at next (connect_proto.js:240:15)
    at urlencoded (connect_urlencoded.js:51:37)
    at connect_bodyParser.js:64:7
    at json (connect_json.js:53:37)

A: can you compare the code with
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
app = express();

app.set('views', 'cloud/views');  // Specify the folder to find templates
app.set('view engine', 'ejs');    // Set the template engine
app.use(bodyParser.json());    // Middleware for reading request body
app.get('/hi', function(req, res){
  res.sendFile(path.join(__dirname + '/index.html'), function (err) {
    if (err) {
      console.log(err);
    }
    else {
      console.log('File sent!');
    }
  });
});

app.listen(3100);


text:
Q: Twitter like web app for MOSS 2007 Has anyone created a twitter like app in Sharepoint 2007? Would really like to know about your ideas and suggestions.

A: There are a few options for you.
Michael Gannotti has this point on how to do it simply with a content editor web part and some javascript:
http://sharepoint.microsoft.com/blogs/mikeg/Lists/Posts/Post.aspx?ID=1202
Aidan Garnish has a solution here:
http://aidangarnish.net/blog/post/2009/02/Twitter-SharePoint-web-part.aspx
There's a CodePlex project called SharePointTwitter here:
http://sharepointtwitter.codeplex.com/
And if you just want to search twitter there's a web part here:
http://www.mattjimison.com/blog/2009/03/04/twitter-search-webpart/
Hope that helps!

A: Check out this Team Status solution from Zevenseas.

A: Have a look at Yammer for SharePoint.

A: Check this
http://tweetpart.codeplex.com/


text:
Q: Spam and Placement in the Store According to Spam and Placement in the Store that comes under Google Play Developer Program Policies
Do not post an app where the primary functionality is to:

*

*Drive affiliate traffic to a website or

*Provide a webview of a website not owned or administered by you
(unless you have permission from the website owner/administrator to
do so)

I wanted to know

*

*if I can provide links in my Android App to Youtube, Google Search,
Wikipedia and Facebook Fan page that I administer?

*According to point number 2. I cannot provide a webview for Youtube,
Google Search and Wikipedia because I don't own or administer them
but can I provide a webview for my Facebook fan page that I administer?

My App has got some photos of a celebrity. According the points below, I don't own them.
Ask permission to use copyrighted work—If you want to use another party's copyrighted work in your app, you should ask for permission from the work's creator or copyright owner and include appropriate copyright attribution.
I wanted to know how can I ask for their permission and who to ask for? as they are all over the web available for free. How do I make them copy right protected.
I find these points confusing. I'd be grateful if someone can explain them to me. My App got suspended twice. I don't know how to make things right. Please help.


text:
Q: How do I format input from a text file into a defaultdict in python Text file has over 50K lines with this format
M:org.apache.mahout.common.RandomUtilsTest:testHashDouble():['(O)java.lang.Double:<init>(double)', '(M)java.lang.Double:hashCode()', '(S)org.apache.mahout.common.RandomUtils:hashDouble(double)', '(S)org.apache.mahout.common.RandomUtilsTest:assertEquals(long,long)', '(O)java.lang.Double:<init>(double)']
M:org.apache.mahout.common.RandomUtilsTest:testHashFloat():['(M)java.util.Random:nextLong()', '(M)java.util.Random:nextLong()', '(M)java.util.Random:nextLong()', '(S)org.apache.mahout.common.RandomUtilsTest:assertEquals(java.lang.String,long,long)']
M:org.apache.mahout.math.AbstractVectorTest:testAssignBinaryFunction():['(I)org.apache.mahout.math.Vector:assign(org.apache.mahout.math.Vector,org.apache.mahout.math.function.DoubleDoubleFunction)', '(O)java.lang.StringBuilder:<init>()', '(I)org.apache.mahout.math.Vector:getQuick(int)', '(S)org.apache.mahout.math.AbstractVectorTest:assertEquals(java.lang.String,double,double,double)']
M:org.apache.mahout.math.AbstractVectorTest:testAssignBinaryFunction2():['(S)org.apache.mahout.math.function.Functions:plus(double)', '(I)org.apache.mahout.math.Vector:assign(org.apache.mahout.math.function.DoubleFunction)', '(S)org.apache.mahout.math.AbstractVectorTest:assertEquals(java.lang.String,double,double,double)']

How do I read and format this data into a dictionary so that all of the methods in the [] are individual values and the string before the [ (test method) is the key? And how would I remove the '' before storing them as values in the dictionary? #python
Here is the code used to populate the text file. Now I am trying to take that txt file data and read/parse it back into another dictionary.
    d = {}
    with open("filtered.txt") as input:
        for line in input:
            (key, val) = line.strip().split(" ")
            if str(key) in d:
                d[str(key)].append(val)
            else:
                d[str(key)] = [val]

    keys = []
    for key in d:
        keys.append(key)

    keys.sort()

    input.close()

    with open('mahout-coverage.txt', 'w') as outfile:
        for key in keys:
            outfile.writelines('{}:{}'.format(key, d[key]) + "\n")

A: json module can be used to store python dictionary into a file and later load the file and still parse it to the same data type before it was written to the file.
d = {}
with open('filtered.txt') as input:
    for line in input:
        key, value = line.strip().split("():")
        key = "{}()".format(key)
        d[key] = value

print(d)

# It would be better and easy if you write the data to the file using json module
import json

with open('data.txt', 'w') as json_file:
  json.dump(d, json_file)

# Later you can read the file using the json module itself
with open('data.txt') as f:
  # this data would be a dicitonay which can be easily managed.
  data = json.load(f)

Refer: json.dump() and json.load()

A: Using ast.literal_eval you can convert string list to list
from collections import defaultdict
import ast
with open('tst.txt') as fp:
    d = defaultdict(list)
    for line in fp:
        k, v = line[: line.index('):') + 1], ast.literal_eval(line[line.index(':[') + 1:])
        d[k] += v
print(dict(d))

Output:
{
M:org.apache.mahout.common.RandomUtilsTest:testHashDoubl :  ['(O)java.lang.Double:<init>(double)', '(M)java.lang.Double:hashCode()', '(S)org.apache.mahout.common.RandomUtils:hashDouble(double)', '(S)org.apache.mahout.common.RandomUtilsTest:assertEquals(long,long)', '(O)java.lang.Double:<init>(double)']
M:org.apache.mahout.common.RandomUtilsTest:testHashFloa :  ['(M)java.util.Random:nextLong()', '(M)java.util.Random:nextLong()', '(M)java.util.Random:nextLong()', '(S)org.apache.mahout.common.RandomUtilsTest:assertEquals(java.lang.String,long,long)']
M:org.apache.mahout.math.AbstractVectorTest:testAssignBinaryFunctio :  ['(I)org.apache.mahout.math.Vector:assign(org.apache.mahout.math.Vector,org.apache.mahout.math.function.DoubleDoubleFunction)', '(O)java.lang.StringBuilder:<init>()', '(I)org.apache.mahout.math.Vector:getQuick(int)', '(S)org.apache.mahout.math.AbstractVectorTest:assertEquals(java.lang.String,double,double,double)']
M:org.apache.mahout.math.AbstractVectorTest:testAssignBinaryFunction :  ['(S)org.apache.mahout.math.function.Functions:plus(double)', '(I)org.apache.mahout.math.Vector:assign(org.apache.mahout.math.function.DoubleFunction)', '(S)org.apache.mahout.math.AbstractVectorTest:assertEquals(java.lang.String,double,double,double)']
}


text:
Q: $\lim_{x \to \infty} {{(x!)^p}\over {x^x}}$ After some experimentation, I am pretty sure that $$\lim_{x \to \infty} {{(x!)^p}\over {x^x}} \to \infty $$ for $p \gt 1$, and that
$$\lim_{x \to \infty} {{(x!)^p}\over {x^x}} \to 0 $$ for $p \le 1$.
I do not, however, have any proof of this, and I was wondering if someone could help me.  I have tried applying the ratio test, but I am not quite sure how.  Thanks in advance for the help!

A: The Stirling approximation states $x!\sim\sqrt{2\pi}x^{x+1/2}e^{-x}$. Thus $$\lim_{x\to\infty}\frac{x!^p}{x^x}=(2\pi)^{p/2}\exp\lim_{x\to\infty}\left[\left((p-1)x+\frac{p}{2}\right)\ln x-px\right].$$If $p>1$, this is $\exp\infty=\infty$ due to the $x\ln x$ term. If $p<1$, the same logic obtains a limit of $\exp-\infty=0$. If $p=1$, we get $$\sqrt{2\pi}\exp\lim_{x\to\infty}(\tfrac12\ln x-x)=\exp-\infty=0$$ because $\ln x\in o(x)$.

A: Solution via Ratio Test:
The ratio between two successive terms is: $${{(n!)^p}\over{n^n}}\over{{((n+1)!)^p}\over{(n+1)^{n+1}}}$$
Simplifying gives:
$$\left({{n!}\over{(n+1)!}}\right)^p \cdot {{(n+1)^{n+1}}\over {n^n}}$$
Further simplification yields:
$${1\over (n+1)^p} \cdot \left({{n+1}\over {n}}\right)^n\cdot (n+1)$$
With some rearrangement we have:
$${1\over (n+1)^{p-1}} \cdot \left({{n+1}\over {n}}\right)^n$$
The second term goes off to $e$ as $n$ goes to infinity.  The first goes to $0$ when $p$ is larger than $1$, $1$ when $p$ is equal to $1$, and $+\infty$ when $p$ is less than $1$.  In the first case, the ratio between successive terms is $0$.  In the second case, it is $e$, and in the third case it is unbounded.  By the ratio test, it must convege in the first case and diverge in the other two.


text:
Q: Create a details page from API in Wordperss I'm creating a project in Wordpress, and are using api to get information into the site.
I have created a JavaScript file to fetch the api information.
This api has images in each result. What I want to do, is to click on one image that directs me to a (created) detail page that has more information about that specific result (This is a page I want to create myself).
I am relative new to Wordpress, so I hope I have done it right so far.
Here is my code in JS
const siteID = window.gamerRevData.siteID; // gamerRevData from functions.php

for(let i=2; i < 7; i++) {

    let gameUrls = fetch("https://api.rawg.io/api/games?page=" + i).then(res => res.json());

    const retrieveAll = async function() {
        let results = await Promise.all([gameUrls]);
        let gameResults = results[0].results;

        for(let j=0; j < gameResults.length; j++) {

            console.log(gameResults[j]);

            const gamePlatforms = gameResults[j].platforms;
            const gameName = gameResults[j].name;
            const gameSlug = gameResults[j].slug;
            const gameImg = gameResults[j].background_image;
            const gameRating = gameResults[j].rating;
            const gameRelease = gameResults[j].released;
            const gameID = gameResults[j].id;

            function htmlOutput () {

                gameList.innerHTML += `
                '

${gameName}

${gameRating}

${gameRelease}

                `
            }

           for(let k=0; k < gamePlatforms.length; k++) {
                let platformID = gamePlatforms[k].platform.id;

                // Playstation 5
                if(platformID == 187 && siteID == "5") {
                    htmlOutput();
                }

                // Playstation 4
                if(platformID == 18 && siteID == "8") {
                    htmlOutput();
                }

                // Xbox S/X
                if(platformID == 186 && siteID == "10") {
                    htmlOutput();
                }

                // Xbox One
                if(platformID == 1 && siteID == "12") {
                    htmlOutput();
                }

                // Nintendo Switch
                if(platformID == 7 && siteID == "14") {
                    htmlOutput();
                }

                // PC
                if(platformID == 4 && siteID == "16") {
                    htmlOutput();
                }
            } // end loop
        } // end loop
    }(); // end async function
} // end loop

and the page.php
<?php
    get_header();

    while(have_posts()) {
        the_post(); ?>

<?php the_title(); ?>

Lorem ipsum dolor sit amet consectetur adipisicing elit.
        Sapiente necessitatibus minima blanditiis dicta harum dolore quisquam,
        voluptatem ducimus expedita corporis voluptas at autem fuga repellat perspiciatis!
         Dolore eum nulla corrupti?

    <?php }

    get_footer();

?>

and functions.php
<?php

function gamerRevolutionFiles () {
    wp_enqueue_script("gamer_revolution_script", get_theme_file_uri("/js/script.js"), NULL, 1.0, true); // JavaScript
    wp_enqueue_style("bootstrap", "//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"); // Bootstrap
    wp_enqueue_style("gamer_revolution_styles", get_stylesheet_uri()); // CSS
    wp_localize_script("gamer_revolution_script", "gamerRevData", array(
        "siteID" => get_the_ID()
    ));
}

add_action("wp_enqueue_scripts", "gamerRevolutionFiles");

function gamerRevolutionTitle() {
    add_theme_support("title-tag");
}

add_action("after_setup_theme", "gamerRevolutionTitle");

Not sure if there is anything more you need. Thanks in advance.


text:
Q: Removing non-matching items from datasets I have two datasets consisting of lists of nested lists such that each item in the list looks like list1[i]= [a, x, y b] and list2[j] = [c, x, y, d] and where the length of the two lists does not necessarily match. I'd like to be able to go through the lists, preserve their order, and eliminate any of the sub-lists that do not contain matching x values. In the end, I want to get two lists of identical length and where for each index, the x value is the same in corresponding sub lists.
Right now I have a somewhat messy code that assumes that the set of x values in list2 is a subset of those in list1 (true at the moment) and then proceeds to remove items where the x values don't match.
    len_diff = len(list1) - len(list2)
    if len_diff > 0:
        removed = []
        for (counter, row) in enumerate(list2):
            while list1[counter][1] != list2[counter][1]:
                removed.append(list1.pop(counter))
        new_len_diff = len(list1) - len(list2)
        if new_len_diff < 0:
            raise IndexError('Data sets do not completely overlap')
        else:
            for i in range(new_len_diff):
                removed.append(temp_data.pop())

So basically I'm removing any items that don't x values match until they start matching again and then removing the end of list1 beyond the x values in list2 (raising an exception if I've cut too much out of list1).
Is there a better way to do this?
I don't necessarily need to relax the assumption that all x values in list2 are in list1 at the moment but it would make this code more useful to me in the future for other data manipulations. The biggest hole in my code now is that if there is a gap in my list1 data, I'll remove my entire list.

A: You should try this:
list1 = list2 = [x for x in list1 if x[1] in zip(*list2)[1]]

EDIT
Based on the comments below, the OP adapted this answer to do what was wanted by doing
list1 = [x for x in list1 if x[1] in zip(*list2)[1]]
list2 = [x for x in list2 if x[1] in zip(*list1)[1]]


text:
Q: set image width quals to window width on resize (without jQuery) I need some help :).
I have a wrapper-container with, let say 60% width on desktop devices (on mobile 100% width). Then I have different images on this page, they all have same width as wrapper.
Now on window resize and wanna set the width of those images equal to the window width and place this images horizontally in the middle of the page.
I know I have to deal with window resize, window width and then move images with CSS transform to the left. But how?
The image must then have inline-style with all these parameters.
Dummy:

window.addEventListener('resize', function(){
        var img = document.getElementsByClassName("fullwidth");
        var windowWidth = window.innerWidth;
    }, true);
.wrapper {
  padding: 1em;
}

.fullwidth {
  max-width: 100%;
  height: auto;
}

@media (min-width: 800px) {
  body {
    background: #555;
    color: #fff;
  }

  .wrapper {
    max-width: 60%;
    margin: 0 auto;
  }
}

  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

Thanks
BTW: I need this kind of layout for Wordpress theme, since I didn't found any solution for WP to set images to full width, wich are placed in a post, while there is an wrapper-container.

A: Here is a solution using plain js. You could improve it by using jQuery or ES6. For the fullscreen image, I set the width to calc(100vw - 2em) which corresponds to the full size of the viewport width minus the padding set on the wrapper.
The handleResize() method does the following: get the wrapper width and subtract the window width. Divide that by two and you should obtain a negative offset which is then applied to the image's marginLeft style attribute. This pushes the image to the left edge of the window and the css calc() above handles the expansion.
Hope this helps.

var images = document.getElementsByClassName("fullwidth");
var wrapper = document.getElementById("wrapper");

handleResize = function() {
  var displacement = (wrapper.offsetWidth - window.innerWidth) / 2;
  for (i = 0; i < images.length; i++) {
    images[i].style.marginLeft = displacement + "px";
  }
}

window.addEventListener('resize', function() {
  handleResize();
}, true);

handleResize();
html,
body {
  margin: 0px;
  padding: 0px;
}

#wrapper {
  padding: 1em;
}

.fullwidth {
  width: calc(100vw - 2em);
  height: auto;
}

@media (min-width: 800px) {
  body {
    background: #555;
    color: #fff;
  }
  #wrapper {
    max-width: 60%;
    margin: 0 auto;
  }
}

    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
    sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
    Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
    sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
    Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.


text:
Q: La carpeta de VENV no aparece Desinstalé virtualenv y al instalarlo de nuevo con sudo apt-get install python-virtualenv virtualenv se instala normalmente, pero la carpeta de env no aparece en ninguna parte.
Luego intenté instalarlo con pip install virtualenv y me dice que no tengo permisos, así que procedí a hacerlo con sudo sudo pip install virtualenv pero ahí me arrojó el siguiente problema sudo: pip: orden no encontrada

A: prueba con:
sudo pip3 install virtualenv


text:
Q: Bugzilla installation issue in Solaris 10 I encountered the following error when installing Bugzilla in Solaris 10.
Can anyone advise on how to resolve the issues? I am installing on a Solaris 10 x86 machine.
# /usr/bin/perl install-module.pl Digest::SHA
/usr/ucb/cc: language optional software package not installed
*** Error code 1
make: Fatal error: Command failed for target 'SHA.o'

# /usr/bin/perl install-module.pl DateTime
Error: no compiler detected to compile 'lib/DateTime.c'. Aborting

A: This might work:
export CC
CC=gcc
PATH=$PATH:/usr/sfw/bin
/usr/bin/perl install-module.pl Digest::SHA


text:
Q: Razor Pages - Can't pass different model to partial view within a page handler I'm not quite sure if this is possible to do but wanted to check. I have a razor page that has a few different handler methods. In some of them, I return a partial view result.
Example:
public class BoardMeetingsModel : PageModel
{
      //ctor
      //properties

      public IActionResult OnGetFetchCreateMeetingPartial()
          {
             return Partial("_CreateMeetingPartial", new ManipulationDto());
          }
}

My partial view is setup as below:
@using Models.ManipulationModels
@model ManipulationDto

It's a partial page so I am not using the @page directive (partial page is named _CreateMeetingPartial.cshtml. When I pass in the ManipulationModel though, I run into below error
The model item passed into the ViewDataDictionary is of type 'Models.ManipulationDto', but this ViewDataDictionary instance requires a model item of type 'Pages.BoardMeetingsModel'.

I am not calling the partial with my razor page. I am directly returning a partial page because I am consuming the returned data in a javascript modal. Is it even possible to override this behavior? By default it always expects the base PageModel (i.e. BoardMeetingsModel) to be passed in.
I'm surprised that even though I am explicitly passing in a model that exists, the partial view is still expecting a pagemodel instead of the model I explicitly stated for the partial view.

A: This appears to be bug in newly introduced Partial() in ASP.NET Core 2.2 where model parameter seems to be completely redundant, because "this" is the only thing it will accept.
If you however use PartialViewResult() it will work. Should be simpler and more readable than the accepted solution.
Just swap this
return Partial("_CreateMeetingPartial", new ManipulationDto());

with this
return new PartialViewResult
{
    ViewName = "_CreateMeetingPartial",
    ViewData = new ViewDataDictionary<ManipulationDto>(ViewData, new ManipulationDto())
};

A: To resolve above issue, I had to do below. Note that I do not have [BindProperty] attribute on my ManipulationDto property because I have multiple models on my page. If you have multiple models and you have validation (e.g. required properties), all of them will trigger in razor pages which is different from MVC. The way to handle it in my case was to pass the model directly as a parameter but also making sure to have a public property which I can assign all the values in case model state validation fails.
If you do not have multiple unique models, each with their own validation, you can just apply the bindproperty attribute and not worry.
public class BoardMeetingsModel : PageModel
{
      //this gets initialized to a new empty object in the constructor (i.e. MeetingToManipulate = new ManipulationDto();)
      public ManipulationDto MeetingToManipulate { get; set; }

      //ctor
      //properties

      public IActionResult OnGetFetchCreateMeetingPartial(ManipulationDto meetingToManipulate)
          {
             //send the page model as the object as razor pages expects
             //the page model as the object value for partial result
             return Partial("_CreateMeetingPartial", this);
          }

      public async Task<IActionResult> OnPostCreateMeetingAsync(CancellationToken cancellationToken, ManipulationDto MeetingToCreate)
        {
            if (!ModelState.IsValid)
            {
                //set the pagemodel property to be the values submitted by the user
                //not doing this will cause all model state errors to be lost
                this.MeetingToManipulate = MeetingToCreate;
                return Partial("_CreateMeetingPartial", this);
            }
            //else continue
         }
}


text:
Q: How to apply AddEventListener to created element? I need your help I working on an application and I'm a beginner in JS
I want to apply addEventListener on a created element
const i = document.querySelector(".fas");
li.innerHTML = `<i class="fas fa-times"></i>`;
i.addEventListener("click", removeTask);

function removeTask(e) {
    e.preventDefault();
    li.style.textDecoration = "line-through";
}

It's not working can anybody help me, please.
Thanks in advance

A: You used li when you should have used i. I'm not sure if your variable li is defined somewhere else, but that might be causing the problem. Otherwise, everything looks fine.

A: Try using this:
const fas = document.getElementByClassName("fas");
li.innerHTML = `<i class="fas fa-times"></i>`;
i.addEventListener("click", function(){ removeTask(e));
function removeTask(e) {
e.preventDefault();
li.style.textDecoration = "line-through";
}

A: I think you want to click on the times icon and apply line through to your li element.
In your case as in mine, i element as an innerHTML of another element this means it exists !
Here is a simple example below

document.querySelector("div").innerHTML = ""

document.querySelector("i").addEventListener("click", ()=>{
  console.log("Hello Stackoverflow")
  //your code here for callback
})
i{
  cursor: pointer;
  }
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>

  Hello world


text:
Q: iOS 10 Simulator LayerKit connection failed After moving to latest mac OS Sierra and Xcode 8, LayerKit(version 0.22.0) stop working on simulator. Always return error:
Error Domain=com.layer.LayerKit.Security Code=-34018 "Generation of key pair failed with result code -34018." UserInfo={NSLocalizedDescription=Generation of key pair failed with result code -34018., parameters={
    atag = <63657274 732d7472 75737465 642e6c79 72382e6e 65743a43 46363431 3046342d 42383546 2d313145 342d4134 42452d34 37424235 46303235 444534>;
    bsiz = 1024;
    pdmn = ck;
    perm = 1;
    type = 42;
}}
Does anyone have the same problem?

A: Enable "Keychain Sharing" fix this issue. Look this thread https://forums.developer.apple.com/thread/60617


text:
Q: *.csv Increase the file size Looking for help with this issue.
I have an excel file of size 5.7 MB, when I save the file as csv it will increase to 14.3 MB! When I click on the created csv file and save it again as csv, the size will be reduced to 1KB!
My question, is there a way to save my Excel file directly to csv and strip out all formatting so that it will be save as 1KB csv file?
Thanks in advance.

A: I had same problem, my original file size was about 250KB, after some processing in Excel, it increased to about 5.5 MB and then when I save as CSV, it went to 184MB. Then I have discovered that I was somehow saving all >milloin rows in the Excel sheet and that was making file size enormous. When I  select only the data rows/columns and copy/paste into another sheet, then the file size became 115KB.

A: A CSV file will often be larger than the XLSX it was created from. This is because in XLSX is a actually a compressed (zipped) file - you can unzip it with a standard compression tool and check it out for yourself.
You will see smaller XLSX files if there is a lot of repeat data. XLSX actually pulls out every text value, stores it in a lookup table, and then replaces it with a smaller reference number to the lookup table. This means that it only has to use up space once per text string (a little more than "once" because of the references, but still much less space).
A CSV file will list every occurrence in full which takes up much more space. I've seen files balloon to 10x the size after saving to CSV. The only time you should expect a savings with a CSV is if there is a lot of formatting and not too much reused text. Then the CSV strips out the formatting and the final product is smaller.
In reference to your 1KB file, that's a placeholder temporary file while the OS loads data to the final version. After the save is complete, it will be the same size as the other CSV. Either that, or the file is corrupt.

A: Doing File > Save As and choosing .csv as the file type will always save it with all formatting stripped out.
Saving it as a 1KB file doesn't make sense. You may just be seeing the size of the file placeholder when it is first created and before windows explorer has refreshed to show the full filesize after it is fully saved.
When you open the 1KB file, does it actually contain all of your data? What does the properties of the file say when you right click on the file in windows explorer?

A: If the Excel file is an XLS file, than the CSV file should be significantly smaller than the Excel file, but I doubt that so small as 1KB. It should be around 1-2MB.
If the Excel file is an XLSX file, than the CSV file should be a little smaller than the Excel file.
The numbers assumes that the Excel files does not contain images and the data in cells is dominant.
The size of the CSV also depends by the encoding of the file. Check also the encoding for the two CSV files that you have.
Later edit:
If you don't want to export the last rows, you can try to export only a range of cells. You have 2 options:
1. Export a range using VBA
2. Create a new sheet, create formulas that points to the first sheet, export this new sheet as CSV.


text:
Q: Failed to install-write all apks samsung GT-I9500 defaultConfig {
        android.defaultConfig.vectorDrawables.useSupportLibrary = true
        applicationId "com.orbizpro.lboard"
        minSdkVersion 17
        targetSdkVersion 29
        versionCode 4
        versionName "1.20190904"
        renderscriptTargetApi 22
        renderscriptSupportModeEnabled true
        multiDexEnabled true
        //
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        signingConfig signingConfigs.release
    }

12/23 12:29:36: Launching 'app' on samsung GT-I9500. Installation did
  not succeed. The application could not be installed. Installation
  failed due to: 'Failed to install-write all apks' Retry


text:
Q: Cloning git repo Today I cloned a Git repo successfully (I hope), however I can not see any source files in the cloned directory. To be specific I cloned the msm-kernel repo from Google with the command:
git clone https://android.googlesource.com/kernel/msm.git kernel_msm

A: The master branch of this repo is empty. You need to check out the proper branch:
$ git branch -a
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/android-msm-2.6.35
  remotes/origin/master
$ git checkout android-msm-2.6.35
Checking out files: 100% (33866/33866), done.
Branch android-msm-2.6.35 set up to track remote branch android-msm-2.6.35 from origin.
Switched to a new branch 'android-msm-2.6.35'
$ ls
COPYING     MAINTAINERS arch        firmware    ipc     net     sound
CREDITS     Makefile    block       fs      kernel      samples     tools
Documentation   README      crypto      include     lib     scripts     usr
Kbuild      REPORTING-BUGS  drivers     init        mm      security    virt
$

A: Apparently, master has no files. You have to checkout a branch:
git checkout --track -b android-msm-2.6.35 origin/android-msm-2.6.35


text:
Q: Uninitialized local variable in C I am learning C and found a similar question on a website.http://www.careercup.com/question?id=5707884834848768
I tried to understand it by writing my own program
int main()
{
   int i;
   printf("%d\n", i);
   int *ptr = &i;
   int**ptr2= &(ptr);
   return 0;
}

When the two pointer assignments are commented out, the output of this program is a random garbage value each time it is executed.
If I uncomment the first pointer assignment, the output is always a fixed value (134513705).
If I uncomment the second pointer assignment, the output is always 0.
I tried to understand it by using size command for a.out

          text data bss dec

          1141 252 8 1405

          1157 256 8 1421

          1157 256 8 1421

So, even though data values are same in 2nd and 3rd cases, the output is different.
  Why is the output having different values in the three cases?

A: As you can tell from the comments the expected output of this program is undefined.  The reason for this is that the variable i was never initialized.  Commenting out or adding back the pointer declarations is a bit of a red herring.  Your printf statement renders the memory that 'i' is using in whatever state it is found.  Running this on ideone.com outputs 0 regardless of what lines I comment in or out.  Likely this is because they clear the memory before code execution.  You could probably even change the output with different compiler options.  The takeaway is that an uninitialized variable is a view on uninitialized memory and doesn't have a defined value.


text:
Q: Is there an additional resistance given by a specific "protection" than a general one? If I add Protection 4 to an armour piece,will it reduce the same amount of damage as an armour piece with a "specific" protection such as Fire Protection?

A: no, I'm pretty sure that fire resistance protects against only fire, but protects more. protection 4 (which, I must add, I admire you for getting) protects against almost everything but protects less.


text:
Q: Добавить область для виджета внутрь поста Каким образом в WP можно добавить область для виджета прямо внутрь текста поста? Например, чтобы область всё время была после второго абзаца в статье.
Вставка виджета шорткодом не подходит, нужна именно область.
Есть идея сделать отдельный php файл с кодом области и подключать его после нужного абзаца но как это правильно написать я не представляю

A: Для этих целей существует хук-фильтр контента. Ниже приведён полный код небольшого плагина, который создаёт свой виджет, и выводит его на определённых страницах после втрого абзаца.
Код можно скопировать в файл some-name.php и поместить в папку /wp-content/plugins/, затем активировать плагин. Вместо кастомного виджета можно использовать любой системный.
Результат работы можно посмотреть на странице http://test.kagg.eu/so572791/.
<?php
/**
 * Widget in the post
 *
 * Plugin Name: Widget in Post
 * Plugin URI: https://wordpress.org/plugins/widget-in-post/
 * Description: Shows widget as the second paragraph in the post.
 * Author: KAGG Design
 * Author URI: https://profiles.wordpress.org/kagg.eu/
 * Requires at least: 5.0
 * Tested up to: 5.4
 * Version: 1.0.0
 * Stable tag: 1.0.0
 *
 * Text Domain: widget-in-post
 * Domain Path: /languages/
 *
 * @package widget-in-post
 * @author  KAGG Design
 */

/**
 * Class WIP_Widget
 */
class WIP_Widget extends WP_Widget {

    /**
     * WIP_Widget constructor.
     */
    public function __construct() {
        parent::__construct(
            'wip_widget',
            'WIP Widget Title',
            [ 'description' => 'WIP Widget description' ]
        );
    }

    /**
     * Frontend.
     *
     * @param array $args     Arguments.
     * @param array $instance Instance.
     */
    public function widget( $args, $instance ) {
        $title = isset( $instance['title'] ) ? $instance['title'] : __( 'Default Widget Title', 'wip-widget' );
        $title = apply_filters( 'widget_title', $title );

        echo wp_kses_post( $args['before_widget'] );
        if ( ! empty( $title ) ) {
            echo wp_kses_post( $args['before_title'] . $title . $args['after_title'] );
        }
        echo wp_kses_post( 'Some text to add via WIP Widget' );
        echo wp_kses_post( $args['after_widget'] );
    }

    /**
     * Backend.
     *
     * @param array $instance Instance.
     */
    public function form( $instance ) {
        $title = isset( $instance['title'] ) ? $instance['title'] : __( 'Default Widget Title', 'wip-widget' );

        ?>

            <label for="<?php echo esc_html( $this->get_field_id( 'title' ) ); ?>">
                <?php echo esc_html__( 'Title:', 'wip-widget' ); ?>

            <input
                    class="widefat" id="<?php echo esc_html( $this->get_field_id( 'title' ) ); ?>"
                    name="<?php echo esc_html( $this->get_field_name( 'title' ) ); ?>" type="text"
                    value="<?php echo esc_attr( $title ); ?>">

        <?php
    }

    /**
     * Save widget settings.
     *
     * @param array $new_instance New settings.
     * @param array $old_instance Old settings.
     *
     * @return array
     * @see WP_Widget::update()
     */
    public function update( $new_instance, $old_instance ) {
        $instance          = [];
        $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? wp_strip_all_tags( $new_instance['title'] ) : '';

        return $instance;
    }
}

/**
 * The content filter.
 *
 * @param string $content Post content.
 *
 * @return string
 */
function wip_the_content_filter( $content ) {
    global $post;

    $insert_after  = 2; // Paragraph number to insert widget after.
    $allowed_pages = [ 'so572791', 'some-other-page-slug' ]; // Pages to work.

    if ( ! isset( $post ) || ! in_array( $post->post_name, $allowed_pages, true ) ) {
        return $content;
    }

    ob_start();
    the_widget( 'WIP_Widget' );
    $addon = ob_get_clean();

    $content_arr = explode( '
', $content );
    array_splice( $content_arr, $insert_after, 0, $addon );

    return implode( '
', $content_arr );
}

add_filter( 'the_content', 'wip_the_content_filter' );

/**
 * Register widget.
 */
function register_wip_widget() {
    register_widget( 'WIP_Widget' );
}

add_action( 'widgets_init', 'register_wip_widget' );


text:
Q: Powershell: IIS Site names into an array I'm looking to populate an array with the site names from IIS. My plan was to use this array/loop through it, to then set the Anonymous Authentication for each site, to Application pool identity, by settings the username to blank.
Set-Webconfigurationproperty –filter /system.webServer/security/authentication/anonymousAuthentication  "IIS:\Sites\[array]" –name username –value ""
Bit stuck on how to get the names into an arry though.  Any smart way of getting the name field from gci iis:\sites maybe?
Thanks in advance.


text:
Q: AngularJS - Multiple binding - calculating input values I'm building a large form with AngularJS which will replace a huge excel spreadsheet with a lot of formulas and functions. In short, this form is a calculator - where a lot of values are depending on previous values. My current approach is to add ng-change on all inputs that affect next ones - also adding watchers to those fields that change programmatically. I find this way of doing very confusing and hard to maintain. Any better patterns of doing that kind of work?
The complete form I'm building consists of 60+ fields that interact with each other. All calculated values, like "price" in example are subject to manual change or override. So the calculation of "total price" in example below should be automatic whether price is calculated via previous values or manually changed.
Small example:

Calculator

    <form>

Width (cm): <input type="text" ng-change="changePrice()" ng-model="width"/>

Height (cm): <input type="text" ng-change="changePrice()" ng-model="height"/>

Depth (cm)<input type="text" ng-change="changePrice()" ng-model="depth"/>

Price per cm3<input type="text" ng-change="changePrice()" ng-model="priceCm"/>

Price<input type="text" ng-model="price"/>

Packaging price<input type="text" ng-change="changeTotalPrice()" ng-model="packagePrice"/>

Total price<input type="text" ng-model="total"/>

    </form>

JS:
function TestCtrl($scope) {
   $scope.$watch('price', function(newValue,oldValue){
    if(newValue != oldValue)
    {
        $scope.changeTotalPrice();
    }
});

$scope.changePrice = function(){
    var width = 0;
    var height = 0;
    var depth = 0;
    var priceCm = 0;

    width = $scope.width;
    height = $scope.height;
    depth = $scope.depth;
    priceCm = $scope.priceCm;

    if(width > 0 && height > 0 && depth > 0 && priceCm > 0)
    {
        $scope.price = width * height * depth * priceCm;
    }
}

$scope.changeTotalPrice = function(){
    var price = 0;
    var packaging = 0;

    price = $scope.price;
    packaging = $scope.packagePrice;

    if(price > 0 && packaging > 0)
    {
        $scope.total = price*1 + packaging*1;
    }
  }
}

Sample: http://jsfiddle.net/rewnao6p/3/

A: Yes this is a better way to do this: since your total depends on the rest of the value, compute the total dynamically
function TestCtrl($scope) {

 $scope.price = function(){
    var width = $scope.width;
    var height = $scope.height;
    var depth = $scope.depth;
    var priceCm = $scope.priceCm;

    if(width > 0 && height > 0 && depth > 0 && priceCm > 0)
    {
        return width * height * depth * priceCm;
    }
}

 $scope.totalPrice = function(){
    var price = $scope.price();
    var packaging = $scope.packagePrice;

    if(price > 0 && packaging > 0)
    {
        return price*1 + packaging*1;
    }
 }

}

See the fiddle: http://jsfiddle.net/g7p7ho6z/


text:
Q: Why does this output 5? My understanding is x++ == 0 runs first. But x is still -1 at the point of calculating (y = y++ / x) == 0? Otherwise it will be dividing by zero. I thought the output will be -5 but eclipse says 5. I'm going crazy.
public static void main(String[] args){

    int x = -1;
    int y = 5;
    boolean s = (x++ == 0) && ((y = y++ / x) == 0);
    System.out.println(x + y);
}

A: ((y = y++ / x) == 0) is never evaluated since && is a short circuited logical AND operator, and (x++ == 0) is false, so s is evaluated to false without evaluating the second operand.
Hence, the output is
x + y

0 + 5 == 5

Note that if you change the && operator to &, which is not short circuited, the second operand will be evaluated, which will lead to division by 0 and ArithmeticException. x is incremented when the first operand is evaluated, so once the second operand is evaluated, x is already 0.


text:
Q: What permissions do I need in order to check out a page? I'm redesigning a page for my team's Sharepoint site. However, I am not able to check out the page for some reason. I have Full Control permissions for the site and thought that would be enough, but that does not seem to be true. What permissions should I request so that I can check out the page and check it back in when I am done with my changes?

A: From the URL, you can find the page library to which this page belongs.
Eg:
If the page url is http://sp/sites/team/SitePages/test.aspx, the page is exits in the site pages library.
if the page url is http://sp/sites/team/Pages/test.aspx, the page is exists in the pages library.
Remove test.aspx from the url, it will navigate to the library to which this page belongs.
Then you can go to library settings->versioning settings->choose yes for "Require documents to be checked out before they can be edited":

A: Are you sure that versioning is enabled on that pages library?
As far as I recall the Contribute permissions level should be sufficient


text:
Q: Implied property of type Object in C# - is it possible? I'm trying to convert the following function from VB to C#:
Private Function CheckHeader(ByVal Request As Object, ByRef Response As Object) As Boolean
  CheckHeader = True
  If Request.Header Is Nothing Then
     CheckHeader = False
     Throw New System.ArgumentException("Header Object not found")
  End If
End Function

And here is what I have so far in C#:
private bool CheckHeader(object Request, ref object Response)
  {
     bool functionReturnValue = false;
     functionReturnValue = true;

     var localRequest = Request;

     if (localRequest.Header == null)
     {
        functionReturnValue = false;
        throw new System.ArgumentException("Header Object not found");
     }
     return functionReturnValue;
  }

The problem is with the Request parameter that is of type Object.  In VB, we have the nice feature of the implied property, which of course C# doesn't like one bit. Any object that does get passed as the "Request" parameter is supposed to have the Header parameter.  I'm just checking to see if it's there. I'm thinking the use of generics might apply here, but I'm unsure of the route to take.  Any ideas?

A: only way I can think for you to do the same thing in c# is to use the dynamic keyword
it should behave like the strict off of vb.net
    private bool CheckHeader(dynamic Request, ref object Response)
    {
        bool functionReturnValue = false;
        functionReturnValue = true; //you should put true above instead

        var localRequest = Request; //not sure why this but whatever

        if (localRequest.Header == null)
        {
            functionReturnValue = false; //no need for this here, because of the throw
            throw new System.ArgumentException("Header Object not found");
        }
        return functionReturnValue; //at this point remove
                                    //this variable and simply return true
    }

so this should be ok
    private bool CheckHeader(dynamic Request, ref object Response)
    {
        //Response variable should stay there since it might be a
        //breaking change, you should check if you can remove it

        if (Request.Header == null)
        {
            throw new System.ArgumentException("Header Object not found");
        }
        return true;
    }

A: Because object has no Header property, if possible I would convert Request Object into a c# interface.  So I would change the code to look like this:
First IRequest interface:
public interface IRequest
{
    //Assuming Header is an object.
    MyHeaderObject Header {get;set;}
}

Now CheckHeader function:
private bool CheckHeader(IRequest Request, ref object Response)
{
    bool functionReturnValue = false;
    functionReturnValue = true;

    var localRequest = Request;

    if (localRequest.Header == null)
    {
       functionReturnValue = false;
       throw new System.ArgumentException("Header Object not found");
    }
    return functionReturnValue;
}

Now everything that passes a Request to CheckHeader needs to implement IRequest.
Here is an example of it:
public MyRequest : IRequest
{
   public MyHeaderObject Header {get;set;}
}


text:
Q: Mirror SVN Repository [Write-through proxying] I have a codebase located in Europe and access this codebase from Asia. Codebase is substantially huge, downloading the whole codebase (which is required sometimes) becomes a pain.
I wanted to know whether anything like this.
I want a solution that "I will have a svn server locally which will sync with the main svn and serve my team as the svn is locally hosted."
Thanks in advance
Munim

A: Here is a pretty good article on how to set this up:
http://wordaligned.org/articles/how-to-mirror-a-subversion-repository
The general idea is to use svnadmin hotcopy to do the copy without down time, perhaps triggered by a post-commit hook, or on a timer.
Another option, discussed here:
http://blogs.collab.net/subversion/2007/08/mirroring-repos/
Is to use SVN sync to do a sync, rather than a copy, using the svnsync synchronize command.

A: You can also try a write-through-proxy which is supported since SVN 1.5 and works fine.
With this setup you have a master and a slave repository.
The slave repo acts as a local read cache while commits will be proxied to your master server and synced back.
This solution comes with subversion / apache.
See this svndevelopers blog  for more details. Or the superb SVN book, or last but not least the subtrain admin training presentations

A: Besides the svnsync, you can try the commercial solution from Wandisco.

A: Try Multisite Repository Replication with VisualSVN Server. That's exactly what you were looking for then.
Multisite Repository Replication enables classic master/slave replication architecture which allows you to setup a master repository at your main codebase location in Europe with multiple slaves at other locations.
In contrast to standard write-through proxy solution, in Multisite Repository Replication feature

*

*master and slave repository looks and acts just like a regular writeable Subversion repository,

*the replication between master ans slaves is performed automatically and transparently,

*supports advanced authentication mechanisms,

*It's easy to setup, works out-of-the-box with minimal configuration via VisualSVN Server Manager MMC console.
Learn more at http://www.visualsvn.com/support/topic/00068/


text:
Q: How do I stream an audio .pls from a url gained from a json response in android? I am making a Radio like app in Android that uses streaming, here I need to stream the audio from a link
http://sc-ccountry.1.fm:7806/listen.pls
in background. This link I got from JSON response. I am able to play MP3 type of audio in MediaPlayer but ".pls" can not be played.
What is the issue with that? How do I overcome that?

A: A .pls file is a file format used by SHOUTcast and Icecast, for stream media, according to Wikipedia. It's definitely not supported by Android media players natively. But it looks awfully easy to parse yourself. The file format is a basic .ini file, which is trivial to write a parser for. You'll have to figure out yourself what the various tags are.
You should probably request the HTTP headers of any file you're going to pass off to a media player, before you do so, just to make sure that the content type of the stream is reasonable. If you're scraping content from web radio stations, you'll see a lot of content wrapper formats in addition to .pls files (e.g. M3U files are pretty common too).
You can use the HTTP HEADER verb instead of the GET verb to see what the headers are without also getting the content. Or maybe they're kind enough to give you the MIME type in the JSON.