text:
Q: How does social and sharing websites e.g. Facebook and Google+ handle security policies in code? I have heard that most websites use ad-hoc security.
How is security policy specified and enforced in code?
E.g., only bob's friends may see his email address.
If the policy Intertwined throughout the code, how do they manage it as it is error prone.
I have started developing a Information Flow Control package for web applications, just curious on what big companies use?

A: Note: this question is best suited for the Security Stack Exchange site.
Generally speaking, software development companies - not just websites - develop their own authorization logic ad-hoc using code (Java, C#... you name it).
There are a few companies / teams that have decoupled their business logic from their authorization logic. Doing so is called externalizing authorization. The field related to that is called externalized authorization.
There are several benefits to externalizing authorization:

*

*decouple business logic from authorization logic

*easier to maintain either codebase separately

*easier to audit

*centralized logic

*...

There are several ways to achieve externalized authorization. Here are some examples:

*

*Spring Security (Java) gives you a way to express authorization logic using roles and annotations

*Claims-based authorization in .Net

*CanCan and CanCanCan in Ruby

*Flask in Python

All these approaches are specific to one given language. Some e.g. CanCan are policy-based. Others use a role-based approach.
Ideally, all companies and websites would use a technology-neutral approach based on policies. There is in fact a standard around such a 'thing'. It is called ABAC (attribute-based access control) and it uses policies written in XACML to express the access control logic.
The cool thing is that you could principally reuse these policies across Facebook, Yahoo, etc...


text:
Q: keep C# datetime local time between json and Web api? I have problem when I have datatime  in json object it will convert it to UTC time zone in C# dateTime just want to ask how to keep local time?can I set time zone  property in web.config file or geter or setter because I have to may object have day and time?
this is class example ?
public class Patient
{
    public long RecordId { get; set; }
    public string Username { get; set; }
    public DateTime Date
      {
          get;
          set;
      }
    public bool Deleted { get; set; }
    public string ModifiedBy { get; set; }
    public DateTime ModifiedOn { get; set; }
    public string CreatedBy { get; set; }
    public DateTime CreatedOn { get; set; }
}

update I tried to use getter and setter to fix I have this exception {Cannot evaluate expression because the current thread is in a stack overflow state.}
[System.Web.Http.Route("api/postpatientform")]
public HttpResponseMessage PostPatientForm(PatientViewModel form)
{
    using (var db = new AthenaContext())
    {
        try
        {
            var form2 = Mapper.Map<Patient>(form);
            db.Patient.Add(form2);
            db.SaveChanges();

            var newId = form2.RecordId;
            foreach (var activity in form.PatientActivities)
            {
                activity.PatientId = newId;

                db.NonPatientActivities.Add(Mapper.Map<PatientActivity>(activity));
            }
            db.SaveChanges();

        }
        catch (DbEntityValidationException e)
        {
            foreach (var eve in e.EntityValidationErrors)
            {
                Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                    eve.Entry.Entity.GetType().Name, eve.Entry.State);
                foreach (var ve in eve.ValidationErrors)
                {
                    Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                        ve.PropertyName, ve.ErrorMessage);
                }
            }
            throw;
        }
    }

    return Request.CreateResponse<Patient>(HttpStatusCode.Created, null);
}

A: You can configure this. See: http://www.newtonsoft.com/json/help/html/SerializeDateTimeZoneHandling.htm
Here's an example:
public void Config(IAppBuilder app)
{
    var config = new HttpConfiguration();

    var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
    jsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;

    app.UseWebApi(config);
}

A: You can change your serializer settings to use the JSON.net serializer :
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings =
    new JsonSerializerSettings
    {
        DateFormatHandling = DateFormatHandling.IsoDateFormat,
        DateTimeZoneHandling = DateTimeZoneHandling.Unspecified,
    };

There is also various date format you can choose from : DateTimeZoneHandling
/// <summary>
/// Specifies how to treat the time value when converting between string and <see cref="DateTime"/>.
/// </summary>
public enum DateTimeZoneHandling
{
    /// <summary>
    /// Treat as local time. If the <see cref="DateTime"/> object represents a Coordinated Universal Time (UTC), it is converted to the local time.
    /// </summary>
    Local = 0,

    /// <summary>
    /// Treat as a UTC. If the <see cref="DateTime"/> object represents a local time, it is converted to a UTC.
    /// </summary>
    Utc = 1,

    /// <summary>
    /// Treat as a local time if a <see cref="DateTime"/> is being converted to a string.
    /// If a string is being converted to <see cref="DateTime"/>, convert to a local time if a time zone is specified.
    /// </summary>
    Unspecified = 2,

    /// <summary>
    /// Time zone information should be preserved when converting.
    /// </summary>
    RoundtripKind = 3
}

A: You can use TimeZoneInfo.ConvertTime to convert to the wanted timezone.
Checkout this method:
https://msdn.microsoft.com/en-us/library/bb382770(v=vs.110).aspx

redpajama_set_name: RedPajamaStackExchange


text:
Q: ClickListener added to view of MotionLayout prevents layout from responding to events I have ImageViews in a MotionLayout to animate moving the ImageView across the screen. I want to also add a ClickListener to the ImageView so that there can be functionality when the ImageView is simply clicked/tapped instead of moved.
I followed the advice here to write a custom MotionLayout which only handles ACTION_MOVE but after adding the ClickListener to the ImageView in onCreate() only the ClickListener code would run and the MotionLayout would not respond. I've also tried overriding onTouchEvent() in a custom ImageView but that hasn't worked.
Inside Custom MotionLayout
       <FrameLayout
            android:id="@+id/bottomCard"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TapImageView
                android:id="@+id/bottom"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="fitXY" />
        </FrameLayout>

        <FrameLayout
            android:id="@+id/topCard"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TapImageView
                android:id="@+id/top"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="fitXY" />
        </FrameLayout>

Inside Custom ImageView
override fun onTouchEvent(event: MotionEvent?): Boolean {
        when (event?.action) {
            MotionEvent.ACTION_UP -> {
                super.onTouchEvent(event)
                Toast.makeText(context, "Works", Toast.LENGTH_LONG)
                    .show()
                return false
            }

        }
        return super.onTouchEvent(event)
    }

I've also tried in activity onCreate()
  binding.topCard.setOnClickListener {
            Toast.makeText(applicationContext, "Works", Toast.LENGTH_LONG)
                .show()
        }

Thanks for your attention!

A: obviously, when MotionEvent is draging, it shouldn't allow children view to consume the event, so. i intercept the motionevent as underlying code . it works.
 private var touchDownX = 0f
private var touchDownY = 0f
private var mScrolling = false
private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop

override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
    when (event.action) {
        MotionEvent.ACTION_DOWN -> {
            touchDownX = event.x
            touchDownY = event.y
            mScrolling = false
        }
        MotionEvent.ACTION_MOVE -> mScrolling = abs(touchDownY - event.y) >= touchSlop
        MotionEvent.ACTION_UP -> mScrolling = false
    }
    return if (mScrolling) true else super.onInterceptTouchEvent(event)
}

A: If you have your own Click listener you need to launch the transition from it.
If the button is doing more than just animation. You will probably want to make some decisions on the animation.
Remove the <OnClick .../> from the motionScene  and add
motionLayout.transitionToState(R.id.mystate);  to your click handler


text:
Q: hyper-v machines are crashing with the message "An address incompatible with the requested protocol was used." Formerly working Hyper-v machines are crashing at start with the message  "An address incompatible with the requested protocol was used."
While ubuntu deskop machines are crashing immediately is the DockerDesktopVm running but docker desktop gets an timeout.
Creating a new machine or reinstall the hyper-v feature in windows doesn't help.
Disabling or Enabling Enhanced Session Mode in the hyper-v settings has no effect.

Update 1: a windows machine created with "quick create" is running.
Update 2: after upgrading to windows 10 2004 everything works again.


text:
Q: JS - Add a new property and value on one of the objects I have a list of objects
const array = [
    {club: "Club A", number: 12},
    {club: "Club B", number: 12}
]

I want to add a new property in one of the objects
member: ["a", "b"]

It would be
const newArray = [
    {club: "Club A", number: 12, member: ["a", "b"]},
    {club: "Club B", number: 12}
]

Tried with map
const newArray = array.map(obj => check if obj.club ==="Club A" )

A: You could just assign the new property.
With a classic assignment:

const
    array = [{ club: "Club A", number: 12 }, { club: "Club B", number: 12 }],
    member = ["a", "b"];

array.find(({ club }) => club === "Club A").member = member;

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Or take Object.assign

const
    array = [{ club: "Club A", number: 12 }, { club: "Club B", number: 12 }],
    member = ["a", "b"];

Object.assign(array.find(({ club }) => club === "Club A"), { member });

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: You can use map and object destrcturing

const array = [{club: "Club A", number: 12},{club: "Club B", number: 12}]
let member = ["a", "b"]

const newArray = array.map(obj => obj.club === "Club A" ? {...obj,member} : obj)

console.log(newArray)

A: You could use Object.assign in map

const array = [
    {club: "Club A", number: 12},
    {club: "Club B", number: 12}
]

const member = {member: ["a", "b"]};

const newArray = array.map(obj => obj.club === 'Club A' ? Object.assign(obj, member) : obj);
console.log(newArray);

A: You can use find() to get the item you want to edit. Then just assign the property to it:

const array = [
    {club: "Club A", number: 12},
    {club: "Club B", number: 12}
]

// find the correct item
let item = array.find(item => item.club == "Club A")
item.member =  ["a", "b"]

console.log(array)


text:
Q: How to set select options on client side with database values from server How can I pass a javascript variable to compare and set with PHP? I have tried the following code:
      $.each(jsonData, function( index, value ) {
             var functId=value.functId;

             html +="
  <select  id='FunctionName' ><?php foreach($conn-
            >query( 'select resid as id ,resdesc as value  from FUNCTNAMES')-
            >fetchAll(PDO::FETCH_OBJ) as $row){

    //how can i pass functId to compare and set in following option code ???

             $sel = ($row->id== functId)? "selected='selected'":"";

            echo '<option value='.$row->id.' '.$sel.'>' . $row->value .
            '</option>';}
           ?> </select>
";
          })

A: You are mixing client and server code on the client side. The browser (client) cannot evaluate the <?php ... ?> section. Instead, you should use jQuery.ajax() to get the database values from the server. Having said that, you have to be careful not to run these ajax calls one-by-one in a loop here. Better to execute only one ajax call to get all values at once.


text:
Q: Exception deserializing the package error when executing SSIS package I've just installed Visual studio Professional 2015 on a Microsoft 2019 Server with the following tools:

*

*VS update 3

*Sql Server Data Tools

*BI Developer Extensions for Visual Studio 2015

*Apex tools

*ZappySys SSIS tools

When I go to run an SSIS package that works on other machines I get the following error message:
TITLE: Microsoft Visual Studio
------------------------------

Exception deserializing the package "The type initializer for 'Microsoft.SqlServer.Dts.Runtime.XMLSerializationHelper' threw an exception.".

------------------------------
ADDITIONAL INFORMATION:

The type initializer for 'Microsoft.SqlServer.Dts.Runtime.XMLSerializationHelper' threw an exception. (Microsoft.SqlServer.ManagedDTS)

------------------------------

Could not load file or assembly 'Microsoft.SqlServer.Diagnostics.STrace, Version=14.100.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified. (Microsoft.SqlServer.ManagedDTS)

------------------------------

Could not load file or assembly 'Microsoft.SqlServer.Diagnostics.STrace, Version=14.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.

I've repaired SQL Server Data tools and Visual studio itself with no luck. Any suggestions?

A: I had created a new SSIS project and facing same problem while executing it.
Generally this type of issue occurred when you have not selected the right SQL Server Version.
You have to first check the SQL Server version installed in your or remote machine and verify it with the SSIS Project. You have choose the same SQL Server version in Visual studio for your SSIS project.

 SSIS Project>>Right Click (properties)>>Configuration Properties>>General>>Target Server Version

After setting this if still you are facing the same issue then please check the below settings.

 SSIS Project>>Right Click (properties)>>Common Properties>>project>>Security>>Select the appropriate protection level.

Solution-1

Solution-2


text:
Q: Is it possible to control the embedded video player within youtube.com? While browsing a youtube.com page is it possible to control the video player through javascript on that page? E.g. get the embed element and send it a "pause" message.
Could it be possible to use the Youtube JS API?
I have managed to do something similar by browsing the video as HTML 5 (using the &html5=1 query parameter), then getting the video element and calling play() or pause(). However not all youtube videos will show in HTML 5, some load as SWF even when requesting HTML 5.
Any ideas?
Edit:
Okay so given var player is the embed object, the functions such as player.playVideo() work, however I cannot seem to get events to work. E.g. player.addEventListener('onStateChange', myFunc) never calls myFunc. In fact the SWF object seems to swallow all events including 'click'.
Is there any way I can listen for when a user manually plays or pauses, without polling player.getPlayerState()?

A: The answer is just in the link you posted to the JS API. More precisely, here.
Excerpt:

Playing a video
player.playVideo():Void
Plays the currently cued/loaded video. The final player state after this function executes will be playing (1).


text:
Q: UIActivityViewController for Facebook not Showing Default Text I am using a UIActivityViewController which provides some default text and a link.  With all social mediums (sms, email, twitter) the default text and URL are shown.  However, with FB while the URL image is shown, the default text is not showing (it is just blank).  Below is the code:
    NSString *shareStr = [NSString stringWithFormat:@""some text"];
    NSURL *website = [NSURL URLWithString:@"website"];
    NSArray *shareAray = @[shareStr,website];

    [self viewWillDisappear:YES];

    UIActivityViewController *activityController = [[UIActivityViewController alloc]initWithActivityItems:shareAray
                                                                                applicationActivities:nil];

    if([activityController respondsToSelector:@selector(popoverPresentationController)] )
        activityController.popoverPresentationController.barButtonItem = self.shareButton;

    [self presentViewController:activityController
                       animated:YES completion:nil];

    [activityController setCompletionHandler:^(NSString *activityType, BOOL completed){
        if (!activityType || UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
        {
            [self viewWillAppear:YES];
        }
    }];

Update:
As noted in what others said below, FB no longer allows pre-fill.  Here is another link to a video that gives examples of what is allowed and what isn't:  https://developers.facebook.com/docs/apps/review/prefill

A: It would seem Facebook no longer wants developers to pre-fill posts with text. From https://developers.facebook.com/docs/sharing/ios#ios-integration:

Use of the iOS share sheet is subject to Facebook Platform Policy, including section 2.3 which states that apps may not pre-fill. In the context of the share sheet, this means apps may not pre-fill the share sheet's initialText field with content that wasn't entered by people earlier in their use of the app.

Seems they would prefer devs to use the SDK:

While you can use the iOS native view controller API (share sheet) directly, there are several reasons to use the native iOS Share dialog provided by the Facebook SDK. Using the native Share dialog provides a quick way to test that people have signed into Facebook on their iOS 6+ devices. This API also uses the same style block as other parts of the Facebook SDK.

A: I have done one trick to share text and image from UIActivityViewController in iOS. First I need to find if user have clicked on facebook icon from UIActivityView and then open the share dialog of facebook with text and image. This is the only way to share for both text and image. Below is my code. I hope this can save time for the developers. Since Facebook have changed there policies and its really hard to share pre fill text.
Please add UIActivityItemSource in .h file as Delegate
This will be called when user click on share button to show UIActivityViewController.
NSString *textObject = [NSString stringWithFormat:@"%@, %@",shareString,timeDuration];
NSMutableArray *activityItems = [NSMutableArray arrayWithObjects:self, textObject, shareImage, nil];
activityController = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
[self presentViewController:activityController animated:YES completion:nil];

And When user click on facebook icon from it.
pragma mark - UIActivityItemSource Protocol
- (id)activityViewController:(UIActivityViewController )activityViewController itemForActivityType:(NSString )activityType {

    if ([activityType isEqualToString:UIActivityTypePostToFacebook]) {

        [self dismissViewControllerAnimated:activityController completion:nil];
        [self performSelector:@selector(postToFacebook) withObject:self afterDelay:1.0];}
    return nil;
}

-(void)postToFacebook {

    [FBSDKSettings setAppID:@""];
    NSArray *imagesListingArray = [[item objectForKey:@"imgs"] valueForKey:@"img"];
    NSString * shareImage = [imagesListingArray objectAtIndex:0];

    FBSDKShareLinkContent *content = [[FBSDKShareLinkContent alloc] init];
    content.contentTitle = @"F-Spot";
    content.contentDescription = [NSString stringWithFormat:@"%@  %@", [item valueForKey:@"event_name"],[item valueForKey:@"duration"]];
    content.imageURL = [NSURL URLWithString:shareImage];

    FBSDKShareDialog *shareDialog = [[FBSDKShareDialog alloc] init];
    shareDialog.mode = FBSDKShareDialogModeNative;
    if(shareDialog.canShow) {
        shareDialog.mode = FBSDKShareDialogModeFeedBrowser;
    }
    shareDialog.shareContent = content;
    shareDialog.delegate = self;
    [shareDialog show];

}

A: I've found it happens when you have the Facebook app installed. By removing the Facebook app the UIActivityViewController shows the pre-filled text correctly and the image preview is also different. It shows the site url at the bottom of the image.

A: Based on @Kashifs solution. Here is a version in Swift 4.2, Xcode 10 and FacebookSDK 4.4.
  import FBSDKShareKit

extension YourViewController: UIActivityItemSource{

    //MARK: - ActionSheet

    func showShareSheet(){
        let shareStr = "Text you want to share"
        let activItems =  [self,shareStr, #imageLiteral(resourceName: "YourImageName")] as [Any]
        let shareSheet = UIActivityViewController(activityItems: activItems, applicationActivities: nil)
        self.shareSheet = shareSheet
        self.present(shareSheet, animated: true, completion: nil)
    }

    //MARK: - FacebookPost

    func postToFacebook() {
        let quote = "Text you want to share"
        if let URL = URL(string: "https://yourURL"){
            let content : LinkShareContent = LinkShareContent(url: URL, quote: quote)
            let dialog = ShareDialog(content: content)
            dialog.mode = .shareSheet
            dialog.presentingViewController = self
            do{
                try dialog.show()
            }catch{
                print("\(error)")
            }
        }
    }

    //MARK: - UIActivityItemSource Protocol

    func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any?{
        if activityType == UIActivity.ActivityType.postToFacebook{
            self.shareSheet?.dismiss(animated: true, completion: {
                self.postToFacebook()
            })
        }
        return nil
    }

    func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
        return ""
    }

}//endReferral/Invite-Share

A: This extension fix the problem, check it out! https://github.com/alexruperez/ARFacebookShareKitActivity
Launch FBSDKShareKit from UIActivityViewController instead of the default Facebook share sheet.

A: I tricked UIActivityViewController to use the text by adding a preview image to the share array.


text:
Q: How do I add a column(average_user_rating) to the dataframe that gives me the average rating for the userId in that row? Python dataframes:
I got a dataframe with UserId, MovieId and rating (length 81116).

I also have a series that has the average rating of each UserId (length 610).

average rating series view
How do I add a column, average_user_rating, to the dataframe that gives me the average rating for the userId in that row?

A: Supposing the series is in UserId's crescent order, you can do it using pandas with something like:
df["average_user_rating"] = df["UserId"].apply(lambda x: s[x-1])

You can test:
s = pd.Series([10,20])
df = pd.DataFrame([[1,5],[1,15],[2,10],[2,30]], columns = ["UserId", "Rating"])
print (s)
print (df)
df["average_user_rating"] = df["UserId"].apply(lambda x: s[x-1])
print(df)

A: You can use merge.
It works like a SQL JOIN
A possible code would be:
df = pd.merge(left=movies_df, right=users_df, how='left',
              left_on='userId', right_index=True)


text:
Q: How to ask phonegap plugin permission on exact run time and not on app start? I am building an app with phonegap build. My app has some plugins as i list below. When i run the app, at start it asks for "record audio" and "modify or delete SD card contents. read the contents of your SD card".
How can I prevent asking this permissions at start and make it ask on exact run time?
`<plugin name="cordova-plugin-camera" spec="2.4.1" />`
`<plugin name="cordova-plugin-compat" spec="1.2.0" />`
`<plugin name="cordova-plugin-whitelist" spec="1.3.3" />`
`<plugin name="cordova-plugin-file" spec="4.3.1" />`
`<plugin name="cordova-plugin-file-transfer" spec="1.6.1" />`
`<plugin name="cordova-plugin-media-capture" spec="1.4.3" />`
`<plugin name="cordova-plugin-statusbar" spec="2.4.3" />`
`<plugin name="cordova-plugin-globalization" spec="1.11.0"/>`
`<plugin name="cordova-plugin-splashscreen" spec="5.0.3"/>`
`<plugin name="cordova-plugin-android-permissions" spec="1.0.0" />`
`<preference name="permissions" value="none" />`
`<preference name="orientation" value="portrait" />`
`<preference name="AutoHideSplashScreen" value="true"/>`
`<preference name="SplashScreenDelay" value="1300" />`
`<preference name="ShowSplashScreenSpinner" value="false" />`
`<preference name="fullscreen" value="false" />`
`<preference name="SplashMaintainAspectRatio" value="true" />`
`<preference name="SplashScreenBackgroundColor" value="#34495e" />`
`<preference name="SplashScreen" value="screen" />`
`<preference name="FadeSplashScreen" value="true"/>`

A: I found my own answer. Phonegap build app asks permissions at start but when you upload it to google play, the app downloaded from play store asks permissions on runtime.


text:
Q: JavaScript - Insert PHP multidimensional array into Javascript class in Google Charts I'm using this Google Charts tutorial on how to convert an array into a graph.
The data in the tutorial is already in the function. Now I want to insert my own data into the function from a PHP array. I managed to convert my PHP array into a JavaScript array. Below is my code:
$jsArray = array();
foreach($movingAverages as $movingAverage) {
   $jsArray[] = array((int) $movingAverage['unix'], (int) $movingAverage['closing-prices']);
}

Below is my sample code:
Array
(
    [0] => Array
        (
            [0] => 1505040240
            [1] => 3452
        )

    [1] => Array
        (
            [0] => 1505040300
            [1] => 3451
        )

    [2] => Array
        (
            [0] => 1505040360
            [1] => 3446
        )

    [3] => Array
        (
            [0] => 1505040420
            [1] => 3449
        )

This is my current Javascript Code:

When I call alert(js_array); The array is called.
I don't know why the chart is not being displayed. I'm not sure how to insert the js_array into my function drawChart().
This is the first time I'm using JavaScript. So thank you for your help.

A: You're likely adding one more dimension to the array.
var data = google.visualization.arrayToDataTable([
    ['Time', 'Closing Prices'],
    js_array
]);

UPDATE:
js_array.unshift(['Time', 'Closing Prices']);
var data = google.visualization.arrayToDataTable(js_array);


text:
Q: scipy.optimize.curve_fit unable to fit shifted skewed gaussian curve I am trying to fit a skewed and shifted Gaussian curve using scipy's curve_fit function, but I find that under certain conditions the fitting is quite poor, often giving me close to or exactly a straight line.
The code below is derived from the curve_fit documentation. The code provided is an arbitrary set of data for test purposes but displays the issue quite well.
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import math as math
import scipy.special as sp

#def func(x, a, b, c):
#    return a*np.exp(-b*x) + c

def func(x, sigmag, mu, alpha, c,a):
    #normal distribution
    normpdf = (1/(sigmag*np.sqrt(2*math.pi)))*np.exp(-(np.power((x-mu),2)/(2*np.power(sigmag,2))))
    normcdf = (0.5*(1+sp.erf((alpha*((x-mu)/sigmag))/(np.sqrt(2)))))
    return 2*a*normpdf*normcdf + c

x = np.linspace(0,100,100)
y = func(x, 10,30, 0,0,1)
yn = y + 0.001*np.random.normal(size=len(x))

popt, pcov = curve_fit(func, x, yn,) #p0=(9,35,0,9,1))

y_fit= func(x,popt[0],popt[1],popt[2],popt[3],popt[4])

plt.plot(x,yn)
plt.plot(x,y_fit)

The issue seems to pop up when I shift the gaussian too far from zero (using mu). I have tried giving initial values, even those identical to my original function, but it does not solve the problem. For a value of mu=10, curve_fit works perfectly, but if I use mu>=30 it not longer fits the data.

A: You can call curve_fit many times with random initial guess, and choose the parameters with minimum error.
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import math as math
import scipy.special as sp

def func(x, sigmag, mu, alpha, c,a):
    #normal distribution
    normpdf = (1/(sigmag*np.sqrt(2*math.pi)))*np.exp(-(np.power((x-mu),2)/(2*np.power(sigmag,2))))
    normcdf = (0.5*(1+sp.erf((alpha*((x-mu)/sigmag))/(np.sqrt(2)))))
    return 2*a*normpdf*normcdf + c

x = np.linspace(0,100,100)
y = func(x, 10,30, 0,0,1)
yn = y + 0.001*np.random.normal(size=len(x))

results = []
for i in xrange(50):
    p = np.random.randn(5)*10
    try:
        popt, pcov = curve_fit(func, x, yn, p)
    except:
        pass
    err = np.sum(np.abs(func(x, *popt) - yn))
    results.append((err, popt))
    if err < 0.1:
        break

err, popt = min(results, key=lambda x:x[0])
y_fit= func(x, *popt)

plt.plot(x,yn)
plt.plot(x,y_fit)
print len(results)

A: Giving starting points for minimization often works wonders. Try giving the minimizer some information on the position of the maximum and the width of the curve:
popt, pcov = curve_fit(func, x, yn, p0=(1./np.std(yn), np.argmax(yn) ,0,0,1))

Changing this single line in your code with sigma=10 and mu=50 produces


text:
Q: wcs1800 current sensor (with sensitivity of 66mV/A) output voltage varies unexpectedly with a range of 10 - 20mA I am using wcs1800 sensor to read current in the range of 100mA to 30A, even though the sensor has a sensitivity of ~66mV/A (5V input) and ~50mV/A (3.3v input) the output voltage is varied in the range of 10mA - 20mA which makes the sensor unusable to read the current in the range of 100mA. I have tried the recommended capacitor values for output from the datasheet. Can someone help me with a solution to this problem?
Thanks.

A: You are expecting too much dynamic range from a crude Hall sensor like that. Thermal drift alone is 1mV/K which means 7 degrees C change will change the output equivalent to a 100mA current, so the variation you are seeing is equivalent to only a degree C or two.
Maybe you can use another sensor that covers a lower range (either more sensitive or wind more turns through the core). It will saturate at higher currents.

A: I have solved this somewhat by taking a very large amount of samples (500) separated by 10ms, and calculating the mean value. Variation in my readings is thereby limited to 0.05 A  (ca. 3mV from the WCS1800), which is usable for me.
Temperature drift is indeed around 1mV per Kelvin/Celsius, with the output increasing (suggesting more current is measured) as temperature drops.


text:
Q: Book about a boy who discovered he had superhuman abilities, and ran away from an organization that wanted to use him as a weapon I'm looking for a book I think I read maybe in 2018. I don't remember much, but I remember reading it in middle school, so I believe it would be in the more advanced part of a children's section of the library.
It goes like this: this boy ran away after discovering he had super human abilities, and was being controlled like a machine. The whole FBI/organization was after him, because he was like a weapon for the military or something. But I think he ended up being taken by said organization, and was in training by the military to be the country's weapon.
Along the way, he finds out his parents created him for the sole purpose of experimenting on him. He's like half-cyborg, I guess, because he had this machine inside him that controlled him. One ally he met was a tea house owner who let him stay in the upstairs of the store, it was like a old apartment.
If it helps, the cover was black, except for the outline of a door opening, which was colored in red, and the boy was running through it (the door). I think it was also part of a series of books. Anything helps, so if you know what book I'm talking about, please tell me!  Thanks so much!
Edit: I believe it was published early 2010s. The book cover was all black, there was a outline of an open door, it was colored red and the main character is running through it. This book may be hard to find, I remember searching about it when I first read it and the author wasn't super well known. He didn't write many books and I believe this book was one of his last. It's surprising how much I know but just can't remember it's name

A: The Twelve-Fingered Boy (2013) by John Hornor Jacobs, the first book in the The Twelve-Fingered Boy trilogy...?

Fifteen-year-old fast-talking Shreve doesn't mind juvie. He's good at dealing contraband candy, and three meals a day is more than his drunk mother provided. In juvie, the rules never change and everyone is the same. In juvie, Shreve has life figured out.
So when he's assigned a strangely silent and vulnerable new cellmate, Jack, Shreve takes the younger boy under his wing. But all Shreve's plans and schemes unravel when he discovers Jack is different. For one thing, Jack has six fingers per hand. For another thing, he just might have superpowers.
Soon Jack has drawn the attention of the cellblock bullies as well as the mysterious and chilling Mr. Quincrux—who claims to be from the Department of Health and Human Services. But when Shreve feels Quincrux invade his mind and shuffle through his darkest memories, he knows Quincrux's interest in Jack is far more sinister. Mr. Quincrux means to take Jack away. For what purposes, no one knows.
But Shreve has another plan: escape.


text:
Q: Play YouTube video in UIWebView in landscape orientation while ViewController is in Portrait Orientation I am developing an iPhone application that needs to play a YouTube video.
I have a ViewController in Portrait Orientation only with a UIWebView that loads a YouTube Video.
What I am trying to do is that the video can be played in landscape orientation.
This sounds pretty simple but I can't figure out how to do that. Could someone please help me out?
Thanks!

A: This goes in the AppDelegate. Will enable horizontal mode for video players only
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {

    if let presentedViewController = window?.rootViewController?.presentedViewController {

        let className = String(describing: type(of: presentedViewController))
        if ["MPInlineVideoFullscreenViewController", "MPMoviePlayerViewController", "AVFullScreenViewController"].contains(className)
        {
            return UIInterfaceOrientationMask.allButUpsideDown
        }

    }
    return UIInterfaceOrientationMask.portrait
}

A: There is currently no way to start playing a YouTube video programmatically.
That said, you can make a UIWebview in the ViewController's willRotateToInterfaceOrientation:duration: checking for the horizontal orientation and display the webview with the code that shows the video's thumbnail. But the user will still have to activate the view.
To remove the video you do it in the same method, but for the portrait orientation and remove the webview.

A: I found the answer.
1) I add this code to my viewController.m
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

2) In interface builder I build my interface in Landscape, with every single element rotated by 90°.
When I build and Run, the view seems to be in portrait mode when it is in fact landscape. Therefore, the YouTube Video embedded in the UIWebView plays in Landscape.


text:
Q: Django rest + React front Currently, I am working with a group to try to create a website with a functional Django backend and a React frontend. We are using a user view set
class UserViewset(viewsets.GenericViewSet, mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin):
    permissions_classes = (permissions.AllowAny,)
    serializer_class = UserSerializer
    queryset = User.objects.all()

This is where I am stuck, I haven't used viewsets or serializers before and I am at an impasse on where to go from here. I was hoping to get some clarification of how to add in a create/register user plus login and logout functions so that we can start messing with our api. Any help would be appreciated.

A: For Login you can use the following code in urls.py-:
    from rest_framework.authtoken.views import obtain_auth_token

    urlpatterns=[
    //your urls
    path("api/login/",obtain_auth_token,name="auth_user_login"),]//<-- include this line
                ]

You can use this endpoint to authenticate using token authentication.
For this you need to do some modification in settings.py file
INSTALLED_APPS=[
//Your existing apps
'rest_framework.authtoken'
]

REST_FRAMEWORK={"DEFAULT_AUTHENTICATION_CLASSES":(
                "rest_framework.authentication.TokenAuthentication",
                "rest_framework.authentication.SessionAuthentication"

            ),
}

In react you can send post request to this endpoint with username and password for login. This will send back authentication token which will be used in next requests that needs authentication.


text:
Q: React isomorphic component with both client-side and server-side rendering I want to create a react app with both client side and server side rendering.
Here is the example:
import styles from './Main.css';

import React, {Component} from 'react';
import Info from './Info/Info';
import Record from './Record/Record'

export default class Main extends Component {
    render() {
        return (

                        <Info info_num="2012201972"/>

                            <Record />

        )
    }
}

In this component Main, it needs to be rendered at the client side except <Record />
Component Record
import styles from './Record.css';
import layout from '../../shared/styles/layout.css'

import React, {Component} from 'react';

export default class Record extends Component {
    render() {
        return (

                    This is Record!

        )
    }
}

Here is my question:
I have searched some examples of server-side rendering examples with ReactDom.renderToString and react-router. However, there is no tutorial with both client-side and server-side rendering.
What I want to achieve is that, client first loads and renders Component  and then loads <Record /> from server-side.
Another question is that, how to load the style module Record.css with renderToString, because I think in this renderToString can just load the html things not the css.

A: When people refer to server-side rendering they are usually referring to the initial rendering of the top-level application at a certain route, not individual components.
I'm having trouble understanding your use case is for what you request. Your React application is one big tree of Fragments, so rendering a single component server-side does not really make sense. If you want Record to be a part of React then the client will need to know about it, so why not just render it on the client side as per usual?
If you really need to render it server side then I guess you could build the Record component so that it does an AJAX request and then the html returned could be rendered using https://facebook.github.io/react/tips/dangerously-set-inner-html.html, but I wouldn't recommend it.
My guess is that Record requires some kind of data from the server side and that is why you want to render it there? Instead just fetch that data as JSON and use that to render the component client side.

Having read your comments, I know what you are trying to do. What you want is to dynamically load content (not rendered html) from the server in response to some event (scrolldown, button click or whatever). React is very good at this. By changing the state (i.e. what Records there are) of your application, React will take care of rerendering efficiently.
This is a very simple application. It starts by having 2 items (foo and bar) that should be rendered. In response to an action (button click in this case) more data is loaded into the state and thus rendered to the page. All you need to do is modify this so that instead of the setTimeout you do an AJAX call to your backend to get the actual data.
Live version here: https://codepen.io/dpwrussell/pen/qadrko
class Application extends React.Component {

  constructor(props) {
    super(props);

    // Start with 2 records
    this.state = {
      records: [
        {
          name: 'foo',
          description: 'Some foo'
        },
        {
          name: 'bar',
          description: 'Some bar'
        }
      ]
    };

    // Bind handlers
    this.loadMoreRecords = this.loadMoreRecords.bind(this);
  }

  // Method to call which gets more records on demand
  // Here I just use setTimeout and some static data, but in your case
  // this would be AJAX to get the data from your server where the callback
  // would do the setState. I use a 2 second delay to exaggerate a delay getting
  // the data from the server.
  loadMoreRecords() {
    setTimeout(() => {
      this.setState({
        records: this.state.records.concat([
          {
            name: 'hello',
            description: 'Some newly loaded hello'
          },
          {
            name: 'world',
            description: 'Some newly loaded world'
          }
        ])
      })
    }, 2000);
  }

  // Method to render whatever records are currently in the state
  renderRecords() {
    const { records } = this.state;
    return records.map(record => {
      return (

{ `${record.name} - ${record.description}` }

      );
    })
  }

  // React's render method
  render() {
    return (

List of Records Page

          { this.renderRecords() }

        <input type='button' onClick={this.loadMoreRecords} value='Load more Records' />

    );
  }
}

/*
 * Render the above component into the div#app
 */
ReactDOM.render(<Application />, document.getElementById('app'));

A: Using css-modules-require-hook. It's similar to babel-register but for .css file. Basically, it transforms your require('Record.css') to a javascript Object base on your hook config. So your hook config should be same as your webpack css-loader config.
Put it in the entry file of your server.
const hook = require('css-modules-require-hook');

hook({/* config */});


text:
Q: should the same machine key be used in development and production environments? Our production servers all have the same machine key. However, our production and development systems do not have identical machine keys.  We get heaps (about one per second) of exceptions of the form
System.Security.Cryptography.CryptographicException: Padding is invalid and cannot be removed.
at System.Security.Cryptography.RijndaelManagedTransform.DecryptData()
at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock()
at System.Security.Cryptography.CryptoStream.FlushFinalBlock()
at System.Web.Configuration.MachineKeySection.EncryptOrDecryptData()
at System.Web.UI.Page.DecryptStringWithIV()...

We deploy the code after a build, .cs source is not present on production. aspx files are present on production.
(Should I have posted in Stack Overflow?  It's not a coding question.)
From experimentation, we've found using the dev machine key value causes the exceptions to go away. Does anyone have documentation that I can use with the security team on the need for identical keys at compile and deployment time?

A: The answer is no.
The reason for not using same machine keys is that developers should not see production environment secret keys.
If you have an ex-workers or external consultants, you can't guarantee that they won't spread the development code to somewhere. In wrong hands, the keys make it easy to attack to the servers.
Here is a nice link.


text:
Q: Issue with my own routes in ruby I created a method on my controller (admin/highlights_controller) like this:
def process
    @checkIfExists =  Highlight.where(year: params[:year], highlight_category:params[:highlight_category])

    if @checkIfExists.count > 0
      redirect_to admin_highlight_path(@checkIfExists.first)
    else
      redirect_to new_admin_highlight_path(year: params[:year], highlight_category:params[:highlight_category])
    end
end

And in my routes I created:
get '/admin/highlight', to: 'admin/highlights#process', as: 'highlights_process'

In another View I want to link to this method I created, im doing this:
<%= link_to year.year, highlights_process(year: year.id, highlight_category: highlight_category.id) %>

But I get this error:
undefined method `highlights_process' for #<#<Class:0x007faee6309bb0>:0x007faee7813d30>

What Im doing wrong? When I do a rake routes I get that route was created correctly.
   highlights_process GET    /admin/highlight(.:format) admin/highlights#process


text:
Q: SQLAlchemy / MySQL Deadlocks on serialized access I have a big problem with a deadlock in an InnoDB table used with sqlalchemy.

sqlalchemy.exc.InternalError: (mysql.connector.errors.InternalError) 1213 (40001): Deadlock found when trying to get lock; try restarting transaction.

I have already serialized the access, but still get a deadlock error.
This code is executed on the first call in every function. Every thread and process should wait here, till it gets the lock. It's simplified, as selectors are removed.
    # The work with the index -1 always exists.
    f = s.query(WorkerInProgress).with_for_update().filter(
        WorkerInProgress.offset == -1).first()

I have reduced my code to a minimal state. I am currently running only concurrent calls on the method next_slice. Session handling, rollback and deadloc handling are handled outside.
I get deadlocks even all access is serialized. I did tried to increment a retry counter in the offset == -1 entity as well.
def next_slice(self, s, processgroup_id, itemcount):
    f = s.query(WorkerInProgress).with_for_update().filter(
        WorkerInProgress.offset == -1).first()

    #Take first matching object if available / Maybe some workers failed
    item = s.query(WorkerInProgress).with_for_update().filter(
        WorkerInProgress.processgroup_id != processgroup_id,
        WorkerInProgress.processgroup_id != 'finished',
        WorkerInProgress.processgroup_id != 'finished!locked',
        WorkerInProgress.offset != -1
        ).order_by(WorkerInProgress.offset.asc()).limit(1).first()

    # *****
    # Some code is missing here. as it's not executed in my testcase

    # Fetch the latest item and add a new one
    item = s.query(WorkerInProgress).with_for_update().order_by(
        WorkerInProgress.offset.desc()).limit(1).first()

    new = WorkerInProgress()
    new.offset = item.offset + item.count
    new.count = itemcount
    new.maxtries = 3
    new.processgroup_id = processgroup_id
    s.add(new)
    s.commit()
    return new.offset, new.count

I don't understand why the deadlocks are occurring.
I have reduced deadlock by fetching all items in one query, but still get deadlocks. Perhaps someone can help me.

A: Finally I solved my problem. It's all in the documentation, but I have to understand it first.

Always be prepared to re-issue a transaction if it fails due to
  deadlock. Deadlocks are not dangerous. Just try again.
Source: http://dev.mysql.com/doc/refman/5.7/en/innodb-deadlocks-handling.html

I have solved my problem by changing the architecture of this part. I still get a lot of deadlocks, but they appear almost in the short running methods.
I have splitted my worker table to a locking and an non locking part. The actions on the locking part are now very short and no data is handling during the get_slice, finish_slice and fail_slice operations.
The transaction part with data handling are now in a non locking part and without concurrent access to table rows. The results are stored in finish_slice and fail_slice to the locking table.
Finally I have found a good description on stackoverflow too. After identifying the right search terms.
https://stackoverflow.com/a/2596101/5532934


text:
Q: React Context and ES6 classes If I have an ES6 class,
export default class WSConn {
    constructor() {
        this.conn = null;
        this.event_id = null
        this.navigator = null;
    }

    getEventID() {
        return this.event_id
    }

    setEventID(event_id) {
        this.event_id = event_id
    }
}

and I pass it in to context (and initialize it),
class ContextProvider extends Component {
    getChildContext() {
        return {
            logger: new appLogger(Platform.OS),
            websocket: new WSConn()
        };
    }

    render() {
        return this.props.children
    }
}

ContextProvider.childContextTypes = {
  websocket: React.PropTypes.object
};

function wrapWithContextProvider(Comp) {
  return (props) => {
    return (
        <ContextProvider>
            <Comp {...props} />
        </ContextProvider>
    );
  };
}

and I set data in the class, why when I then get the data, is it still null?
How do I set and store data in an es6 class that I pass around via react context without losing any of the state? Or should I just be keeping this as a global object?

A: The solution was that I was doing this:
class SomeClass extends Component {
    getChildContext() {
    return {
        monitor: new Monitoring(url)
    }
  }
}

class Monitoring {
    constructor(url) {
    this.url = url
  }
  getUrl() {
    return this.url
  }
}

Instead of this:
class SomeClass extends Component {
    constructor() {
    this.monitor = new Monitoring(url)
  }

    getChildContext() {
    return {
        monitor: this.monitor
    }
  }
}

class Monitoring {
    constructor(url) {
    this.url = url
  }
  getUrl() {
    return this.url
  }
}


text:
Q: Jsx does not show props properly I am learning react by creating an app, but I have a strange problem in my code, could someone please point out the error? thanks
 test=()=>{
        console.log('filtered card: ',this.state.cards.filter(c=>c.id===this.state.idToDelete)[0].name)

    }

when I use this function to test the line of code, it works fine and shows all of the name properly when ever I click but when I apply the line to render so I can have the name so to put in my Jsx it gives me error?
    const warningCard=this.state.idToDelete && this.state.cards.filter(c=>c.id===this.state.idToDelete)[0].name.toUpperCase()
    return(

        <button onClick={this.test}>test</button>
        <button onClick={()=>this.setState({showForm:!this.state.showForm})}>form</button>
        <button onClick={()=>this.setState({showEditForm:false})}>close edit from</button>

you have {this.state.cards.length} {card}

        {this.state.showWarning &&

ARE YOU SURE YOU WANT TO DELETE THIS {warningCard} CARD?

this is the picture

all the cards show their names correctly when I use console.log and comment out the warningCard, but when I add the warningCard line in i have this error

this is my full component if it may help
import React from 'react';
import CardList from './cardList';
import CardForm from './cardForm';

    class FlashCardMainPage extends React.Component{
        constructor(){
            super();
            this.state={
                cards:[
                    {...},
                    {...},
                    {...}],
                nextId:3,
                showForm:false,
                showEditForm:false,
                cardToEdit:{},
                showWarning:false,
                confirm:false,
                idToDelete:''
            }
        }

        onCardClick=(id)=>{
            const {cards}=this.state
            const newCardsState=this.state.cards.map((c)=> c.id===id ? {...c,showInfo:!c.showInfo} : c)
            this.setState({cards:newCardsState})
        }

        deleteCard=(id)=>{
            this.setState({showWarning:true})
            this.setState({idToDelete:id})
        }

        editCard=(id)=>{
            const cardToEdit = this.state.cards.filter(c=>c.id===id)
            this.setState({cardToEdit, showEditForm:true})
        }

        onFormSubmit=(cardFromSubmit)=>{
            const newCard={id:this.state.nextId,...cardFromSubmit}
            this.setState({
                cards:[...this.state.cards,newCard],
                nextId:this.state.nextId+1,
                cardToEdit:{},
                showForm:false
            })
        }

        onEditCardSubmit=(editedCard)=>{
            this.setState({showEditForm:false})
            const cards=this.state.cards.map((c)=>c.id===this.state.cardToEdit[0].id?c={id:c.id,...editedCard}:c)
            this.setState({cards})
        }

        onCloseForm=()=>{
            this.setState({showForm:false, showEditForm:false})
        }

        test=()=>{
            console.log('filtered card: ',this.state.cards.filter(c=>c.id===this.state.idToDelete)[0].name)

        }

        onConfirm=(pass)=>{
            const check=pass
            if(pass){
                const cards=this.state.cards.filter(c=>c.id!==this.state.idToDelete)
                this.setState({cards, showWarning:false})
            }else
                this.setState({showWarning:false})
        }

        render(){
            const card=this.state.cards.length===1?'card':'cards'
            const filteredCards = this.state.idToDelete && this.state.cards.filter(c=>c.id===this.state.idToDelete);
            const warningCard = filteredCards[0] && filteredCards[0].name.toUpperCase();
            return(

                    <button onClick={this.test}>test</button>
                    <button onClick={()=>this.setState({showForm:!this.state.showForm})}>form</button>
                    <button onClick={()=>this.setState({showEditForm:false})}>close edit from</button>

you have {this.state.cards.length} {card}

                    {this.state.showWarning &&

ARE YOU SURE YOU WANT TO DELETE THIS {warningCard} CARD?

                        <button onClick={()=>this.onConfirm(true)}>Yes</button>
                        <button onClick={()=>this.onConfirm(false)}>No</button>

                    }

                    {this.state.showForm &&
                        <CardForm
                        cardSave={this.onFormSubmit}
                        closeForm={this.onCloseForm}
                        />
                    }

                    {this.state.showEditForm &&
                        <CardForm
                        editCardSave={this.onEditCardSubmit}
                        cardToEdit={this.state.cardToEdit}
                        closeForm={this.onCloseForm}
                        editStatus={this.state.showEditForm}
                        />
                    }

                    <CardList
                        cards={this.state.cards}
                        cardClick={this.onCardClick}
                        deleteCard={this.deleteCard}
                        editCard={this.editCard}
                    />

            )
        }
    }

    export default FlashCardMainPage

A: I think some guards might help you here. What if you try changing the first line into two?
const filteredCards = this.state.idToDelete && this.state.cards.filter(c=>c.id===this.state.idToDelete);
const warningCard = filteredCards[0] && filteredCards[0].name.toUpperCase();


text:
Q: Can cout alter variables somehow? So I have a function that looks something like this:
float function(){
    float x = SomeValue;
    return x / SomeOtherValue;
}

At some point, this function overflows and returns a really large negative value.  To try and track down exactly where this was happening, I added a cout statement so that the function looked like this:
float function(){
    float x = SomeValue;
    cout << x;
    return x / SomeOtherValue;
}

and it worked!  Of course, I solved the problem altogether by using a double.  But I'm curious as to why the function worked properly when I couted it.  Is this typical, or could there be a bug somewhere else that I'm missing?
(If it's any help, the value stored in the float is just an integer value, and not a particularly big one.  I just put it in a float to avoid casting.)

A: Printing a value to cout should not change the value of the paramter in any way at all.
However, I have seen similar behaviour, adding debugging statements causes a change in the value. In those cases, and probably this one as well my guess was that the additional statements were causing the compiler's optimizer to behave differently, so generate different code for your function.
Adding the cout statement means that the vaue of x is used directly. Without it the optimizer could remove the variable, so changing the order of the calculation and therefore changing the answer.

A: As an aside, it's always a good idea to declare immutable variables using const:
float function(){
    const float x = SomeValue;
    cout << x;
    return x / SomeOtherValue;
}

Among other things this will prevent you from unintentionally passing your variables to functions that may modify them via non-const references.

A: Welcome to the wonderful world of floating point.  The answer you get will likely depend on the floating point model you compiled the code with.
This happens because of the difference between the IEEE spec and the hardware the code is running on.  Your CPU likely has 80 bit floating point registers that get use to hold the 32-bit float value. This means that there is far more precision while the value stays in a register than when it is forced to a memory address (also known as 'homing' the register).
When you passed the value to cout the compiler had to write the floating point to memory, and this results in a lost of precision and interesting behaviour WRT overflow cases.
See the MSDN documentation on VC++ floating point switches.  You could try compiling with /fp:strict and seeing what happens.

A: cout causes a reference to the variable, which often will cause the compiler to force it to spill it to the stack.
Because it is a float, this likely causes its value to be truncated from the double or long double representation it would normally have.
Calling any function (non-inlined) that takes a pointer or reference to x should end up causing the same behavior, but if the compiler later gets smarter and learns to inline it, you'll be equally screwed :)

A: I dont think the cout has any effect on the variable, the problem would have to be somewhere else.


text:
Q: Can't see unanswered C++ questions It looks like the plus sign %2b is getting doubly unescaped in tag names in URLs.
Unanswered Questions => c++ link => https://stackoverflow.com/unanswered/tagged/c%2b%2b but this lists only tagged c:

Add 11 to preceding URL => https://stackoverflow.com/unanswered/tagged/c%2b%2b11 lists questions tagged c 11.
Clicking another tab then converts the %2b's to unescaped plus signs.
The "unanswered" tab under the "Questions" section works:

Why are there separate unanswered buttons right next to each other — a website section and a search filter with near identical functionality?

A: Interesting; it looks like we (ok: me) added some code to "fix" (cough) that route after is was misbehaving locally. It looks like the various IIS versions (including express) process a path with non-trivial values slightly differently. But if the non-trivial values are in the query, all is well. I've removed the "fix", so that it will play nicely on prod - should be fine in a few minutes.
It actually reminds me of this slightly-related "feature", which MS claim to have now fixed (presumably on new OS versions, because it isn't fixed for us!) - in which case we might need to revisit this in future, if MS's new fix breaks it for us! All fun.

A: Try this link:
http://stackoverflow.com/questions/tagged/c%2b%2b?sort=unanswered&pagesize=50

It works here.


text:
Q: How to tell mac OSX "osascript tell for "any device" set volume 0 "" how to execute command in terminal to set volume for currect windows or application or any device.... For example to mute system vole it's simple :
osascript -e "set volume 1"

So, i got application witch aren't instaled only runing, i want to put:
osascript -e "tell application \"Applicationame\" to set sound volume to 0"

1) Where to look for Applicationname?
2) How to write correct command?

A: This is the correct syntax:
osascript -e 'tell app "Spotify" to set volume 2'

or
osascript -e 'tell app "<app_name>" to set volume <volume>'


text:
Q: C freeing struct pointer members I have the following structure that I've declared:
typedef struct binTreeNode
{
    void *data;
    struct binTreeNode *left;
    struct binTreeNode *right;
} myBinaryTreeNode;

In my main function, I'm trying to use a pointer to an instance of that structure called root.
myBinaryTreeNode *root = malloc(sizeof(myBinaryTreeNode));
printf("\nPlease insert root data: ");
int input;
scanf("%d", &input);
root->data = (void*)&input;
printInt(root->data);
free(root);

this code runs perfectly well. But, I thought that when you have a  struct with members that are pointers, you should free() each one of them (additionally to the pointer to the struct).
So here, I didn't malloc for root->data (because I think that mallocing the struct does that), but it is initialized to the input value and it's value gets printed successfully. When I try to free(root->data) my program crashes.
So root->data is not malloced when I malloc root? If not, how can I still use it?
Why does this happen? What am I missing here?

A: First, get the concept of where and how you need to (or need not) call free().
You don't need to malloc() "for" root->data, that variable is already allocated while you allocated memory equal to the size of the structure. Now, next, you certainly need root->data to point to some valid memory, so that you can dereference the pointer to read from to write into it. You can do that by either of two ways

*

*store an address which is valid (like in your case, supply the address of an already existing variable)

*assign a pointer returned by another malloc() (success).

In case, you're storing the pointer returned by malloc(), yes you must free() the memory but in your case, root->data holds a pointer not returned by malloc(), so it does not need free()-in either.
Just to add and emphasis on the part related to free()-ing, you must not attempt to free() the memory which has not been previously allocated by a call to malloc() and family otherwise, it invokes undefined behavior. To quote, standard C11, chapter §7.22.3.3, (emphasis mine)

void free(void *ptr);

The free function causes the space pointed to by ptr to be deallocated, that is, made
  available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if
  the argument does not match a pointer earlier returned by a memory management
  function, or if the space has been deallocated by a call to free or realloc, the
  behavior is undefined.

A:
When I try to free(root->data) my program crashes.

You cannot free memory that you have not dynamically allocated. If you want to free the elements, you should first allocate them this way :
typedef struct binTreeNode
{
    int *data;
    struct binTreeNode *left;
    struct binTreeNode *right;
} myBinaryTreeNode;

root->data = malloc(sizeof(int));
if (root->data == NULL)
{
    printf("Error allocating memory\n");
    return;
}
scanf("%d", root->data);
free(root->data);

Note that you should check the result of malloc before continuing.

So root->data is not malloced when I malloc root? If not, how can I still use it?

Note also that space for root->data is allocated when you allocate memory for the struct, but it is not malloced. You need an extra malloc especially for root->data, as shown in the example above. The reason why you need malloc for root->data is to be able to dereference the pointer.

A: data member points to input local variable, so you cannot free it.
You must free members if you dynamically allocate them, like
typedef struct binTreeNode
{
    int *data;
    struct binTreeNode *left;
    struct binTreeNode *right;
} myBinaryTreeNode;

root->data = malloc(sizeof(int));
scanf("%d", root->data);
free(root->data);

A: I have added some annotations to your code.
I hope this clears things up.
// I have added an enclosing block for the purpose of demonstration:
{
    // Here you allocate memory for a tree node object with dynamic/allocated
    // storage duration.
    // That is: three pointers, that point to nowhere are created and will
    // exist until the memory holding them is free'd.
    myBinaryTreeNode *root = malloc(sizeof(myBinaryTreeNode));
    printf("\nPlease insert root data: ");
    // Here you create an object with automatic storage duration.
    // That is, the object is automatically destroyed when the function
    // returns or the block is closed: { ... }
    int input;
    // here you attempt to assign a value to the variable
    // (you should check the return value: the input may fail)
    scanf("%d", &input);
    // Here you assign the address of an object to a pointer.
    // Note that you are only allowed to use the pointer as long as the
    // object it points to "lives".
    root->data = (void*)&input;
    // Here you probably print the value, or the pointer address, or something else
    printInt(root->data);
    free(n); // <-- Where and how did you allocate this?
    // Here you free the memory holding the tree node
    free(root);
} // <-- At this point the "input" variable is automatically destroyed.

You should really read up on the different storage durations (automatic and dynamic/allocated) and the purpose of dynamic memory allocation:

*

*http://en.cppreference.com/w/c/language/storage_duration

*http://en.cppreference.com/w/c/language/lifetime

*C Memory Management

To address the questions in detail:

When I try to free(root->data) my program crashes.

That is because you can only free() what you have malloc(). Memory management is different for the different types of storage duration.

So root->data is not malloced when I malloc root?

Memory for the pointer is allocated, but it doesn't "own" or "point to" any object by default.

If not, how can I still use it?

Just as you did. You assign a memory address of an object to it, that lives long enough for you to use it. You can produce such object using dynamic memory management (then take care that you destroy it manually once you're done: don't leak memory) or using "automatic memory management" as you have done (then take care that it isn't destroyed too early: don't access invalid memory). (To name just two of the possible ways to create an object...)


text:
Q: Prevent page from loading in javascript? I am using javascript onunload function to display a popup form when user is trying to leave the page, it shows the popup but it can't prevent page load.
Here's my code
$(window).bind('unload', function(e) {
    $( "#dialog" ).dialog({
        modal: true
    });

    e.preventDefault();
    return false;
});

A: It should be something like this:
$(window).bind('beforeunload', function(e){
    e.preventDefault();
    $( "#dialog" ).dialog({
        modal: true
    });
    return "Look at the modal";
});

Without Jquery:
window.onbeforeunload = function (e) {
   var message = "Your pop up message",
   e = e || window.event;
   // For IE ,Firefox and Chrome
   if (e) {
      // your functions go here
      console.log("test");
      e.returnValue = message;

   } else {
      // For Safari
      //your functions go here
      console.log('test');
      return message;
    };
};


text:
Q: Two python codes to find second lowest marks I have been told to solve this HackerRank problem:
Print the name(s) of any student(s) having the second lowest grade in Physics; if there are multiple students, order their names alphabetically and print each one on a new line.
Link to Question:
https://www.hackerrank.com/challenges/nested-list/problem
Now, additional constraint apart from that mentioned on HackerRank Page:

*

*No use of lambda function

*Minimal or no use of List functions (apart from sorting)

*Try to not create additional (duplicate) list (a new list which doesn't have the minimum value of original list. Thus, minimum of this list is second minimum of original list.)
Here's my first code.
Tried to make it as basic as possible(without use of many in-built function)
data= []
names = []

for _ in range(int(raw_input())):
    name = raw_input()
    score = float(raw_input())

    data.append([name,score])

# chossing minimum and second minimum form the first two scores.
if data[0][1] > data[1][1]:
    smin = data[0][1]
    mins = data[1][1]
else:
    mins = data[0][1]
    smin = data[1][1]

for i in range(len(data)):

    if data[i][1] < mins:
        smin = mins
        mins = data[i][1]

    elif data[i][1] > mins and data[i][1] < smin:
        smin = data[i][1]

for i in data:
    if i[1] == smin:
        names.append(i[0])

names.sort()
for i in names:
    print(i)

This code runs good for all test cases except test case 3(hidden).
Now, I wrote another code.
This code breaks rule 3 of additional constraints(mentioned above) but runs perfectly.
if __name__ == '__main__':
    x = int(raw_input())
    student = []
    l = []
    for i in range(x):
        name = raw_input()
        score = float(raw_input())
        y = [name,score]
        student.append(y)

    lowest = 0
    for i in range(len(student)):
        if(student[lowest][1] > student[i][1]):
            lowest = i

    l_marks = student[lowest][1]
    stud = []
    for i in student:
        if(l_marks != i[1]):
            stud.append(i)

    lowest = 0
    for i in range(len(stud)):
        if(stud[lowest][1] > stud[i][1]):
            lowest = i

    l_marks = stud[lowest][1]
    l.append(stud[lowest][0])
    del(stud[lowest])
    for i in stud:
        if(l_marks == i[1]):
            l.append(i[0])

    l = sorted(l)
    for i in l:
        print(i)

This code is totally correct. Runs good for all test cases.
Now, I can't figure out why is the code 1 not covering all cases and how did code 2 run correctly??
What, is wrong in code 1?
Note:
I have seen many alternate codes(from GeeksforGeeks and StackOverFlow) which are correct. I don't want link to any new code which will give me correct answer. Instead I would like to know, what is wrong with code 1?

A: The fatal flaw in your first code extract is the bit where you set up mins and smin:
# chossing minimum and second minimum form the first two scores.
if data[0][1] > data[1][1]:
    smin = data[0][1]
    mins = data[1][1]
else:
    mins = data[0][1]
    smin = data[1][1]

What happens here if the first two people have the same score? mins and smin will be the same.
Consider this input:
3
foo
10
bar
10
baz
50

When you get to considering baz in your for loop, you will have mins == 10 and smin == 10.
So, when you try to work out if baz's score should be the second minimum, there is a problem:
elif data[i][1] > mins and data[i][1] < smin:
    smin = data[i][1]

Because mins and smin are the same, you won't set a new value for smin.
Your second programme solves this problem by taking a different approach. Hope this helps!

A: What if the first two scores are equal and negative?
For example: [['John': -15], ['Nic': -15], ['Mike': 20]]

In this scenario your code sets both minimum and second_minimum to -15 at:
if data[0][1] > data[1][1]:
    smin = data[0][1]
    mins = data[1][1]
else:
    mins = data[0][1]
    smin = data[1][1]

Then at this part of the  code, your smin is -15 :
for i in data:
    if i[1] == smin:
        names.append(i[0])

But the second_minimum is actually 20
You just appended the names list with ['John', 'Nic']


text:
Q: Error in Update T-SQL in SQL Server 2005 I want to update some data in EditEmail table from DBUsers database to EditEmail  table in DBCurrent datebase.So i got error when  i execute following statement:
USE DBCurrent

UPDATE [DBUsers].[dbo].[EditEmail] EN
SET EN.MailSubject = E.MailSubject,
    EN.MailMessage = E.MailMessage
FROM
(
    SELECT * FROM EditEmail
) AS E
WHERE EN.Type = E.Type

Error message:

ERROR:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near 'EN'.
Msg 156, Level 15, State 1, Line 8
Incorrect syntax near the keyword 'AS'.

Is there any syntax  mistake in this T-SQL?

A: You cannot give the table you're specifying in the UPDATE statement a table alias (for whatever reason - don't ask me why this isn't possible, ask the T-SQL design team)...
Try this statement instead:
USE DBCurrent

UPDATE
    [DBUsers].[dbo].[EditEmail]
SET
    MailSubject = E.MailSubject,
    MailMessage = E.MailMessage
FROM
    dbo.EditEmail E
WHERE
    DBUsers.dbo.EditEmail.Type = E.Type
    AND E.Type = 'blahblah'  -- or whatever additional conditions you have!

You need to specify the table being updated in full, e.g. with its database, schema, table and column name, in the WHERE clause.
There is also no need for your "artificial" subquery there to reference the EditMail table - just define that in the FROM clause and give it a table alias (here, they're supported).

A: T-SQL doesn't allow to define an alias on the table updated,
but it allows to update an alias:
This fixes the syntax, I think the logic must still be improved.
Please try (I didn't check):
UPDATE EN
SET EN.MailSubject = E.MailSubject,
    EN.MailMessage = E.MailMessage
FROM [DBUsers].[dbo].[EditEmail] EN
    join EditEmail E
on EN.Type = E.Type


text:
Q: Summarise data.table when "by" grouping variables stored as vector of strings I am trying to summarise a datatable as part of a function. The grouping variable changes depending on user requirements/data. The grouping variables are entered as a vector of strings. How can I use this as a grouping variable? See code below
library(data.table)
test <- as.data.table(mtcars)

grouping_vars <- c("vs", "am")

#does what I would like
test[,.(counts = .N,
       mpg = mean(mpg),
       disp = median(disp)), by = .(vs,am)]

#throws error
test[,.(counts = .N,
       mpg = mean(mpg),
       disp = median(disp)), by = .(grouping_vars)]

#only gets the first variable
test[,.(counts = .N,
       mpg = mean(mpg),
       disp = median(disp)), by = .(get(grouping_vars))]

A: Instead of .(, here we can use c(
library(data.table)
test[,.(counts = .N,
    mpg = mean(mpg),
    disp = median(disp)), by = c(grouping_vars)]
#    vs am counts      mpg  disp
#1:  0  1      6 19.75000 160.0
#2:  1  1      7 28.37143  79.0
#3:  1  0      7 20.74286 167.6
#4:  0  0     12 15.05000 355.0


text:
Q: why the DIV jumps why I scroll window( it works fine in firefox while not in chrome&safari) **

$(window).scroll(function() {
  $('#box').css('top', $(this).scrollTop())
})
* {
  margin: 0;
  padding: 0;
}
body {
  height: 2000px;
}
#box {
  width: 200px;
  height: 200px;
  position: absolute;
  background: gray;
}

**
when I scroll page,this #box jumpy;maybe you suggest me use position:fixed ,however, The animation need use javascript.
help me, please


text:
Q: Not able to send regular sms instead of iMessage I tried everything.
Restarting iPhone, removing dialog and send again, disabling iMessage, reset network setting. Nothing helps.
Any another idea? My operator is Vodafone, and it supports SMS. It has adequate SMS balance in my pack. This recipient is available to receive SMS.
The same SIM works in other phone.


text:
Q: Prove that $\mathbb{R} \nsim \mathbb{R}^{\mathbb{R}}$. The task is to prove that $\mathbb{R} \nsim \mathbb{R}^{\mathbb{R}}$.
I know how easy it is to prove this once I can use cardinality, but I can't. I need to show that a bijection between those sets doesn't exist (or by using Cantor-Schröder-Bernstein theorem).
The injection $f:\mathbb{R} \Rightarrow \mathbb{R}^{\mathbb{R}}$ is easy:
$$ f(h)=g_h, g_h:\mathbb{R} \Rightarrow \mathbb{R}, g_h(x)=h$$
So, $k(\mathbb{R}) \leq k(\mathbb{R}^{\mathbb{R}})$.
What I struggle to do is to prove that $k(\mathbb{R}) \neq k(\mathbb{R}^{\mathbb{R}})$.
Thanks in advance!


text:
Q: Deducing that an analytic function $f$ in a simply connected domain $\Omega$ is the derivative of an analytic function $F:\Omega\to\mathbb{C}$ Let $\Omega$ be a simply connected domain, i.e. open and connected subset of $\mathbb{C}$ and $f$ be analytic in $\Omega$. I am trying to understand how you can deduce that $f(z) = \frac{d}{dz}F(z)$ for some analytic function $F:\Omega\to\mathbb{C}$ from the two following results (which are verbatim from my old notes handed in class):
1.) Monodromy theorem: If $\Omega$ is simply connected and $f:\Omega'\to\mathbb{C}$ is an analytic function which admits an analytic continuation along any path $\gamma$ in $\Omega$ with the starting point of $\gamma$ staying in $\Omega'$, then $f$ has a direct analytic continuation to $\Omega$.
2.) If $f$ is an analytic function in a domain $\Omega$ and $F$ is its primitive, i.e. $\frac{d}{dz}F(z) = f(z)$, then $F$ has an analytic continuation along $F_k:\Omega_k\to\mathbb{C}, k=1,\dots,n$, i.e. $F_{k+1}\equiv F_k$ in $\Omega_{k+1}\cap \Omega_k$, where $\Omega_k$s are discs and $\frac{d}{dz}F_k(z) = f(z)$ in $\Omega_k$.
(Thoughts:) My current understanding is nil in the sense that I do not see what Monodromy theorem has to do with the second result, which likely used to conclude the result. Specifically, the analytic continuation along $F_k$ of the second result almost fit with out need: Their derivative agrees with $f$ on the disks $\Omega_k$. To satisfy our case we would need to inflate some of (or all) the disks $\Omega_k$ so that inflated $\tilde{\Omega_k} = \Omega$. But I just don't see how this happens with the Monodromy theorem.
Edit: As discussed in the comments, the function $F(w) = \int_{\gamma_{w_0, w}}f(z)dz$ will do as such an analytic function where $w_0\in\Omega$ is fixed and $\gamma_{w_0, w}$ is a path contained in $\Omega$ connecting $w_0$ and $w$. But what is still unclear to me is that where do we need the two stated theorems? To me the only thing we need is to be able to conclude that in simply connected domains, the path integral of an analytic function depends only on the initial and terminal point.


text:
Q: how to flatten lists while leaving some nesting (in python) I have a list of lists of lists with strings, something like this (representing chapters, paragraphs and sentences of a text)):
[ [[ ['chp1p1s1'], ['chp1p1s2'], ['chp1p1s3'] ],
   [ ['chp1p2s1'], ['chp1p2s2'], ['chp1p2s3'] ]],
  [[ ['chp2p1s1'], ['chp2p1s2'], ['chp2p1s3'] ],
   [ ['chp2p2s1'], ['chp2p2s2'], ['chp2p2s3'] ]] ]

I know how to flatten this list completly (for example by [x for y in z for x in y]), but what I would like to do is to flatten it partially, to finally look like this:
[ [ ['chp1p1s1'], ['chp1p1s2'], ['chp1p1s3'],
    ['chp1p2s1'], ['chp1p2s2'], ['chp1p2s3'] ],
  [ ['chp2p1s1'], ['chp2p1s2'], ['chp2p1s3'],
    ['chp2p2s1'], ['chp2p2s2'], ['chp2p2s3'] ] ]

I managed to solve this by some for loops:
semiflattend_list=list()
for chapter in chapters:
    senlist=list()
    for paragraph in chapter:
        for sentences in paragraph:
            senlist.append(sentences)
    semiflattend_list.append(senlist)

But I wonder if there is a better, shorter solution? (I don't think, zip is a way to go, because my lists are different in size.)

A: The easiest change I can see is using the itertools.chain method:
q = [
     [[ ['chp1p1s1'], ['chp1p1s2'], ['chp1p1s3'] ],
       [ ['chp1p2s1'], ['chp1p2s2'], ['chp1p2s3'] ]],
     [[ ['chp2p1s1'], ['chp2p1s2'], ['chp2p1s3'] ],
       [ ['chp2p2s1'], ['chp2p2s2'], ['chp2p2s3'] ]]
    ]

r = [list(itertools.chain(*g)) for g in q]
print(r)

[[['chp1p1s1'], ['chp1p1s2'], ['chp1p1s3'], ['chp1p2s1'], ['chp1p2s2'], ['chp1p2s3']],
 [['chp2p1s1'], ['chp2p1s2'], ['chp2p1s3'], ['chp2p2s1'], ['chp2p2s2'], ['chp2p2s3']]]

So, what does [list(itertools.chain(*g)) for g in q] mean:
# If I only had this
[g for g in q]
# I would get the same I started with.
# What I really want is to expand the nested lists

# * before an iterable (basically) converts the iterable into its parts.
func foo(bar, baz):
   print( bar + " " + baz )

lst = ["cat", "dog"]
foo(*lst) # prints "cat dog"

# itertools.chain accepts an arbitrary number of lists, and then outputs
# a generator of the results:
c = itertools.chain([1],[2])
# c is now <itertools.chain object at 0x10e1fce10>
# You don't want an generator though, you want a list. Calling `list` converts that:
o = list( c )
# o is now [1,2]
# Now, together:
myList = [[2],[3]]
flattened = list(itertools.chain(*myList))
# flattened is now [2,3]


text:
Q: Django URL pattern with a list I have a list with category names , e.g. cats = ["tv", "movie", "theater"].
I would like to write a url pattern to catch only URLs which contain one of the items in the list, such as:
url(r'^site/CATEGORY_NAME/$', 'mainsite.views.home'),

so that CATEGORY_NAME can only one one of the items in the list cats.
How can I do that?
Thanks,
Meir

A: You can build part of a regular expression from the list by using python's string join method, and then use that in the URL pattern.
For example:
cats = ["tv", "movie", "theater"]
cats_re = '(?:' + '|'.join(cats) + ')'

# ...then...
url(r'^site/' + cats_re + '/$', 'mainsite.views.home'),

In this case, the whole regular expression would look like:
url(r'^site/(?:tv|movie|theater)/$', 'mainsite.views.home'),

A: As URL matching is done based on a regular expression you can use the ability of regular expressions to match multiple strings to do this. The | (pipe) character selects between multiple options, i.e. (a|b|c) will match a, b or c.
url(r'^site/(tv|movie|theatre)/$', 'mainsite.views.home'),

The Python regular expression documentation is really rather good and worth a read.

A: For Django 2+ with Python 3+, you can use the following:
from django.urls import re_path
from . import views

# List of category names defined here:
_entities = ["tv", "movie", "theater"]
re_entities = f'(?P<enertainment>{"|".join(_entities)})'

urlpatterns = [
    ...
    re_path(f'^{re_entities}/.../$', views.EntertainmentHandler.as_view()),
    ...
    ]


text:
Q: Visual studio 2022 Python programming, How to remove tool tips / parameter pop up? I am just learning Python and using Visual studio 2022.
But I am getting these really annoying parameter descriptions / pop ups that appear as I am writing code. Sometimes they take up half the screen, depending on what I've written.screenshot screenshot2
Is there a way to remove them?
Thank you.


text:
Q: Django, Webpack and Heroku: Error reading /app/webpack-stats.json I'm trying to use Django with Webpack on Heroku via django-webpack-loader. After pushing the files from the repository to Heroku, I run webpack to generate the static files in /dist as well as webpack-stats.json:
npx webpack --config webpack.config.js

This works fine: both the /dist files and the webpack-stats.json file are correctly created (both are placed within /app/). However, when I try to load the page I get an error:
OSError at /
Error reading /app/webpack-stats.json. Are you sure webpack has generated the file and the path is correct?

The error doensn't say much other than the file /app/webpack-stats.json is missing; however, the file exists, its content is well-formatted and it's in the right location.


text:
Q: Running Jplayer from an SSL website, but the audio files are non-SSL. Audio files will not play I run a music aggregation website, HVmusic.com, where I use Jplayer to play MP3 files that users add to their listings. About a year ago I changed my site to run SSL (https) and now I find that any MP3 files that are hosted on non-SSL websites cannot be played by jPlayer.
Here is an example of the Jplayer code..
<script type="text/javascript">
$(document).ready(function(){        // Player instance
        $("#jplayer_1").jPlayer({
        ready: function () {
                $(this).jPlayer("setMedia", {
                        mp3: "http://ellywininger.com/mp3/Little Red Wagon.mp3"
                });
        },
    play: function() { // To avoid multiple jPlayers playing together.
        $(this).jPlayer("pauseOthers");
    },
        cssSelectorAncestor: "#jp_container_1",
        swfPath: "/common/licensed/jplayer",
        supplied: "mp3",
        useStateClassSkin: true
      });        // Player instance
        });
</script>

Note that this person's site (http://ellywininger.com) actually runs SSL mode and the http: redirects to https:, so these MP3 files play fine in Jplayer.
Is that just the way it is? I didn't think these files were considered "part of the SSL page" but instead "links", and links from an SSL page can be to non-SSL pages.
Thanks for your help.


text:
Q: Loading listView in new activity I'm having a bit of a trouble loading contents to a fresh listView. If i use setContentView, it displays an empty list and if i try changing my Intent the app crashes. Please what am I doing wrong. The main Activity class is:
ListView lv;
Context context;

private int [] prgmImages={R.drawable.phones_and_tablets,R.drawable.home_and_kitchen_appliances,
        R.drawable.beauty_health_and_personal_care,R.drawable.fashion,R.drawable.subscriptions,
        R.drawable.electronics,R.drawable.windows_logo,R.drawable.music_and_movies,
        R.drawable.baby_kids_and_toys,R.drawable.sports,R.drawable.books_and_stationery,
        R.drawable.fastfood_and_eatery};
private String [] prgmNameList={"Phones & Tablets","Home & Kitchen","Beauty, Health & Personal Care",
        "Fashion","Subscriptions","Electronics","Computer & Accessories","Music & Movies","Baby, Kids & Toys",
        "Sports & Fitness","Books & Stationery","Fast Food, Drinks & Groceries"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    context=this; // Instantiate context after listView's properties are set.
    lv=(ListView) findViewById(R.id.listView);
    lv.setAdapter(new MainCustomAdapter(this, this.prgmNameList, this.prgmImages));
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch( position ){
                case 0:  { setContentView(R.layout.activity_fone_cats); break; }
                case 1:  { setContentView(R.layout.activity_home_kit_cats); break; }
                case 2:  { setContentView(R.layout.activity_beauty_care_cats); break; }
                case 3:  { setContentView(R.layout.activity_fashion_cats); break; }
                case 4:  { setContentView(R.layout.activity_telecoms_cats); break; }
                case 5:  { setContentView(R.layout.activity_electronics_cats); break; }
                case 6:  { setContentView(R.layout.activity_computers_cats); break; }
                case 7:  { setContentView(R.layout.activity_entertainment_cats); break; }
                case 8:  { setContentView(R.layout.activity_toys_cats); break; }
                case 9:  { setContentView(R.layout.activity_sports_cats); break; }
                case 10:  { setContentView(R.layout.activity_stationeries_cats); break; }
                case 11:  { setContentView(R.layout.activity_f_food_drinks_grocery_cats); break; }
            }
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

My main xml layout construct is as follows:
<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:textSize="25dp"
    android:textStyle="bold"
    android:textColor="@color/colorBlack"
    android:text="@string/action_companyName" />

<ImageView
    android:id="@+id/imageView"
    android:layout_gravity="right"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/icon" />

<TextView
    android:id="@+id/textView_1"
    android:layout_gravity="right"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/action_motto"
    android:textSize="18sp"
    android:textStyle="italic|bold"/>

<TextView
    android:id="@+id/textView_2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/action_query"
    android:textColor="#3a94d5" />

<SearchView
    android:id="@+id/searchView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:queryHint="@string/action_query2"
    android:contentDescription="@string/action_query2" />

<ImageView
    android:id="@+id/imageView_1"
    android:layout_width="match_parent"
    android:layout_height="100sp"
    android:scaleType="fitXY"
    android:src="@drawable/ad" />

<TextView
    android:id="@+id/textView_3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="."
    android:textColor="#FFFFFF" />

<ListView
    android:id="@+id/listView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
</ListView>

I built it the following custom adapter:
String [] category; // The category a sales-item belongs to
Context context;
int [] imageId;
private static LayoutInflater inflater=null;

public MainCustomAdapter(MainActivity currentActivity, String[] prgmNameList, int[] prgmImages) {
    context = currentActivity;
    category = prgmNameList;
    imageId = prgmImages;
    inflater = ( LayoutInflater )context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
    return category.length;
}

@Override
public Object getItem(int position) {
    return position;
}

@Override
public long getItemId(int position) {
    return position;
}

public class Holder{ // Set an object to hold category items for each position in the list
    TextView txt;
    ImageView img;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    Holder holder=new Holder();
    View rowView = inflater.inflate(R.layout.programlist, null);
    holder.txt=(TextView) rowView.findViewById(R.id.textView1);
    holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
    holder.txt.setText(category[position]); // Hold the name of the selected category
    holder.img.setImageResource(imageId[position]); // Hold the icon of the selected category
    return rowView;
}

programlist layout was built as follows:
<ImageView
    android:id="@+id/imageView1"
    android:layout_gravity="center"
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:src="@drawable/ic_launcher" />

<TextView
    android:id="@+id/textView1"
    android:layout_gravity="center"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="24dp"
    android:text="TextView" />

I built activity_fone_cats thus:
    <TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:textSize="25dp"
    android:textStyle="bold"
    android:textColor="@color/colorBlack"
    android:text="@string/action_companyName" />

<ImageView
    android:id="@+id/imageView"
    android:layout_gravity="right"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/icon" />

<TextView
    android:id="@+id/textView_1"
    android:layout_gravity="right"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/action_motto"
    android:textSize="18sp"
    android:textStyle="italic|bold"/>

<TextView
    android:id="@+id/textView_2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/action_query"
    android:textColor="#3a94d5" />

<SearchView
    android:id="@+id/searchView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:queryHint="@string/action_query2"
    android:contentDescription="@string/action_query2" />

<ImageView
    android:id="@+id/imageView_1"
    android:layout_width="match_parent"
    android:layout_height="100sp"
    android:scaleType="fitXY"
    android:src="@drawable/ad" />

<TextView
    android:id="@+id/textView_3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="."
    android:textColor="#FFFFFF" />

<ListView
    android:id="@+id/listView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
</ListView>

Please how do I ensure that the items in the list are displayed upon clicking on a listItem in main activity and how do I stop the app from crashing if I wanted to use changing of Intents, instead of switching contentViews?

A:  lv=(ListView) findViewById(R.id.listView);

        lv.setAdapter(new MainCustomAdapter(this, prgmNameList, prgmImages));

   lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) setContentView(R.layout.activity_fone_cats);
                else if (position == 1) {
                    startActivityForResult(new Intent(view.getContext(),HomeKitchenCatsActivity.class), 0);
                    // setContentView(R.layout.activity_home_kit_cats);
                }
                else if (position == 2) setContentView(R.layout.activity_beauty_care_cats);
                else if (position == 3) setContentView(R.layout.activity_fashion_cats);
                else if (position == 4) setContentView(R.layout.activity_telecoms_cats);
                else if (position == 5) setContentView(R.layout.activity_electronics_cats);
                else if (position == 6) setContentView(R.layout.activity_computers_cats);
                else if (position == 7) setContentView(R.layout.activity_entertainment_cats);
                else if (position == 8) setContentView(R.layout.activity_toys_cats);
                else if (position == 9) setContentView(R.layout.activity_sports_cats);
                else if (position == 10) setContentView(R.layout.activity_stationeries_cats);
                else if (position == 11) setContentView(R.layout.activity_f_food_drinks_grocery_cats);
            }
            });

A: @aburimegregory yes you have got the answer now. OnItem click you want to bind new layout with your activity.
        lv=(ListView) findViewById(R.id.listView);
        lv.setAdapter(new MainCustomAdapter(this, this.prgmNameList, this.prgmImages));
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch( position ){
                    case 0:  { setContentView(R.layout.activity_fone_cats); break; }
                    case 1:  { setContentView(R.layout.activity_home_kit_cats); break; }
                    case 2:  { setContentView(R.layout.activity_beauty_care_cats); break; }
                    case 3:  { setContentView(R.layout.activity_fashion_cats); break; }
                    case 4:  { setContentView(R.layout.activity_telecoms_cats); break; }
                    case 5:  { setContentView(R.layout.activity_electronics_cats); break; }
                    case 6:  { setContentView(R.layout.activity_computers_cats); break; }
                    case 7:  { setContentView(R.layout.activity_entertainment_cats); break; }
                    case 8:  { setContentView(R.layout.activity_toys_cats); break; }
                    case 9:  { setContentView(R.layout.activity_sports_cats); break; }
                    case 10:  { setContentView(R.layout.activity_stationeries_cats); break; }
                    case 11:  { setContentView(R.layout.activity_f_food_drinks_grocery_cats); break; }
                }

               lv=(ListView) findViewById(R.id.listView);
               lv.setAdapter(new MainCustomAdapter(this, this.prgmNameList, this.prgmImages));
            }
        });

After binding new layout, you need to find the listview and set the adapter to load the list of items in the new ContentView.
Same thing you need to do for all other items in the new layout.(Find the view and set the value after binding new layout)
Note:I am not sure about your project requirment.Your way of approaching the listview may be inappropriate. Spend some more time to learn listview and its functionality and then start implement. All the best.


text:
Q: Is it possible to change the camera view in the FIFA 12 practice arena? In FIFA 12 (and some previous versions of FIFA) when you first start up the game you can control a player and practice playing against an AI goalie on an otherwise empty warm-up field. This also occurs before each match.
My problem with it is that the camera view is always facing the goal, whereas the usual camera view for matches in FIFA is the side-on view from high on the sideline. This means that practising shooting is a little pointless as you will never see the goal like that in a proper match.
Is there any way to change the camera view in the practice arena?

A: I havent played FIFA for a while so this isn't 100% but I'm pretty sure there is no way to change the camera. All u can do is check the different camera settings in the option menu, and if it isn't there then sadly no there is no way to change it. The warm up is mainly for fun and not for real match practice.


text:
Q: How to call sendMFACode function from out of the authenticateUser function in aws cognito How to call the sendMFACode function from out of the authenticateUser function in the aws cognito
when i executing the cognitoUser.sendMFACode. i get following error
{ code: 'InvalidParameterException',
  name: 'InvalidParameterException',
  message: 'Missing required parameter Session' }

The executed code is
cognitoUser.sendMFACode('123456', {
                onSuccess: function (result) {
                   console.log(result);
                },
                onFailure: function (err) {
                   console.log(err);
                }
            })

cognitoUser.getSession() works only for authenticated user
Error: Local storage is missing an ID Token, Please authenticate