text:
Q: Sets of form fields have stopped passing information to the database I have three sets of form fields that are shown and hidden by jQuery and a Select list.
They are displaying just like I want them. But now the information that was being passed to the php code from the first two sets is being lost and if the bottom set of three fields are the set used. The information is passed no problem.
Is this a case of similarly named items lower in the page erasing the information of items in the upper part of the pages?
How do I get around this?

Your guest names

                    Guest: <input type="text" style="width:180px;" name="GuestName" id="GuestName" />

Your guest names

                    Guest: <input type="text" style="width:180px;" name="GuestName" id="GuestName" />

                    Guest 2: <input type="text" style="width:180px;" name="GuestName2" id="GuestName2" />

Your guest names

                    Guest: <input type="text" style="width:180px;" name="GuestName" id="GuestName" />

                    Guest 2: <input type="text" style="width:180px;" name="GuestName2" id="GuestName2" />

                    Guest 3: <input type="text" style="width:180px;" name="GuestName3" id="GuestName3" />

A: When you hide those fields, try also disabling them. This will prevent them from being submitted with the form. You'll, of course, have to re-enable them when you show them.
Try these changes (your code commmented, replace with new code):
// $("#options").children().hide().eq(index).show();
$("#options").children().hide().find('input').prop('disabled', true);
$("#options").children().eq(index).show().find('input').prop('disabled', false);

A better way might be to make jQuery fire a 'hide' event when you call hide() and disable the inputs when that happens (and similar for show()):
// taken from http://stackoverflow.com/a/2857952/259457
var _oldhide = $.fn.hide;
$.fn.hide = function(speed, callback) {
    $(this).trigger('hide');
    return _oldhide.apply(this,arguments);
}

$('#options li').on('hide', function() {
    $(this).find('input').prop('disabled', true);
});

Then you can keep your code the rest of your code the same, and the fields will be disabled/enabled automatically when you call show() or hide() on the li tags.

A:
Is this a case of similarly named items lower in the page erasing the information of items in the upper part of the pages?

yes it is.. when the form is posted.. the fields in the form is posted by its name , in your case three inputs have the same name so it is replacing and only one is getting posted... one way is to give it a unique name..
or disableing all other field except the one ,so that it is not posted ..
try this
 $("#numberattending").change(function() {
      var index = $(this).children(":selected").index();
      $("#options").find('input').prop('disabled',true);
      $("#options").children().hide().eq(index).show().find('input').prop('disabled',false);
 });


text:
Q: Cast an ICollection in order to override GetOrphans() I would like to allow reparenting in Fluent NHibernate.
Here I read that I have to create two classes which inherit from IUserCollectionType and PersistentGenericBag<MyClass>. If I change Box from the example to my own classname, everything works fine - except one thing: In the class which inherits from PersistentGenericBag<MyClass> I can't override GetOrphans() because Cast() is not defined for an ICollection.
This is what I would like to have:
public override ICollection GetOrphans(object snapshot, string entityName)
{
    var orphans = base.GetOrphans(snapshot, entityName)
        .Cast<MyCalss>()
        .Where(b => ReferenceEquals(null, b.CurrentStorage))
        .ToArray();

    return orphans;
}

How can I use Cast on an ICollection?
Edit
This is the exact error I get (unfortunatly it's german): Fehler   1   "System.Collections.Generic.ICollection<T>" enthält keine Definition für "Cast", und es konnte keine Erweiterungsmethode "Cast" gefunden werden, die ein erstes Argument vom Typ "System.Collections.Generic.ICollection<T>" akzeptiert. (Fehlt eine Using-Direktive oder ein Assemblyverweis?)

A: Cast<T> is an extension method living in the System.Linq namespace.
And to use an extension method you need to add it's namespace with an using directive.
So just add the following using to your file and it should work:
using System.Linq;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android google maps custom tiles I'd like to build an app using google maps and I'd love to have some kind of custom tiles.
As I've found nothing on the web, I'd like to know if there is any way to do that on Android?
I found that library on open street map: http://code.google.com/p/osmdroid/
But I'd prefer using google maps.

A: Just create your own TileOverlay and TileProvider to return tiles to the Maps API.  Then call gmap.setMapType(GoogleMap.MAP_TYPE_NONE) to disable Google's tiles.

A: There is no support for custom tile sets with the Google Maps SDK Add-on for Android, sorry.
UPDATE
Maps V2 -- introduced well over a year after this question was asked and this answer was posted -- offers a TileProvider facility that apparently handles this.


text:
Q: How to customize the color of the currently selected item of a listbox? This question results out of my last question here in stackoverflow. The problem to scroll automatically to a specific item is solved, but now i want to set the selected item background to transparent or white. How can i do this??
Update 1
<ListBox ItemsSource="{Binding SomeData}"
         SelectedIndex="{Binding SomeIndex}">
   <ListBox.ItemsPanel>
      <ItemsPanelTemplate>
         <WrapPanel Orientation="Vertical" />
      </ItemsPanelTemplate>
   </ListBox.ItemsPanel>
   <ListBox.ItemTemplate>
      <DataTemplate>
         <SomeChart DataContext="{Binding }" />
      </DataTemplate>
   </ListBox.ItemTemplate>
 </ListBox>

And for this example i need a way to customize the selecteditem color.

A: Starting with a simple listbox in a window:
<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="MainWindow"
    Width="525"
    Height="350">
<Window.DataContext>
    <local:ViewModel />
</Window.DataContext>
<Grid Name="LayoutRoot">
    <ListBox ItemsSource="{Binding Elements}"/>
</Grid>

Select the listbox in ExpressionBlend:

Then select "Object" in the superior menu and choose:

This will create a new ListBoxItemStyle and, for the new style, a new ListBoxItem Template, based on the original. In the default template there is already some logic for changing the visual of the element based in triggers and visualstates. The visual of the element when it is selected is driven by a trigger, which you can modify to acomplish your needs.
Select the view triggers. There will some triggers driven by the "IsSelected" property. There you can change the appearence of the item when it is selected, selected and disabled, etc.

Just select the trigger you want from the existing ones (for example, the "IsSelected = True") and modify the properties of elements of the template with Blend recording. By default, there is some properties changes targeting a "target-element", meaning the template itself, like "Foreground". Others target elements of the template, like the Border "Bd".
Of course you can create your ListBoxItemStyle from scratch, but this way is faster if you just want to make simple changes.


text:
Q: Vertically center active li in the ul I want to do something like musixmatch. I want to display the active verse at the center of ul.

I know how to do it in javascript, but is it possible to do it with pure CSS?

You know, everybody's been tellin' me what they think about me for the last few months

It's too loud

Maybe it's time I tell 'em what I think about them

CSS:
@import url('https://fonts.googleapis.com/css?family=Roboto');
body {
    background: #252525;
    font-family: 'Roboto', sans-serif;
    color: white;
}

#lyrics {
    background-color: rgba(0, 0, 0, 0.45);
    position: fixed;
    width: 70%;
    list-style: none;
    top: 50%;
    transform: translate(-50%, -50%);
    left: 50%;
    margin: 0 auto;
    text-align: center;
    font-weight: 500;
    font-size: 2em;
    height: 50vh;
    color: rgb(240, 240, 240);
    overflow: hidden;
}

#lyrics .active {
    color: cornsilk;
    font-weight: 600;
    font-size: 1.2em;
}

A: What about it:
#lyrics {
background-color: rgba(0, 0, 0, 0.45);
position: fixed;
width: 70%;
list-style: none;
top: 50%;
transform: translate(-50%, -50%);
left: 50%;
margin: 0 auto;
text-align: center;
font-weight: 500;
font-size: 2em;
height: 50vh;
color: rgb(240, 240, 240);
overflow: hidden;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;

}

A: 0While you are trying to change the positioning of the text in correspondence to the song, which involves the use of time, you certainly need Javascript; but if you're asking only about changing the positioning of text, then-

*

*wrap the active div around the next line

*change the value of the top tag to a negative pixel value/percentage

For example, if you want the next line of the song highlighted, this is the code:

body {
    background: #252525;
    font-family: 'Roboto', sans-serif;
    color: white;
}

#box {
    background-color: rgba(0, 0, 0, 0.45);
    position: fixed;
    width: 70%;
    top: 50%;
    transform: translate(-50%, -50%);
    left: 50%;
    margin: 0 auto;
    text-align: center;
    font-weight: 500;
    font-size: 2em;
    height: 50vh;
    color: rgb(240, 240, 240);
    overflow: hidden;
}
ul {
    position: relative;
    top: -15%;
    list-style: none;
}

#lyrics .active {
    color: cornsilk;
    font-weight: 600;
    font-size: 1.2em;
}

You know, everybody's been tellin' me what they think about me for the last few months

It's too loud

Maybe it's time I tell 'em what I think about them

There are some changes I have made to the code. I have wrapped the ul around a div by the id box. I have transferred all the CSS properties of the id lyrics to box and to the ul, I have made its position relative(relates not to the main screen but to the box inside which it is) and have set a negative value to the top attribute, in order to move the text upwards, making the next line visible.
Note: I have set -120% based on its preview. If in case you want a full page result change it to something like -20% or -15%.

I hope this is what you asked for and that it helps.


text:
Q: How to replace click function with span id I'm working on a jquery dropdown menu. (demo here)
And what I needed to do is to get the full path of what the users choose and to validate that there's no more options to the right.
The original idea (before dropdown menu, with just regular li/ul) was accomplished with this fiddle
As you can see, there's validation and a full path variable for later usage.
Now, what I'd like to achieve is the same thing with the drop down menu.
This is the code in which I fill a Label with the Users' choice based on the Dropdown Menu.
<asp:Label ID="LabelMenu" text="" runat="server" />

As you can see, the span id menuSelection is the one getting the result.
So my question is. How can I replace the click function shown on the fiddle, for the menuSelection result?
The goal is to get full path and validation once the user has chosen a field from the Dropdown Menu
Regards.

A: You can use the change event instead of click
$("select").on('change' , function() {

A: I might misunderstood you but this would at least give you an idea.
resources:
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />

html:

My Span List

jQuery:
$(document).ready(function(){
    // Flag to prevent multiple insertion
    var flag = false;
    $("#menuSelection").click(function() {
        // Prevent inserting more than 1 menu
        if (flag == false) {
            // Your menu
            $('

First Level 1

FL1 Second Level 1

FL1 Second Level 2

First Level 2

FL2 Second Level 1

FL2 SL1 Third Level 1

FL2 Second Level 2

FL2 SL2 Third Level 1

FL2 Second Level 3

First Level 3

FL3 Second Level 1

FL3 SL1 Third Level 1

FL3 SL1 Third Level 2

FL3 Second Level 2

FL3 Second Level 3

FL3 SL3 Third Level 1

First Level 4

'
             ).insertAfter($(this)).menu().focus().focusout(function() {
                // When out of menu remove this instance
                $(this).empty().remove();
                // Flag false again
                flag = false;
            });
            // Find which menu item is clicked
            $('#mylist a').click(function() {
                var route=$(this).parent().text();
                if($(this).next().length==0){
                    alert('no more levels');
                    alert(route);
                    $('#LabelMenu').text(route);
                }else{
                    alert(route);
                    $('#LabelMenu').text($(this).text());
                }
            });
        }
        // Change flag on click
        flag = true;
    });
});

fiddle: http://jsfiddle.net/BerkerYuceer/gp6H5/

A: $('element.selector').on('click', function(event) {
      event.preventDefault();
      // your logic
});

A: Is there a way you can assign IDs to the menu items at all the levels. If so, these IDs can be progressive. i.e. in the main menu ids can be 1,2,3,4,5,6. And if 3,4,5 extend further then the child menu can have entries like (3_1, 3_2, 3_3), (4_1, 4_2) and so on.
This way when you finally select an element, you can use the ID to get the full qualified path of from where you traversed to this option.
This will only work out if somehow you can push ids to all the li elements.

A: can make change in your plugin file there is function this.chooseItem their you can write your stuff
      this.chooseItem = function(item){
    menu.kill();

    //your custom code should go here:

    $('#menuSelection').text($(item).text());
    location.href = $(item).attr('href');
};


text:
Q: Android Google People API error: TokenResponseException: Missing parameter: code I've used up my way. I followed the tutorial(part 1 and 2) to use Google People API in my android project. It always hit an error saying parameter code is missing in the signed apk, and stucked at getting GoogleTokenResponse. It works fine in the debug version. What did I do wrong?
And I have done all these:

*

*Changed SHA1 to released version.

*Replace downloaded google-services.json file downloaded from Firebase.

*Client ID and Client Secret using OAuth Client ID for web

*Invalidate caches/Restart.

*Delete and recreate credential.

Google Sign In class:
public void Google_signIn() {

        //migrate to people api
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                // The serverClientId is an OAuth 2.0 web client ID
                .requestServerAuthCode(Constants.Google_Client_ID)
                .requestEmail()
                .requestScopes(new Scope(Scopes.PLUS_LOGIN),
                        new Scope(PeopleScopes.USERINFO_EMAIL))
                .build();

        if (mGoogleApiClient == null) {

            mGoogleApiClient = new GoogleApiClient.Builder(activity)
                    .enableAutoManage(activity /* FragmentActivity */, this /* OnConnectionFailedListener */)
                    .addOnConnectionFailedListener(this)
                    .addConnectionCallbacks(this)
                    .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                    .addApi(LocationServices.API)
                    .build();
        }

        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        activity.startActivityForResult(signInIntent, GOOGLE_SIGN_IN);
    }

Handler result after signing in successfully:
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
            new PeoplesAsync().execute(result);
        }

PeoplesAsync:
class PeoplesAsync extends AsyncTask<GoogleSignInResult, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(GoogleSignInResult... params) {

            GoogleSignInAccount acct = params[0].getSignInAccount();
            JSONObject userInfo = new JSONObject();

            try {

                //basic profile information
                String G_id = acct.getId();
                String G_email = acct.getEmail();
                String G_name = acct.getDisplayName();
                String G_url = acct.getPhotoUrl().toString();//profile img

                userInfo.put(AccountCenter.ACC_ID, G_id);
                userInfo.put(AccountCenter.ACC_NAME, G_name);
                userInfo.put(AccountCenter.ACC_EMAIL, G_email);
                userInfo.put(AccountCenter.ACC_PROFILE_IMAGE, G_url);

                //problem here
                //additional profile information
                com.google.api.services.people.v1.People peopleService = PeopleHelper.setUp(activity, acct.getServerAuthCode());

                com.google.api.services.people.v1.model.Person profile = peopleService.people().get("people/me")
                        .setRequestMaskIncludeField("person.genders,person.urls,person.birthdays").execute();

                if (!profile.isEmpty()) {

                    List<Url> urls = profile.getUrls();
                    List<Gender> genders = profile.getGenders();
                    List<Birthday> birthdays = profile.getBirthdays();

                    String G_link = urls.get(0).getValue();
                    String G_gender = genders.get(0).getValue();
                    Date bday = birthdays.get(0).getDate();
                    String G_birthday = String.format("%02d", bday.getDay()) + "-" + String.format("%02d", bday.getMonth()) + "-" + String.format("%04d", bday.getYear());// check: year will be 0000 if not shown, can be null ?

                    userInfo.put(AccountCenter.ACC_URL, G_link);
                    userInfo.put(AccountCenter.ACC_GENDER, G_gender);
                    userInfo.put(AccountCenter.ACC_BIRTHDAY, G_birthday);
                }

                AccountCenter.setUserInfo(activity, userInfo.toString(), Constants.ACCOUNT_TYPE_GOOGLE);
                memberSocialLogin(activity, userInfo, Constants.ACCOUNT_TYPE_GOOGLE, Constants.PROVIDER_NAME_GOOGLE);

            } catch (IOException ie) {
                ie.printStackTrace();
                return ie.toString();
            } catch (Exception e) {
                e.printStackTrace();
                return e.toString();
            }

            return "1";
        }

        @Override
        protected void onPostExecute(String response) {
            super.onPostExecute(response);

            if (!response.equals("1")) {
                GeneralMethods.hideProgressDialog();

                if (mGoogleSignedInListener != null) {
                    mGoogleSignedInListener.onError(response);
                }
            }
        }
    }

PeopleHelper:
public class PeopleHelper {

    private static final String APPLICATION_NAME = "Grapps";//any name

    public static People setUp(final Context context, String serverAuthCode) {

        String progress = "0%";

        try {

            HttpTransport httpTransport = new NetHttpTransport();
            JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

            // Redirect URL for web based applications.
            // Can be empty too.
            String redirectUrl = "";

            progress = "10%";

            //problem here
            // Exchange auth code for access token
            GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(
                    httpTransport,
                    jsonFactory,
                    Constants.Google_Client_ID,
                    Constants.Google_Client_Secret,
                    serverAuthCode,
                    redirectUrl).execute();

            progress = "40%";

            // Create a GoogleCredential object using the tokens from GoogleTokenResponse
            GoogleCredential credential = new GoogleCredential.Builder()
                    .setClientSecrets(Constants.Google_Client_ID, Constants.Google_Client_Secret)
                    .setTransport(httpTransport)
                    .setJsonFactory(jsonFactory)
                    .build();

            progress = "60%";

            credential.setFromTokenResponse(tokenResponse);

            progress = "80%";

            // credential can then be used to access Google services
            return new People.Builder(httpTransport, jsonFactory, credential)
                    .setApplicationName(APPLICATION_NAME)
                    .build();

        } catch (IOException e) {

            final String finalProgress = progress + "\n" + e.toString();

            Handler handler = new Handler(context.getMainLooper());
            handler.post(new Runnable() {
                public void run() {
                    GeneralMethods.showAlert(context, "Error setting up People", finalProgress);
                }
            });

            return null;
        }
    }

}

A: If there aren't issues in Google Console and code, try look into Android project setting, set minifyEnabled false in build.gradle might help.
buildTypes {
    release {
//            minifyEnabled true
//            shrinkResources true
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}


text:
Q: How do I make my submit button red when my submit form is not filled out? I have a form on my person website for people to contact me even if they just want to talk. Right now you can submit it without anything & I don't want it to get spammed or filled out with crap. I'm trying to figure out how to only let the user submit with everything filled out & if it's not don't let them send it & the button turns red. Ranting because "I have too much code, & not enough information. If I can keep  it CSS & HTML only I'd be happy but I understand there are limits so JS or jQuery is sometimes needed. I understand them quite well, I just like to challenge myself. Anyway, I'm pretty much ranting because "I have too much code & should try to add some information to my post."....
Here is my code with HTML5 & CSS3:
HTML Here

I love pen pals!

    —
    <form class="form" id="form1">

        <input name="name" type="text" class="validate[required,custom[onlyLetter],length[0,100]] feedback-input" placeholder="Name" id="name" />

        <input name="email" type="text" class="validate[required,custom[email]] feedback-input" id="email" placeholder="Email" />

        <textarea name="text" class="validate[required,length[6,300]] feedback-input" id="comment" placeholder="Comment"></textarea>

        <input type="submit" value="SEND"/>

    </form>

CSS Here
     .container {
  width: 1000px;
  margin-left: auto;
  margin-right: auto;
  font-family: 'Monserrat', sans-serif;
}

.contact {
  background: white;
  margin: 5%;
  text-align: center;
}

.contact h3 {
color: rgba(144, 198, 149, 0.8);
}

.contact span {
color: rgba(144, 198, 149, 0.8);
}

.contact form {
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  background: white;
  width: 50%;
}

.name {

}

.name input {
  border: none;
  border-bottom: 1px solid #e4e4e4;
  margin: 5% 0% 5% 0%;
  width: 100%;
  background: white;
}

::-webkit-input-placeholder {
    color: rgb(189,195,199);
}
:-moz-placeholder {
   color: rgb(189,195,199);
   opacity:  1;
}
::-moz-placeholder {
   color: rgba (189, 195, 199);
   opacity:  1;
}
:-ms-input-placeholder {
   color: rgba (189, 195, 199);
}

.email {

}

.email input {
  border: none;
  border-bottom: 1px solid #e4e4e4;
  margin: 5% 0% 5% 0%;
  width: 100%;
  background: white;
}

.text {

}

.text textarea {
  border: none;
  border-bottom: 1px solid #e4e4e4;
  margin: 5% 0% 5% 0%;
  width: 100%;
  background: white;

}

.submit {
  margin-left: auto;
  margin-right: auto;
background: rgba(189, 195, 199, 1);
border: 0 none;
cursor: pointer;
-webkit-border-radius: 5px;
border-radius: 5px;
  color: white;
}

input[type=submit] {
    width: 100%;
background: transparent;
border: 0 none;
padding: 5px 15px;
border-radius: 5px;
 color: white;
}

input, select, textarea{
    color: rgba(144, 198, 149, 0.8);
}

textarea:focus, input:focus {
    color: rgba(144, 198, 149, 0.8);
    border: 1px solid rgba(144, 198, 149, 0.8);
}

.to-the-right {
  display: inline-block;
  vertical-align: middle;
  -webkit-transform: translateZ(0);
  transform: translateZ(0);
  box-shadow: 0 0 1px rgba(0, 0, 0, 0);
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
  -moz-osx-font-smoothing: grayscale;
  position: relative;
  -webkit-transition-property: color;
  transition-property: color;
  -webkit-transition-duration: 0.3s;
  transition-duration: 0.3s;
  border-radius: 5px;
  color: white;
}
.to-the-right:before {
  content: "";
  position: absolute;
  z-index: -1;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  color: white;
  background: rgba(144, 198, 149, 0.8);
  -webkit-transform: scaleX(0);
  transform: scaleX(0);
  -webkit-transform-origin: 0 50%;
  transform-origin: 0 50%;
  -webkit-transition-property: transform;
  transition-property: transform;
  -webkit-transition-duration: 0.3s;
  transition-duration: 0.3s;
  -webkit-transition-timing-function: ease-out;
  transition-timing-function: ease-out;
  border-radius: 5px;
}
.to-the-right:hover, .to-the-right:focus, .to-the-right:active {
  color: white;
}
.to-the-right:hover:before, .to-the-right:focus:before, .to-the-right:active:before {
  -webkit-transform: scaleX(1);
  transform: scaleX(1);
}

A: You can use the :valid (and :invalid) attribute in CSS as a selector that applies styles when all form elements are valid.

form:invalid [type=submit] {
  background:red;
}

form:valid [type=submit] {
  background:lime;
}
<form>
  <input required>
  <input type="submit">
</form>

A: Add a class to your .css file like this:
  .red
{
    background-color:red;
}

Use jQuery .blur on each field and check if the field is empty or not: (let's suppose that the id of your submit button is send.
 $('#filed1').blur(function() {
        if($("#field1").val() == "" || $("#field1").val() == null){
            $('#send').addClass('red');
    }else{
         $('#send').removeClass('red');
         }
    });

That should work.


text:
Q: Problem with PHP autoload I am trying to use autoload to load a class on a file but it keeps giving me this error warning message below. What can I do differently ?
The code on the autoload file is:
<?php
function my_autoload($class) {
    if(preg_match('/\A\w+\Z/', $class)) {
        include 'classes/'. $class.'.class.php';
    }
}

spl_autoload_register('my_autoload');

$bike = new Bicycle;
$bike->brand = 'Trek';
echo $bike->brand;
?>

The code on the file the autoload is to access is:
class Bicycle {

  var $brand;
  var $model;
  var $year;
  var $description = 'Used bicycle';
  var $weight_kg = 0.0;

  function name() {
    return $this->brand . " " . $this->model . " (" . $this->year . ")";
  }

  function weight_lbs() {
    return floatval($this->weight_kg) * 2.2046226218;
  }

  function set_weight_lbs($value) {
    $this->weight_kg = floatval($value) / 2.2046226218;
  }

}

The error message I am getting is:
[17-Nov-2020 10:13:50 UTC] PHP Warning:  include(classes/Bicycle.class.php): failed to open stream: No such file or directory in /home/gabng/public_html/autoload.php on line 4
[17-Nov-2020 10:13:50 UTC] PHP Warning:  include(): Failed opening 'classes/Bicycle.class.php' for inclusion (include_path='.:/opt/alt/php72/usr/share/pear') in /home/gabng/public_html/autoload.php on line 4
[17-Nov-2020 10:13:50 UTC] PHP Fatal error:  Uncaught Error: Class 'Bicycle' not found in /home/gabng/public_html/autoload.php:10
Stack trace:
#0 {main}
  thrown in /home/gabng/public_html/autoload.php on line 10


text:
Q: Android Activity create and start I'm currently writting an app for Android. I'm trying to figure out the best place to catch on intent when the activity is created for the first time.
public class DisplayAct extends Activity {

    private Intent mNewIntent;
    private ViewFinderFragment mViewFinderFrag;
    public boolean toot;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState)
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        setContentView(R.layout.activity_display);

        if(savedInstanceState != null) {
            Intent intent = getIntent();
            if (intent != null) {
                String action = intent.getAction();
            }
     }

This is how I get the intent.
I was wondering if grabbing the intent at oncreate is good or it's better to add onStart and add this action inside in term of design perspective.
Thanks

A: If you app is open, handle it with onNewIntent. If you app is closed, you wanna use your Bundle that comes with your Intent.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState.getString(MY_ACTION)) {
        // Do something
    }

EDIT:
I set this action as a String to the Intent's Bundle. I performed it with the code below:
Bundle bundle = new Bundle();
bundle.putString(MainActivity.MY_ACTION, "MY_ACTION");
Intent intent = new Intent(this, MainActivity.class);
intent.putExtras(bundle);


text:
Q: Rails ajax request response I am using Rails CoffeeScript to call an action in my controller, which is fine, but I can not get the response to work.
I have a form with a list of budget lines. I want to allow the use to add a new line using CoffeeScript so I don't need to reload the question.
I have got the following in CoffeeScript:
  $("button[id^='new_budget_line']").on 'click', (event) ->
    category_id = $(this).attr('name')
    child_economy_id = $('#child_economy_id').val()
    $('#form_id').submit ->
      valuesToSubmit = $(this).serialize()
      $.ajax
        type: 'POST'
        url: $(this).attr('action')
        data: valuesToSubmit
        dataType: 'JSON'
    $.ajax({
      type: 'GET'
      url: '../child_economy_lines/create_line'
      data:
        child_economy_id: child_economy_id
        category_id: category_id
        cost_type: 'direct'
      dataType: JSON
    }).done (response) ->
      alert "Hey"
      $('#test_append').html("Hey you now!!")

And the following in my controller
  def create_line
    logger.debug "Hejsa fra create line - category id #{params[:category_id]}"
    @child_economy_line = @child_economy.child_economy_lines.build(:child_economy_category_id => params[:category_id], :cost_type => params[:cost_type])
    if @child_economy_line.save
      respond_to do |format|
        format.js {render nothing: true}
        format.json {render :json => "test"}
      end
    end
  end

The action in the controller i called fine, and the new line is created, but I can not the actions after the ajax call to work. The part from .done ...
Can anybody help me identify where it is going wrong?


text:
Q: The Stack Exchange Data Explorer intermittently goes down Since Sunday, I expect after the refresh of 03:00 UTC, the Stack Exchange Data Explorer seems to have troubles serving pages to us.
I notice that I'm either logged out frequently, I get the red error box that something went wrong with executing my query or I'm presented with the maintenance page.
Retrying my action and/or refreshing seems to resolve the issue somewhat until the next hiccup.
There are reports from other users that experience the same problems. And some users report no issues. That indicates the intermittent nature of the problem.
I think that SEDE instance needs a hug so it feels happy again. Can someone take the bike-ride to the data-centre and apply the needed love?

A: TL;DR; This should be fixed in the next 8-24 hours as we had to block a bot scraping us.

Longer version:
I noticed the flapping over the weekend and started investigating yesterday. My first guess was a SQL issue. After some initial digging, I made some server level changes to see if things would stabilize. They did for several hours, but last night I noticed yet another outage, so I grabbed a memory dump for review this morning.
After a whole lot of flapping overnight, Nick and I started reviewing the dumps this morning, well mostly Nick reviewed and I watched. We noticed some threading issues, so we look at the total connections to SEDE to figure out what was hogging all the connections, but nothing really stood out, so we turned to our Traffic Logs and we found the issue.
We initially queried the logs for the last couple of days and saw we were being crawled by Applebot. Crawled is an understatement, we were getting slammed by it.
Here are some stats of traffic from the Applebot and everyone else to give an idea on scale - the outages started on 2020-08-16 between that date to today (2020-08-18) we had:
Applebot  |  Non-Applebot Traffic
---------------------------------
1484480   |  290063

We've added the Applebot the robots.txt to stop the crawling. It'll take a little while for that to take hold, so we might have a little more flapping of SEDE, but we'll be monitoring it and will kick as needed.


text:
Q: What is your company's policy on using Stack Overflow at work? Obviously, Stack Overflow is a great tool whether you are just striving to increase your programming skills, or working on a home pet project that's going to turn into the next Twitter, or get free help on your freelance project, or even to find the best solutions to your development problems at your IT job in Corporate America.
However, the downside to S.O. is that you might end up spending countless hours on S.O. during work hours (without even realizing it until it's too late!) trying to boost your "Reputation," and that could mean lost productivity.
I think Chacha102's saying sums this up the best.
Nevertheless, one could still justify trolling S.O. for hours if doing so also helps you solve a problem at work in hours instead of days or minutes instead of hours.
So my question is, do your companies realize that you are spending time on S.O. or ask/answer questions, and if so, how do they feel about it?  Of the companies that are aware of the issue, do they impose a daily limit?  Encourage/discourage using it during work hours?  Does anyone's company go so far as to block the domain on their proxy?
And for extra credit, do you think there is a net increase or decrease in productivity from getting great answers quickly or due to spending too much time on it (respectively) from using S.O?  If anyone has any data on this issue, that would be wonderful, but I'm interested in your opinions on this matter too.
Thanks!

A: Encouraged 200%. I'm well known for saying "I think I saw that on SO, did you search there?" Counting myself, there are three SO users above 5k rep working at my company. Several more search it, but aren't comfortable participating due to a bit of a language barrier.
Too much of a good thing can be toxic though. I don't mind people answering a few questions to break up the monotony of the day, as long as they remain productive and focused on the task at hand.
We basically trust that people naturally want to do their job and don't really restrict their browsing, beyond visiting sites that might offend people that may glance at their monitor, hogging all the bandwidth, etc.
I found that trying to place restrictions on resources just ends up in people finding creative ways around those restrictions, which means more time spent not working.
I should also add, almost 99% of what we work on is open source to begin with. People are educated to not share proprietary code, and in two years with this policy, its never been a problem.

A: Quite frankly, I get most of my time on Stack Overlow and Meta while waiting for my code to compile. It would be time wasted fiddling around on a text editor or doing nothing, so I may as well be productive.
The IT head knows I used Stack Overflow (he saw it with remote desktop, and his assistant said he loves the place), but I've heard no complaints. Besides, I've gotten much better answers and fixed more problems with SO in two weeks of usage than I had for 4 years of using Experts-Exchange.
So I don't think they have a real problem with it. I'm still ahead of the production schedule even with the time spent here.

A: My company knows about SO.  I know, because I can look around on everyone's pc and see them looking up information on it all the time.
The way I diffused any situation about me being on it was simple.  When Telerik was giving away free controls to uses with over 10k, I sent it to the VP and said, "Hey didn't know if you were aware of this, but Telerik is giving away free stuff to people who qualify.  Thought I would pass it along in case we could get stuff."  This immediately registered to him as, "If I participate in the community, I get stuff back."  No one has said anything to me since.
If it ever comes up again, my response will be: "You know all those answers you get from that site....well someone has to put them there.  It's in your best interests to support the community, because it takes me 2 minutes to answer a question, and it potentially saves the company hours by having a dev quickly find one there."

A: I'm a statistician working for a hospital, so my perspective might be bit different than most.  I don't think my supervisor knows that I use SO, but I'm certain it's monitored by IT.  But... I just take it on good faith that my IT geeks will see my usage and say, "Rock on, old boy.  I have no freaking idea what this R thing you're always posting about is, but rock on."
There's also an organization-wide emphasis on continuing training, so it would be hard for them to get on my case about spending time on SO when they would happily excuse me from work to go to a SAS Users Group meeting (bleargh).
The 'amount of time spent vs. return' issue is a little different for me, however.  I can't sink hours and hours into the site - I mainly follow the R, SAS and statistics tags, which together probably get about 5-6 questions per day, and where every question is likely to be reviewed by an expert user (the R questions, anyway).  It takes me about five minutes to read every question, and most of them are answered very well by the time I get to them.
I'm learning Python, which could be a dangerous development.

A: It's required. :-)

A: No. They aren't aware of it.
No. I don't plan on telling them.
If they do ask, I'll give them the same answer I give you:
Practice, Practice, Practice. Stack Overflow lets me practice my craft while I'm waiting for this virus-scanner-ridden, websense-enabled, and LANDesk Management-filled computer to catch up with me and my Work.

A: When SO was in beta, I probably did a bit more than "healthy" amounts of involvement to help get things off the ground. Since then my participation has died down, but I've been letting all the developers around here know about it since it is such a great resource.
What is particularly fun is when they have questions and I can point them to an answer I had marked as right. 8^D
We don't have any official policy, but if for some reason websense comes through and blocks it, I'll be talking to the director. 8^D
As is with most things: everything in moderations does the soul good.

A: If you're a programmer, be a little careful if your company doesn't know what you're doing and you say you work for them in the profile.  I got in a little hot water for a different forum where our client saw our company next to my name saying that we knew about a bug in our software which someone else in the company was clueless about.
Disregard this if you work for Microsoft.

A: I can see that it could be a problem (like falling in the C2 Wikihole) - but I don't think I'd stay at a job that wouldn't let me use SO, it's just too useful.


text:
Q: Redirect URLs containing specific string to https I want to redirect my member registration URLs to HTTPS using htaccess. So:
http://example.com/product/register/*
...And any pages under that such as:
http://example.com/product/register/details
http://example.com/product/register/payment
I tried the following, but I'm not sure I'm even on the right track:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond $1 ^(register/*) [NC]
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Any help appreciated.

A: Have it this way:
RewriteEngine On

RewriteCond %{HTTPS} off
RewriteCond %{THE_REQUEST} /product/register/ [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]


text:
Q: How can I handle errors using ActionBuilder, and Action composition?
I have two Actions:
object ErrorHandler extends
    ActionBuilder[Request]{
  def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = {
    try {
      block(request)
    } catch {
      case ex: Throwable => Future.successful{
        InternalServerError(
          Json.obj(
            "status" -> JsString("error")
          )
        )
      }
    }
  }
}

And another action:
object WithFieldAction extends
    ActionBuilder[WithFieldRequest] with ActionTransformer[Request, WithFieldRequest] {

  val FIELD = "field"

  def transform[A](request: Request[A]) = Future.successful {
    new WithFieldRequest(request.getQueryString(FIELD), request)
  }
}

I combine this actions:
def index = (ErrorHandler andThen WithFieldAction) { implicit request =>
  1 / 0
}

But ErrorHandler doesn't catch the exception and I see the default error page. How can I fix it? (I can't use the Global error handler because I want to have different handlers for different groups of endpoints)

A: The problem is that the exception is thrown within the Future and held. That means that when you call block(request), it's just going to return a Future[Result] that wraps the eventual exception (a failed Future). The Future should never let the exception escape it, so wrapping in try/catch won't do anything.
Instead, you need to recover the Future.
def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = {
  block(request) recover { ex: Throwable =>
    InternalServerError(
      Json.obj(
        "status" -> JsString("error")
      )
    )
  }
}

recover accepts a PartialFunction[Throwable, ?], so you can be as fine-grained about the exceptions you handle as you want. For example, you could recover only java.lang.ArithmeticException, and let all other failures propagate to Play's error handling if you wish.


text:
Q: Named Function Expression : Difference between var bar = function () {} & var bar = function foo(){} Can any one help in understanding the difference between following two function expressions:
a) var bar = function() {};
b) var bar = function foo() {};

I have been writing the way it has been written in a).
What is the importance of giving function name as "foo" in b)?
How is a) different from b)?

A: Method a: a variable named bar that refers to the anonymous function. function can only be used by using the variable bar wherever it is in scope.
Method b: a variable name bar that refers to a named function foo. foo can still be used by name anywhere it is in scope along with using bar as well.
As Paulpro mentioned - foo is only in scope inside the function itself, nice for recursive functions.

A: Naming a function may not affect the code, but it's useful for debugging and in constructor functions, it defines the name of the prototype.


text:
Q: GraphViz - How To Draw These Edges Heylo, I just wanted to see if edges like the ones I've mocked up in the image below (in blue/cyan) are possible... I've tried a lot of different combinations of edge attributes and I'm really struggling on getting the edges to look clean and organized and not taking the shortest path possible.

My code is as follows and I do not want the subgraphs to move from their current positions so I know a 'constraint = false' will be required for the edges.
digraph G
{
    graph [compound = true];
    splines = false;
    node [style = bold, shape = record, fontcolor = magenta];

    subgraph cluster0
    {
        style = bold; label = "Mac";
        edge [style = invisible, arrowhead = none];
        "Finder" -> "Terminal" -> "Safari";
    }

    subgraph cluster1
    {
         style = bold; label = "Windows";
         node_1 [label = "<f0> Start|<f1> Command Prompt"];
    }

    subgraph cluster2
    {
         style = bold; label = "Linux";
         node_2 [label = "<f0> Start|<f1> Konsole"];
    }
}

Thank you in advance!

A: I don't have a direct answer, but PlantUML sits on top of GraphVis and generates edges similar to what you're looking for -- so you may be able to generate the .dot file ( see the second example under Conditional ), inspect the edges there.


text:
Q: How does this recursive code change my list? i have tried  running and debugging  the following code in IntellIj in order to track what each line of my code does but i still dont understand the result.
public static void testMyFun() {

  List<Integer> xs = new ArrayList<Integer>();

  for (int i = 0; i < 5; i++)
    xs.add(i);

  myFun(xs,2);

  System.out.println(xs);
}

public static <A> void myFun (List<A> xs, int n) {
  if (n > 0) {

    A x = xs.get(0);

    xs.remove(0);

    xs.add(x);

    myFun(xs, n-1);
}

The result that i get is [ 2,3,4,0,1]
How does 0 and 1 go to the end of the list?

A: Because you've set n as 2. So essentially myFun() will be executed twice at most. myFun() is removing the first element of the list and re-adding it to the back. Since this can only occur twice, the first two element (0 and 1) will be sent to the back of the list.

A: In your code you execute myFun({0,1,2,3,4},2);.
This executes myFun({1,2,3,4,0},1);.
The next myFun executed is myFun({2,3,4,0,1},0);, which immedietly stops.
This is, because you remove the first element and add it at the end(add() appends it at the end)

A: Well
A x = xs.get(0);

xs.remove(0);

xs.add(x);

moves first element to last position
if (n > 0) {

while n is > 0
and you start with
myFun(xs,2);

and recurse call N times due to myFun(xs,n-1);
so you move 2 first element to the end of array

A: The function "myFun " removes n element from the list , then add them again to the list.
The add method add the element in the end of the list.
Because you sent n=2 . myFun  will remove 0,1 fron the "head" of the list and move then to the end of the list.

A: Original  list values:
01234

When n =2 list modified to
12340

When n=1  list modified to
23401

When n reaches 0 recursion will stop.
And items current order in the list will be
23401

A: That's so simple.
Recursive function will be run twice, for n=2 and n=1, when it is 0 if clause don't run and myFun will be finish.


text:
Q: How to calculate the resultant vector The vector $A=5i+6j$ is rotated through an $\angle 45$ about the $Z$ axis in the anticlockwise direction. What is the resultant vector?
My attempt:
I tried to calculate the resultant vector by using the equation,
$R=\sqrt{A^2+B^2+2ABCos\theta} $
since it is rotated in anticlockwise direction its direction changes.
Any hint will be appreciated.

A: HINT
First approach
You can solve it by considering the rotation matrix, where $(x',y')$ are the new coordinates after the rotation:
\begin{align*}
\begin{bmatrix}
x'\\
y'
\end{bmatrix} =
\begin{bmatrix}
\cos\left(\frac{\pi}{4}\right) & -\sin\left(\frac{\pi}{4}\right)\\
\sin\left(\frac{\pi}{4}\right) & \cos\left(\frac{\pi}{4}\right)
\end{bmatrix}
\begin{bmatrix}
5\\
6
\end{bmatrix}
\end{align*}
Second approach
Since $A = 5i + 6j = (5,6)$, you can multiply it by $\exp\left(\frac{\pi i}{4}\right)$.

A: 1) $\vec {i} \rightarrow (1/√2)(\vec {i} +\vec {j})$;
2) $\vec {j} \rightarrow (1/√2)(\vec {-i}+\vec {j})$;
3) $5 \vec {i} +6 \vec {j} \rightarrow $
$(1/√2)(-1)\vec {i} +(1/√2)(11)\vec {j}$.


text:
Q: Angular 2 How to preselect an option in select if ngModel value is null I have the following code which populates correctly. But how do I preselect my "None" option if orderDetail.people value is null? At the moment I just get all the options with a blank option preselected.
<select id="people" [(ngModel)]="orderDetail.people" name="people" #people>
    <option value="">None</option>
    <option *ngFor="let item of people" value="{{item.id}}">{{item.firstName}} {{item.lastName}}</option>
</select>


text:
Q: How to check are there any records in recordset in VBA? Could you help me, please. I have a database in Access and a program written in Delphi (I've used the library Ehlib), which I'm trying to rewrite in the VBA.
with CustomDriver do
  try
    with SelectCommand do
    begin
      CommandText.Text := 'select count(*) from OBJ_APP a' + ^M +
                          'where ID_App = :AID_App and exists (select 1 from obj_app b where b.ID_Obj = a.ID_Obj and b.ID_App = :AID_App_Replace)';
      Parameters.ParamByName('AID_App').Value := AID_App;
      Parameters.ParamByName('AID_App_Replace').Value := AID_App_Replace;
    end;
    vFree := True;
    ExecuteCommand(SelectCommand, DsReplace, vFree);
if (DsReplace <> Nil)
and(DsReplace.RecordCount > 0)
and(DsReplace.Fields[0].AsInteger > 0) then

How do I write the last three lines of code in VBA? And is there an easier way to write double quotes than & Chr (34) &?

A: You only need to check for .EOF after opening a recordset.
Set rs = CurrentDb.OpenRecordset("SELECT * FROM foo")
If Not rs.EOF Then
    If rs(0) > 0 Then
    ' or if you want to be explicit
    If rs.Fields(0).Value > 0 Then

Double quotes are masked by doubling them:
Debug.Print "Hello ""World"""

But usually you can make your code better readable by using single quotes:
strSQL = "SELECT * FROM foo WHERE bar = 'something'"

A: You can also check RecordCount:
Set rs = CurrentDb.OpenRecordset("Select * From YourTable")
If rs.RecordCount > 0 Then
    ' At least one record exists.
    ' Do stuff.
End If

A: All answers are wrong.
Wrong, cause ...
1. Before records counting the recordset must be populated!
2. It's strongly NOT recommended to directly use of CurrentDb
sSQL = "SELECT * FROM foo"

Set cdb = CurrentDb
Set rst = cdb .OpenRecordset(sSQL)

With rst
    Select Case (.BOF And .EOF)
        Case True
            lCnt = 0
        Case False
            .MoveLast: .MoveFirst
            lCnt = .RecordCount
    End Select
End With

Call rst.Close
Set rst = Nothing

Call cdb.Close
Set cdb = Nothing

.


text:
Q: 'RelationshipProperty' object has no attribute 'c' error in sqlalchemy I'm having a lot of trouble implementing SQLalchemy for a legacy MSSQL database. It is a big existing database, so I wanted to use sqlautocode to generate the files for me, because using autoload to reflect the database takes too long.
The first problem was that sqlautocode no longer seems to work on SQLalchemy 0.8. I did still have existing output from an earlier version, so I thought I'd use that, just to test with.
Now sqlautocode outputs the 'classical mapping', which is not really a problem, but whenever I tried to use a foreign key, 'RelationshipProperty' object has no attribute 'c' would show up. An error somewhere deep inside the SQLalchemy library.
So next, I tried just skipping sqlautocode and writing the classes and relations myself, going by this code for SQLalchemy 0.8. I used two example tables and I got the exact same error. Then I commented out most of the columns, all of the relations and I -STILL- get the error.
Below is my code:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, ForeignKey
from sqlalchemy.orm import relationship, backref
from sqlalchemy.dialects.mssql import *

Base = declarative_base()

class PeopleMemberhip(Base):
    __tablename__ = 'people_memberships'

    ppl_mshp_id = Column(VARCHAR(length=36), primary_key=True, nullable=False)
    ppl_mshp_startdate = Column(DATETIME())
    ppl_mshp_enddate = Column(DATETIME())
    # ppl_mshp_pmsd_id = Column(VARCHAR(length=36), ForeignKey('paymentschedules.pmsd_id'))

    # paymentschedule = relationship("PaymentSchedule", backref=backref('people_memberships'))

    def __repr__(self):
        return "<people_membership('%s','%s')>" % (self.ppl_mshp_id, self.ppl_mshp_startdate)

class PaymentSchedule(Base):
    __tablename__ = 'paymentschedules'

    pmsd_id = Column(VARCHAR(length=36), primary_key=True, nullable=False)
    pmsd_name = Column(NVARCHAR(length=60))
    pmsd_startdate = Column(DATETIME())
    pmsd_enddate = Column(DATETIME())

    # paymentschedule = relationship("PaymentSchedule", backref=backref('people_memberships'))

    def __repr__(self):
        return "<paymentschedule('%s','%s')>" % (self.pmsd_id, self.pmsd_name)

And the resulting Error:
Traceback (most recent call last):
  File "C:\Program Files (x86)\JetBrains\PyCharm 2.7\helpers\pydev\pydevd.py", line 1472, in <module>
    debugger.run(setup['file'], None, None)
  File "C:\Program Files (x86)\JetBrains\PyCharm 2.7\helpers\pydev\pydevd.py", line 1116, in run
    pydev_imports.execfile(file, globals, locals) #execute the script
  File "C:/Users/erik/workspace/flasktest/test.py", line 16, in <module>
    contract = db.session.query(PeopleMemberhip).filter_by(ppl_mshp_id='98ABD7E9-4CFF-4F7B-8537-8E46FD5C79D5').one()
  File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\scoping.py", line 149, in do
    return getattr(self.registry(), name)(*args, **kwargs)
  File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\session.py", line 1105, in query
    return self._query_cls(entities, self, **kwargs)
  File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\query.py", line 115, in __init__
    self._set_entities(entities)
  File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\query.py", line 124, in _set_entities
    self._set_entity_selectables(self._entities)
  File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\query.py", line 157, in _set_entity_selectables
    ent.setup_entity(*d[entity])
  File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\query.py", line 2744, in setup_entity
    self._with_polymorphic = ext_info.with_polymorphic_mappers
  File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\util\langhelpers.py", line 582, in __get__
    obj.__dict__[self.__name__] = result = self.fget(obj)
  File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\mapper.py", line 1425, in _with_polymorphic_mappers
    configure_mappers()
  File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\mapper.py", line 2106, in configure_mappers
    mapper._post_configure_properties()
  File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\mapper.py", line 1242, in _post_configure_properties
    prop.init()
  File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\interfaces.py", line 231, in init
    self.do_init()
  File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\properties.py", line 1028, in do_init
    self._setup_join_conditions()
  File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\properties.py", line 1102, in _setup_join_conditions
    can_be_synced_fn=self._columns_are_mapped
  File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\relationships.py", line 115, in __init__
    self._annotate_fks()
  File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\relationships.py", line 311, in _annotate_fks
    self._annotate_present_fks()
  File "C:\Users\erik\workspace\flasktest\lib\site-packages\sqlalchemy\orm\relationships.py", line 331, in _annotate_present_fks
    secondarycols = util.column_set(self.secondary.c)
AttributeError: 'RelationshipProperty' object has no attribute 'c'

I'm really at a loss, any help with this error is appreciated, but also if someone can suggest a different approach that can make SQLalchemy work with our legacy MSSQL database it is also a solution.
As I said, sqlautocode doesn't seem to work any more, but maybe I'm using it the wrong way, or maybe there is an alternative tool I don't know about.
Erik

A: Okay guys, figured it out myself.
I had a couple of files I was messing with that had table definitions in them (output from sqlautocode). One was called 'database.py' another 'model.py' and the last one 'ORM.py'.
I had a test.py file that imported 'model.py'. Model.py was the file I had written my table definitions in. However - the test.py page was also importing the database from within Flask (from app import app, db), and in the __init__() function of the Flask app, Flask was still loading 'ORM.py'.
So some of the objects were coming from ORM.py, which was an old file generated by sqlautocode, instead of from model.py, which I was experimenting with.
Renaming ORM.py gave me a clue. I have written a very simple script in Python that traverses through the MSSQL tables and columns and generates a model.py for me.  I exclusively load that model.py file now and the whole thing works!
Sorry if anyone was spending time on this. Hope it helps somebody Googleing for the same problem though.
Erik


text:
Q: I get an arror for map function(posts.map is not a function) I get this error, while I don't see any issue in that:
posts.map is not a function
import React from 'react'
import { useSelector } from 'react-redux'

export const PostsList = () => {
  const posts = useSelector(state => state.posts)

  const renderedPosts = posts.map(post => (

{post.title}

{post.content.substring(0, 100)}

  ))

  return (

Posts

      {renderedPosts}

  )
}

This is my code Sandbox: https://codesandbox.io/s/wandering-darkness-6hi04d?file=/src/features/posts/PostsList.js

A: Your problem in the file store.js
export default configureStore({
  reducer: () => ({
    posts: postsReducer
  })
});

Modify this file as follows :
export default configureStore({
  reducer: {
    posts: postsReducer
  }
});


text:
Q: Lenovo Yoga 900 Internal Microphone Not Working on Ubuntu 18.04 The internal microphone suddenly stopped working in Ubuntu 18.04 on my Lenovo Yoga 900 laptop. It was working for a while before so I suspect some update caused it to stop working.
The internal microphone is detected, but simply picks up no sound (note the input level in this screenshot). I have tried an external microphone and it successfully picks up sound.
My alsa info can be found here.

A: I had the same issue with yoga 920 and ubuntu 18.04, the mic was working on 16.04 but stopped after the upgrade.
I'm not entirely sure how I managed to resolve it though.
Firstly I added load-module module-echo-cancel to the end of /etc/pulse/default.pa and restarted pulseaudio, for no reason really, simply wanted to check whether it would help or not. It didn't.
Then I booted into my windows partition and disabled Dolby through Lenovo Vantage, the on/off switch can be found in the hardware/audio tab.
After I booted back into ubuntu the mic started working. Although maybe the pulseaudio+reboot fixed the mic, and not the Dolby disabling. Later I enabled Dolby back and the mic was still working in ubuntu.


text:
Q: Using an iterator for generic type on a custom class import java.util.*;

public class MyClass<Item> implements Iterable<Item> {
    public Iterator<Item> iterator(){ return new ListIterator();}

    public class ListIterator implements Iterator<Item>{
        ...
    }

    public static void main(String[] args){

    }
}

How can I use this iterator with a generic type? These are the approaches I've tried in my 'main' function:
MyClass <Item> deq = new MyClass();
ListIterator<Item> it = deq.iterator();

Results in: non-static class Item cannot be referenced from a static context
MyClass deq = new MyClass();
ListIterator<Item> it = deq.iterator();

Results in: non-static class Item cannot be referenced from a static context
MyClass deq = new MyClass();
ListIterator it = deq.iterator();

Results in: non-static class Deque2.ListIterator cannot be referenced from a static context
Edit:
I was calling a class instead of a method. This works:
Iterator it = deq.iterator();
I thought since the type of the returned instance in iterator() was ListIterator, I needed to declare with 'it' that type.

A: You've declared your class as
public class MyClass<Item> implements Iterable<Item> {

In its declaration, you are defining a new type variable, Item. This type variable is bound to instances (or rather expressions that resolve to instance reference values).
It can't be used in a static context, because no instance exists in a static context.
As for ListIterator, this is an inner class. It has the same problem as the type variable. It needs an instance to work.


text:
Q: Catch block for exception thrown in a destructor I have some "nested" try catch blocks, split across functions, but essentially it boils down, for classes Foo and Bar, to this:
try {
    for (;;){
        try
        {
            Foo foo;
            try {
                Bar bar;
                if (something){
                    continue;
                }
            } catch (...){
                std::cout << "inner";
            }
        } catch (...){
            std::cout << "middle";
        }
    }
} catch (...){
    std::cout << "outer";
}

Both classes can throw exceptions in their destructors.
If continue is reached then as the stack unwinds, and during the destruction of foo and bar, an exception is thrown, then I'm expecting to print "outer", but it doesn't do that. What is going on?

A: The standard makes this clear:
If a destructor throws an exception then it is caught by the try block in which the variable is defined.
So if ~Bar() throws an exception, then the output is "inner". If ~Foo() throws, then the output is "middle";


text:
Q: What are the commands that firefox and google chrome print html files to pdf? In either Firefox or Google Chrome On Ubuntu 14.04, I can hit Ctrl+P and choose "Print to file" to print the current html webpage to a pdf.
Are the browsers  using some printing commands outside of them to do that?
What are the corresponding commands that run in terminal and do the same? Thanks.


text:
Q: Android: Realm.getInstance(context) returns an already closed realm instance Realm.getInstance(context) will rarely return an already closed realm instance. How is this possible?
I am using Realm with RxJava, per https://realm.io/news/using-realm-with-rxjava/
In particular, this method throws an IllegalStateException: This Realm instance has already been closed, making it unusable.
@Override
    public void call(final Subscriber<? super RealmList<T>> subscriber) {
        final Realm realm = Realm.getInstance(context);
        subscriber.add(Subscriptions.create(new Action0() {
            @Override
            public void call() {
                try {
                    realm.close();
                } catch (RealmException ex) {
                    subscriber.onError(ex);
                }
            }
        }));

        RealmList<T> object;
        realm.beginTransaction(); //THROWS EXCEPTION

        //...
}

If I comment out the realm.close(); issue, no problems. Though I think this will lead into a native memory leak, then.
My best guess as to why this is occurring is that multiple calls to this method are being made, and if these method calls line up perfectly, then an already closed realm instance can be retrieved?
EDIT: By using Schedulers.io(), I get a lot of Calling close() on a Realm that is already closed warnings. My guess here is that somehow after I am done using the .io() thread, the realm instance is automatically closed. Not sure why this would happen though.
EDIT2: By switching to using Schedulers.newThread() instead of Schedulers.io() for my observables, the issue stopped appearing. But I am seeing a lot of Remember to call close() on all Realm instances warnings. I am pretty sure I am closing them, so I am very confused about this.
EDIT3: By switching to using AndroidSchedulers.mainThread(), no errors. Except my Realm calls run on the main thread, which is bad bad bad. My guess why this causes no warnings is because the realm now lives on the main thread, which is also where realm.close() is called (via the rx.subscriber).
EDIT4: Here's the logic for my realm observable call.
@Override
public Observable<List<ImageArticleCategoryEntity>> getArticleBuckets() {

    return RealmObservable.list(context, GET_ARTICLE_BUCKETS)
            .filter(FILTER_OUT_NULL_OR_EMPTY_LIST)
            .switchIfEmpty(refreshAndSaveAndLoadNewDataFromDb)
            .map(CONVERT_FROM_REALMLIST_TO_IMAGE_ARTICLE_ENTITYLIST);

}

public void loadArticleImages() {
    articleRepo.getArticleBuckets()
            .subscribeOn(RealmThread.get())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<List<ImageArticleCategoryEntity>>() {
                @Override
                public void onCompleted() {
                    Timber.v("Loading article images complete!");
                    if (view != null)
                        view.hideLoadingAnimation();
                }

                @Override
                public void onError(Throwable e) {
                    Timber.e("Error loading article images", e);
                    Log.e("tag", "Error loading article images", e);
                    if (view != null) {
                        view.hideLoadingAnimation();
                        view.showLoadingErrorToast();
                    }
                }

                @Override
                public void onNext(List<ImageArticleCategoryEntity> integerImageArticleCategoryEntityHashMap) {
                    if (view != null)
                        view.loadArticleImages(integerImageArticleCategoryEntityHashMap);
                }
            });

A: Let's simplify how the lifecycle of the Realm instance is managed. If we manage it in the context of the resume/pause cycle of an Activity or Fragment, we can much more easily control and stop work that might consume that Realm instance. The tools in RxAndroid help a lot with that.
So, I'm going to assume for this example this is happening from an Activity, but a very similar approach could be used from a Fragment, or extracted into helper classes with just a hint more plumbing.
If you bind your Observable to the lifecycle of the Activity or Fragment using RxAndroid, which it appears you are already using for mainThread(), you should be able to manage your Realm instance easily within a lifecycle. I'm also using RxAsyncUtil for Async.toAsync, which makes the original creation of the Realm instance easier.
I've used Rx a lot more than Realm (though I've toyed with it a good bit), so forgive me if some of my API usage isn't perfect. I've also abbreviated things to java8-style lambdas just for ease-of-writing and reading. If you're not using something like retrolambda it should still be pretty easy to convert it back.
class MyActivity extends Activity {
  private final CompositeSubscriptions realmSubscriptions = new CompositeSubscription();

  private AsyncSubject<Realm> realm;

  @Override
  protected void onResume() {
    super.onResume();
    realm = AsyncSubject.create();
    realmSubscriptions.add(getRealmInstance());

    // This could actually happen anytime between onResume and onPause.
    realmSubscriptions.add(loadArticlesImages());
  }

  private <T> Observable<T> bindToRealm(final Observable<T> observable) {
    // Utility to bind to the activity lifecycle, observe on the main thread
    // (implicit in the bindActivity call), and do work on the Realm thread.
    return AppObservable.bindActivity(this, observable.subscribeOn(RealmThread.get()));
  }

  private Observable<List<ImageArticleCategoryEntity>> getArticleBuckets(
      final Realm realm) {
    /* As is, except the realm instance should be passed to RealmObservable.list instead
       of the context. */
  }

  private Subscription getRealmInstance() {
    // Grab the realm instance on the realm thread, while caching it in our AsyncSubject.
    return bindtoRealm(Async.toAsync(() -> Realm.getInstance(MyActivity.this)))
        .subscribe(realm);
  }

  private Subscription loadArticleImages() {
      // Using the flatMap lets us defer this execution until the
      // Realm instance comes back from being created on the Realm thread.
      // Since it is in an AsyncSubject, it will be available nearly
      // immediately once it has been created, and is cached for any future
      // subscribers.
      return bindToRealm(realm.flatMap((realm) ->
          articleRepo.getArticleBuckets(realm).subscribeOn(RealmThread.get())))
              .subscribe(
                  (next) -> {
                    if (view != null) {
                      view.loadArticleImages(next);
                    }
                  },
                  (error) -> {
                    Timber.e("Error loading article images", e);
                    Log.e("tag", "Error loading article images", e);
                    if (view != null) {
                      view.hideLoadingAnimation();
                      view.showLoadingErrorToast();
                    }
                  },
                  // onCompleted
                  () -> {
                    Timber.v("Loading article images complete!");
                    if (view != null) view.hideLoadingAnimation();
                  });
  }

  @Override
  protected void onPause() {
    // Stop any work which we added that involves the Realm instance.
    realmSubscriptions.clear();

    // Clean up the AsyncObservable. If it has a Realm instance, close it.
    if (realm.getValue() != null) {
      realm.getValue().close();
    }
    realm.dispose();
    realm = null;

    super.onPause();
  }
}

You should be able to easily extract this outside of an activity as needed, and just pass an Activity/Fragment instance for the lifecycle binding, as well as the Observable<Realm> which in this case would be the AsyncSubject. If there are still race conditions due to the subscription work, you may want to experiment with adding .unsubscribeOn(AndroidSchedulers.mainThread()) or even .unsubscribeOn(Schedulers.immediate()) (I'm actually not sure which would be best in this scenario) to bindToRealm to ensure unsubscribing happens when you want it to in the onPause, before the Realm instance is closed.


text:
Q: Deciding the optimal ARMA model The correlogram structure of the returns series I estimated (up to two lags) had an almost identical ACF and PACF structure. The signs were identical, and the magnitudes of the ACF and PACF up to 12 lags were almost all pretty much identical.
Does this point to some seasonality or a specific structure ARMA?
No other clear patterns were discernible, so I used information criterion and picked based on SBIC (AIC picked ARMA(2,2) but both of the first lags were insignificant so I assumed the model was being overfitted).
Should I have picked a different model instead? This is the step I am taking before determining the conditional variance equation.
All help is greatly appreciated.
Edit as requested:


text:
Q: C++ multiindex column csv load Multi-index column csv is

*

*Its size is (8, 8415).

*This csv file was made from pandas multi-index dataframe (python).

*Its columns are [codes X financial items].

codes are

financial items are

How can I use this csv file to use its year(2014, 2015, ....) as index and codesXfinancial items as multi columns?

A: What kind of output you want is unclear. There are not many libraries to imitate pandas in C++. A very messy, convoluted and inelegant way of doing it is declaring a structure and then put it into a list. Something like,
struct dataframe{
    double data;
    int year;
    int code;
    char item[];   //or you can use "string item;"
}

Make a list of this structure either by a custom class or C++ native "list" class.
If you can provide a more detailed explanation of what kind of data structure you want in the program or what do you want to do with it, I would try to provide a better solution.


text:
Q: Avplayer does not resize to full screen in iphone retina display I have a problem to play the video in iphone 5. The video is playing exactly in full screen in iphone but the problem is with retina display. It does not fit to full screen and leaves white thik bar on right side.
I tried the following code but it does not wirk in retina display
    outputURL = [NSURL fileURLWithPath:filePath];
    av = [[AVPlayer alloc] initWithURL:outputURL];
    AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:av];
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
    {
        [layer setFrame:CGRectMake(0, -20, 1024, 670)];
    }
    else
    {
        [layer setFrame:CGRectMake(0, -10, 480, 287)];
    }

    if([layer.videoGravity isEqualToString:AVLayerVideoGravityResizeAspect])
    {
        layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    }
    else
    {
        layer.videoGravity = AVLayerVideoGravityResizeAspect;
    }
    [self.view.layer addSublayer:layer];
    av.actionAtItemEnd = AVPlayerActionAtItemEndNone;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayBackDidFinish:)
                                                 name:AVPlayerItemDidPlayToEndTimeNotification
                                               object:[av currentItem]];

Please help me with some solution.
Thank you

A: In line 6 of your code you are setting the width of your AVPlayerLayer to 480px but the iPhone 5 screen has a width of 568px (when in landscape). So this can't work.
This should fix your issue:
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
{
    [layer setFrame:CGRectMake(0, -20, self.view.frame.width, 670)];
}
else
{
    [layer setFrame:CGRectMake(0, -10, self.view.frame.width, 287)];
}

But I wonder why you need that -20/-10 vertical offset and where those frame heights come from, maybe instead of that if/else block this could also work for you:
[layer setFrame:self.view.bounds];


text:
Q: Margin-bottom won't move div in tailwind I'm trying to move the email component up the screen but margin-bottom won't do anything. Is there another tailwind utility I have to use?
import React from 'react'

function Email() {
  return (

            <input type="text" placeholder="example@email.com" className="p-3 rounded-l-md sm:w-2/3 font-['DM_Sans']" />
            <button type="button" className="p-3 bg-[#00ADC2] text-white font-semibold rounded-r-md sm:w-1/3  font-['DM_Sans']">Notify Me</button>

  )
}

export default Email

How it looks on the page

A: Margin bottom is going to push the content below down.
If you are looking to move the content up you can try negative margin on top.
With tailwind it's something like -mt-8.


text:
Q: vuejs not update component When I click on links, mounted() works, but new template not loading from server, vue not send AJAX request if route is changed.
<section class="content">
    <router-view :key="$route.fullPath"></router-view>
</section>

<router-link to="/foo"></router-link>
<router-link to="/bar"></router-link>
<router-link to="/somelink"></router-link>

var testComponent = Vue.component('main-section', (resolve) => {
    axios.post('/test.php').then( (res) => {
        resolve({
            template: res.data,
            mounted: () => {
                console.log('mounted-' + new Date().getTime());
            }
        });
    });
});

var router = new VueRouter({
    routes: [
    { path: '/foo', component: testComponent },
    { path: '/bar', component: testComponent },
    { path: '*', component: testComponent }],
    mode: 'history'
});

A: Your component is the same for all of your routes, so Vue will load testComponent only one time. Once it has loaded a component, Vue will never reload it again.


text:
Q: field extension is simple I am working on the following problem:
Let $L/K$ be a field extension of degree $6$. Show that $L/K$ has a primitve element.
My idea is to use the theorem of primitive elements. So, if I prove that $L=K(a,b_1,...,b_n)$ for $a$ algebraic over $K$ and $b_1,...,b_n$ separable it follows that $L/K$ is simple. Unfortunately, I do not know how to start my proof. Any hint is greatly appreciated!

A: Let $L/K$ be a field extension of degree $6$.

Claim:$\;L$ is a simple extension of $K$.

Proof:

Suppose otherwise.

By the theorem of the primitive element, it follows that

*

*The extension $L/K$ is not separable.$\\[4pt]$

*There are infinitely many intermediate fields between $K$ and $L$.

But there can't be two intermediate fields of degree $2$ over $K$ between $K$ and $L$, else the join of those two subfields of $L$ would have degree $4$ over $K$, which is impossible since $4{\,\not\mid\,}6$.

It follows that there are infinitely many intermediate fields of degree $3$ over $K$ between $K$ and $L$.

Let $K(a),K(b)$ be distinct subfields of $L$ both having degree $3$ over $K$.

Necessarily $K(a,b)=L$.

Since $L/K$ is not separable, at least one of $a,b$ is not separable over $K$.

Without loss of generality, assume $a$ is not separable over $K$

It follows that the minimal monic polynomial for $a$ over $K$ is $f=(x-a)^3$.

Let $g$ be the minimal monic polynomial for $b$ over $K$. and let
$$
g=(x-b_1)(x-b_2)(x-b_3)
$$
be a complete factorization of $g$ in $\overline{L}[x]$, where $\overline{L}$ is an algebraic closure of $L$.

From
$$
6=[L:K]=[K(a,b):K(a)][K(a):K]=3[K(a,b):K(a)]
$$
we get $[K(a,b):K(a)]=2$, hence if $h$ is the minimal monic polynomial for $b$ over $K(a)$. we can assume, without loss of generality, that
$$
g=(x-b_1)(x-b_2)
$$
Then by Vieta's formulas we get

*

*$b_1+b_2+b_3\in K$.$\\[4pt]$

*$b_1+b_2\in K(a)$.

hence $b_3\in K(a)$.

It's immediate that $K(a)$ is a splitting field over $K$ of $f$, so $K(a)$ is a normal extension of $K$, hence since $g\in K[x]$ has a root $b_3\in K(a)$, it follows that $b_1,b_2,b_3\in K(a)$.

But then we get $b\in K(a)$, contradiction, since $K(a),K(b)$ are distinct subfields of $L$ both having degree $3$ over $K$, which implies $K(a)\cap K(b)=K$.

This completes the proof.


text:
Q: Apache Server taking longer time I have deployed my PHP API on a Linux based server. It's users are 40000-50000. Server has Disk space 20GB and out of that, 15GB is used. I have used MySQL for Database. GZip is enabled and the response JSON on http://example.com/getData is nearly equal to 100KB. Initially, it used to take 2-3 seconds on each getData call (which includes querying from data table and processing on PHP), but now it is taking more than 15 seconds for a single request. I have checked the CPU usage by TOP command in linux. This is the CPU status:
top - 09:30:44 up 14:44,  3 users,  load average: 1.16, 2.54, 2.28
Tasks: 222 total,   1 running, 221 sleeping,   0 stopped,   0 zombie
Cpu(s):  6.2%us,  1.5%sy,  0.0%ni, 92.2%id,  0.0%wa,  0.0%hi,  0.0%si,  0.2%st
Mem:   2051652k total,  1576444k used,   475208k free,   204408k buffers
Swap:        0k total,        0k used,        0k free,   456548k cached
PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
15942 www-data  20   0  320m  14m 6480 S    1  0.7   0:04.50 apache2
15356 mysql     20   0 1320m  52m 7448 S    1  2.6   1:00.19 mysqld
15973 www-data  20   0  321m  15m 6444 S    1  0.8   0:06.75 apache2
15811 www-data  20   0  318m  12m 5648 S    1  0.6   0:04.33 apache2
28989 root      20   0 96716 3928 2948 S    1  0.2   0:00.03 sshd
15806 www-data  20   0  323m  17m 6756 S    0  0.9   0:04.10 apache2
15807 www-data  20   0  321m  16m 6708 S    0  0.8   0:04.83 apache2
15817 www-data  20   0  322m  16m 6416 S    0  0.8   0:06.19 apache2
15832 www-data  20   0  320m  14m 6416 S    0  0.7   0:04.11 apache2
15838 www-data  20   0  320m  14m 6416 S    0  0.7   0:04.05 apache2
15849 www-data  20   0  321m  15m 6416 S    0  0.8   0:06.15 apache2
15851 www-data  20   0  321m  15m 6424 S    0  0.8   0:04.26 apache2
15853 www-data  20   0  320m  15m 6740 S    0  0.8   0:05.45 apache2
15856 www-data  20   0  323m  18m 6644 S    0  0.9   0:04.68 apache2
All the queries running time is less than 0.01 second and the microtime difference between end and start of the getData function is 0.51.
What may be the reasons of this slow response on browser?

A: I bet for DNS lookups in apache logs. Verify  "HostnameLookups" are off in your apache config.

A: It could probably be the logs that is stored in your system , it holds records of application activities ex time, date and much more  , that's a major thing in system logs as it reduces the performance of any application activities.


text:
Q: Is there a way to filter Customers on Shopify by metafield value through the REST Admin API? I am trying to get Shopify Customers by VAT Number which is a metafield. Apparently there's no way to do it.
I have gone through the docs and GitHub repository and tried all the possible solutions through REST and GraphQL.

A: So you are given a VAT number. You want the customer that has a metafield with the vat number?
Why would you not just ask for the metafield VAT value and search all Customers for a match?
metafield(namespace: "mystore", key: "vat") {
  value
}

Sure, it's a bit inefficient to search all Customers, but you do succeed in the end.


text:
Q: Raw HTML in mediawiki extension I'm writing a mediawiki extension and the code works great in a standalone model.  The goal is to generate an HTML select widget that fires off some javascript with the onchange event.  When I take the same code and put it in mediawiki it shows the raw code instead of interpreting it.
This is for an internal wiki and I'm the only editor, my team of volunteers will be the viewers.  That said I'm not too worried about being somewhat liberal on permissions especially while testing.
I've turned on
$wgRawHtml = true;
in LocalSettings.php
And also tried
return [ $html , markerType => 'nowiki' ];
But I get back the actual HTML on the wiki page
<html>
<select onchange='processSelect ( this.value )'><option value='0' >SWR MV1</option><option value='1' >SWR 2 NA</option><option value='2' >SWR MV2</option><option value='3' >SWR 4 NA</option></select>
</html>

A: You are on the right track with returning [$html, 'markerType' => 'nowiki'], but you also need to tell MediaWiki that the returned output is HTML. Otherwise, the MediaWiki Sanitizer will sanitize the output of your parser function:
return [$html, 'noparse' => true, 'isHTML' => true];
I recommend you turn off $wgRawHtml, since it can be extremely dangerous for publicly editable websites, since it allows your users to insert arbitrary HTML into a page. It will not affect the sanitation of parser functions.


text:
Q: What is the name of the Page Down key when using EventHandler? I want to trap the PageDown event in an EventHandler. The code I've written is working fine for, say, "RightArrowKeyDown". But for the life of me I can't find the label for the Page Down key. I've tried "PageDownKeyDown" and variations using Pg and Dn but none of these seem to work. There is also no documentation on the labels of the keys other than those keys explicitly mentioned on the EventHandler help page.
Does anyone know what label to use?
thanks


text:
Q: Can wrapping a type conversion in a static_cast ever hurt? I'm updating some old code and I get hundreds of warnings along the lines of warning C4244: '+=': conversion from 'std::streamsize' to 'unsigned long', possible loss of data in Visual Studio.
The project compiles and runs fine when just ignoring the warnings, but I want to remove them and put a static_cast<unsigned long>() function around each. Considering the code runs fine now, could this potentially be harmful?

A: Yes, static_cast can hurt, as it will tell the compiler to shut up, as you know what you are doing. The question is whether you actually know what you are doing?
Obviously, casting to a smaller type can result in an unexpected result if the stored data exceeds the smaller types size. Use a static_cast if you know for sure, that this case won't ever happen or that you expect a truncated value. If not, keep the warning until you have properly designed your code.

A:
The project compiles and runs fine when just ignoring the warnings

To start with, never ignore warnings. Think over what your code actually does instead.

Considering the code runs fine now, could this potentially be harmful?

Regarding your particular case, a static_cast<unsigned long> from std::streamsize will be harmful.
As the reference documentation of std::streamsize says, it's intentionally a signed type:

The type std::streamsize is a signed integral type used to represent the number of characters transferred in an I/O operation or the size of an I/O buffer. It is used as a signed counterpart of std::size_t, similar to the POSIX type ssize_t.

Static casting in that case actually means loss of semantics.

A:
The idea is that conversions allowed by static_cast are somewhat less
  likely to lead to errors than those that require reinterpret_cast. In
  principle, it is possible to use the result of a static_cast without
  casting it back to its original type, whereas you should always cast
  the result of a reinterpret_cast back to its original type before
  using it to ensure portability.

from Bjarne Stroustrup's C++ Style and Technique FAQ
Be careful with consts. static_cast doesn't cast away const.
In general, I think it would be better to rewrite your code instead of "casting every problem away" in hope that everything goes well.


text:
Q: decentralized development using git and git-svn We have 2-3 small teams of 2-3 people. We all use git for local and svn for central repository and git-svn got sync. This is works all the time except when we want to share our code between the team it self.
So we have tried out git pull, this creates lots of conflicts and it does not detect that we are on the same tree. It fetches all the changes (same as clone then pull)
Of course i dont want to clone full repo. every time I want to share.
Please suggest a better flow.

*

*We can't get rid of central svn.

*We can't clone every time.

A: Nominate one team member as the 'git hub',  he/she syncs with the SVN server, other team members interact with them,  rather than the SVN server directly.  That way git will know that all team members are on the same tree.

A: SubGit seems like a great alternative for you.
SubGit is server-side solution, it enables Git access to Subversion repository and vice versa. That means you can work with Git repository only, using Git client of your choice.
You need to install SubGit into your Subversion repository once. After that SubGit immediately translates svn revision into git commit on every svn commit and git commit into svn revision on every git push.
SubGit is closed-source software but it is free for open-source projects. For more information please refer to SubGit documenation.

A: To add to Chris Huang-Leaver's answer, you need a central point to dcommit/rebase with the svn repo.
That doesn't deny the "decentralized" aspect of Git, it simply allows everyone to work with, as one of their remote repositories, one "central" repo of reference (i.e. the one sync with svn)
There is no easy way to avoid the burden to clone everything coming from the (potentially huge) svn repo, because the resulting Git repo cannot be split into submodules.
That leaves at least one "solution", which would involve:

*

*creating different Git beside the main one (which sync with SVN)

*exporting patches from the main repo

*applying those patches to each Git repo representing a project within the main Git repo.

It obviously needs to be automated, but one team would focus on one of those git repos as its "central" repo, and the person in charge of SVN synchronization would update those smaller Git repos with patches coming from the main (and hidden) Git<=>SVN repo.


text:
Q: data within kendo-grid disappears on sort In an angular app I have a page that displays several Kendo-grids based on the data retrieved from an http request. The data comes back as json.
This is the function that executes on successful data retrieval. This is within a controller, and ctrl is the "this" object on the controller scope. Moment is a JavaScript library for managing dates. The only thing it's doing here is formatting as strings the date (MM/DD/YYYY) and the time (hh:mm A).
function (data) {
    ctrl.dateGroups = {};
    var currentDate = '';
    data.Data.forEach(function (item) {
        item.Date = item.StartDateTime ? moment(item.StartDateTime).format(HC_APP_CONFIG.dateFormat) : '';
        item.ClockInTime = item.StartDateTime ? moment(item.StartDateTime).format(HC_APP_CONFIG.timeFormat) : '';
        if ( angular.isEmpty(item.EndDateTime) ||
            item.EndDateTime === '' ||
            item.EndDateTime.format(HC_APP_CONFIG.dateFormat).match(HC_APP_CONFIG.badLocalDatePattern) !== null ){
            item.ClockOutTime = '';
            item.EndDateTime = '';
        } else {
            item.ClockOutTime = moment(item.EndDateTime).format(HC_APP_CONFIG.timeFormat);
        }
        var currentDate = 'd'+item.Date;
        if (ctrl.dateGroups.hasOwnProperty(currentDate) &&
            ctrl.dateGroups[currentDate].length > 0) {
            ctrl.dateGroups[currentDate].push(item);
        } else {
            ctrl.dateGroups[currentDate] = [item];
        }
    });
}

The function (successfully) takes each returned item and puts it into an object as part of arrays named after the date, so that all items from Jan 14th, for example, end up in one array, and another for Jan 15th, etc.
This displays in the page with this loop:

{{key.substring(1)}}

The result is a series of grids, each corresponding to a date and containing all the items for that date. This again, is successful.
The grid configuration:
gridConfig = {
    uiOptions: {},
    autoBind: false,
    sortable: {
        mode: 'single'
    },
    height: 'auto',
    columnMenu: false,
    filterable: false,
    dataSource: {
        type: 'json',
        serverPaging: true,
        serverFiltering: true,
        serverSorting: true,
        pageSize: HC_APP_CONFIG.defaultPageSize,
        schema: {
            data: 'Data',
            total: 'TotalCount',
            model: {
                id: 'ShiftId',
                fields: {
                    EmployeeName: {
                        type: 'string'
                    },
                    EmployeeCode: {
                        type: 'string'
                    },
                    JobName: {
                        type: 'string'
                    },
                    ClockIn: {
                        type: 'string'
                    },
                    ClockOut: {
                        type: 'string'
                    }
                }
            }
        }
    },
    columns: [
        {
            field: 'EmployeeName',
            title: 'Name',
            sortable: false
        },
        {
            field: 'EmployeeCode',
            title: 'Employee Code',
            sortable: false
        },
        {
            field: 'JobName',
            title: 'Job',
            sortable: false
        },
        {
            field: 'ClockInTime',
            title: 'Clock In'
        },
        {
            field: 'ClockOutTime',
            title: 'Clock Out'
        }
    ]
}

The problem is when I sort by the Clock In or Clock Out columns (the only sortable columns). At this point, the grid structure (pagination indicator, column heads, etc) remain in tact but the data disappears.
I'm using Kendo UI v2015.1.429

A: Kendo UI grids support direct server interaction via a built-in AJAX system for making API calls. It appears that setting serverSort:true may tell the Kendo UI grid to drop the current data model and query the server for newly sorted data (which it expects the server to provide). Since you are not using direct server interaction with the grid, it probably drops the model but then has no way to get a new one.
There is a sortable:true option that may be what you need for client side sorting of the existing data.
Link to Kendo UI grid server-side sorting article


text:
Q: Set a custom date within select option What I want to achieve:
Within Select, I would like to be able to select the start date and end date and when i click the 'Apply' button, I would like to record the values of startDate and endDate to calculate # of months selected. This value needs to be passed to the ng-model 'monthLimit'
script.js
var app = angular.module('plunker', ['angularjs-datetime-picker', 'ngMaterial']);

app.controller('MainCtrl', function($scope) {
  $scope.monthLimit = 'Test';
  $scope.startDate = '2016-03-02';
  $scope.endDate = '2016-03-10';
 $scope.monthLimitChanged = function(){
   if ($scope.monthLimit == 'Custom'){
     console.log('start date', $scope.startDate);
     console.log('end date', $scope.endDate);
   }
   $scope.showReport(); // calls a method that triggers a
   // http request and pass in the required params
 }
});

index.html
<!DOCTYPE html>

    <meta charset="utf-8" />
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/0.11.2/angular-material.min.css">
    <link rel="stylesheet" href="http://cdn.rawgit.com/kineticsocial/angularjs-datetime-picker/master/angularjs-datetime-picker.css">

    <md-select
        ng-model="monthLimit"
        ng-change="monthLimitChanged()">
        <md-option value="Test">Test</md-option>
        <md-option value="Custom">
            Custom

                <input style="width:90px;" datetime-picker date-format="yyyy-MM-dd" date-only required ng-model="startDate" /> -

                <input style="width:90px;" datetime-picker date-format="yyyy-MM-dd" date-only required ng-model="endDate" />

            <button ng-click="monthLimitChanged()" style="display:inline-block;">Apply</button>
        </md-option>
      </md-select>

style.css
md-select{
    padding: 30px;
    width: 250px;
}

md-option:hover{
    background-color: #eee;
}

Plunker
http://plnkr.co/edit/z4j3PKkEuKh4rd6u3dDG?p=preview

A: You can use moment.js (http://momentjs.com/) if you don't mind using another JS library and just do something like:
(moment.duration(moment($scope.endDate).diff(moment($scope.startDate)))).asMonths()


text:
Q: Create a new column based on existing multiple columns and rows in R I have been struggling to create a new column based on the values of certain rows and columns in another dataframe. I have a data frame that looks like this:

sample_ID
date
test_result

sample1
1/1/2022
positive

sample1
1/1/2022
negative

sample1
1/1/2022
negative

sample2
2/1/2022
positive

sample2
3/1/2022
negative

sample3
4/1/2022
negative

sample3
5/1/2022
positive

sample4
5/1/2022
negative

sample4
6/1/2022
negative

sample4
7/1/2022
negative

I want to create a new column with a decision of the final result of each sample ID. If sample is positive at any date, the final result will be the test result of the earliest date of positivity, otherwise the sample is negative. The results should look like this:

sample_ID
date
test_result
final_result

sample1
1/1/2022
positive
positive

sample1
1/1/2022
negative
positive

sample1
1/1/2022
negative
positive

sample2
2/1/2022
positive
positive

sample2
3/1/2022
negative
positive

sample3
4/1/2022
negative
positive

sample3
5/1/2022
positive
positive

sample4
5/1/2022
negative
negative

sample4
6/1/2022
negative
negative

sample4
7/1/2022
negative
negative

I did try with ifelse and loop but it was not successful.
I would appreciate any help. Thank you very much.

A: You can group_by sample_ID and check whether any of the test_result is "positive":
library(dplyr)
df %>%
  group_by(sample_ID) %>%
  mutate(final_result = ifelse(any(test_result == "positive"), "positive", "negative"))

output
# A tibble: 10 × 4
# Groups:   sample_ID [4]
   sample_ID date     test_result final_result
   <chr>     <chr>    <chr>       <chr>
 1 sample1   1/1/2022 positive    positive
 2 sample1   1/1/2022 negative    positive
 3 sample1   1/1/2022 negative    positive
 4 sample2   2/1/2022 positive    positive
 5 sample2   3/1/2022 negative    positive
 6 sample3   4/1/2022 negative    positive
 7 sample3   5/1/2022 positive    positive
 8 sample4   5/1/2022 negative    negative
 9 sample4   6/1/2022 negative    negative
10 sample4   7/1/2022 negative    negative

An equivalent in base R is:
df |>
  transform(final_result = ave(test_result, sample_ID,
                               FUN = \(x) ifelse(any(x == "positive"), "positive", "negative")))

A: You can use the library dplyr for this, doing a group_by on sample_ID and checking if any of the corresponding values was positive:
library(dplyr)

data = "sample_ID   date    test_result
                 sample1    1/1/2022    positive
                 sample1    1/1/2022    negative
                 sample1    1/1/2022    negative
                 sample2    2/1/2022    positive
                 sample2    3/1/2022    negative
                 sample3    4/1/2022    negative
                 sample3    5/1/2022    positive
                 sample4    5/1/2022    negative
                 sample4    6/1/2022    negative
                 sample4    7/1/2022    negative"

df <- read.table(text=data, sep="\t", header = TRUE)

df %>%
  group_by(sample_ID) %>%
  mutate(final_result = ifelse(any(test_result == 'positive'),'positive','negative')) %>%
  ungroup()