text:
Q: How to know which fareComponent is associated with a segment in BargainFinderMaxRS The rest api BargainFinderMaxRS groupedItineraryResponse object gives me the legs and their schedules (segments). It also gives me the fareComponents in the passengerInfo. But I can't figure out which fareComponent belongs to which flight segment. I don't see any identifier, like 'id' or 'ref', that links a specific flight segment to it's fareComponent. Am I missing something?
Thanks,
legs: [
  0: {
    id: 1,
    schedules: [
      0: {...},
      1: {...}
    ]
  },
  1: {
    id: 2,
    schedules: [
      0: {...}
    ]
  }
]

...

passengerInfo: {
  fareComponents: [
    0: {...},
    1: {...},
    2: {...}
  ]
}

EDIT Ok, I thought I understood how to match Legs to FareComponents, but I'm still having issues. Some times it seems like the array indexes of legs and fareComponents match up, but sometimes they don't.
In the itnerary below the first leg has 2 segments, and the second leg is non-stop. But the first fareComponent has 1 segment, and the second component has 2. Clearly fareComponent2 belongs to Leg1
Here's my Legs array from BFM response object:
"legs": [
{
  "ref": 3,
  "id": 3,
  "schedules": [
    {
      "ref": 13,
      "id": 13,
      "dotRating": "9",
      "frequency": "SMTWT**",
      "stopCount": 0,
      "eTicketable": true,
      "totalMilesFlown": 2556,
      "departure": {
        "airport": "HNL",
        "city": "HNL",
        "state": "HI",
        "country": "US",
        "time": "20:55:00-10:00",
        "terminal": "2"
      },
      "arrival": {
        "airport": "LAX",
        "city": "LAX",
        "state": "CA",
        "country": "US",
        "time": "05:18:00-07:00",
        "terminal": "2",
        "dateAdjustment": 1
      },
      "carrier": {
        "marketing": "DL",
        "marketingFlightNumber": 1212,
        "operating": "DL",
        "operatingFlightNumber": 1212,
        "equipment": {
          "code": "739",
          "typeForFirstLeg": "N",
          "typeForLastLeg": "N"
        }
      }
    },
    {
      "ref": 12,
      "departureDateAdjustment": 1,
      "id": 12,
      "dotRating": "8",
      "frequency": "SMTWT**",
      "stopCount": 0,
      "eTicketable": true,
      "totalMilesFlown": 953,
      "departure": {
        "airport": "LAX",
        "city": "LAX",
        "state": "CA",
        "country": "US",
        "time": "09:38:00-07:00",
        "terminal": "3"
      },
      "arrival": {
        "airport": "SEA",
        "city": "SEA",
        "state": "WA",
        "country": "US",
        "time": "12:27:00-07:00"
      },
      "carrier": {
        "marketing": "DL",
        "marketingFlightNumber": 2540,
        "operating": "DL",
        "operatingFlightNumber": 2540,
        "equipment": {
          "code": "739",
          "typeForFirstLeg": "N",
          "typeForLastLeg": "N"
        }
      }
    }
  ]
},
{
  "ref": 6,
  "id": 6,
  "schedules": [
    {
      "ref": 10,
      "id": 10,
      "dotRating": "9",
      "frequency": "****TF*",
      "stopCount": 0,
      "eTicketable": true,
      "totalMilesFlown": 2676,
      "departure": {
        "airport": "SEA",
        "city": "SEA",
        "state": "WA",
        "country": "US",
        "time": "08:20:00-07:00"
      },
      "arrival": {
        "airport": "HNL",
        "city": "HNL",
        "state": "HI",
        "country": "US",
        "time": "11:29:00-10:00",
        "terminal": "2"
      },
      "carrier": {
        "marketing": "DL",
        "marketingFlightNumber": 1887,
        "operating": "DL",
        "operatingFlightNumber": 1887,
        "equipment": {
          "code": "753",
          "typeForFirstLeg": "N",
          "typeForLastLeg": "N"
        }
      }
    }
  ]
}

]
Here is the fareComponents array:
"fareComponents": [
            {
              "ref": 1,
              "segments": [
                {
                  "segment": {
                    "bookingCode": "V",
                    "cabinCode": "Y",
                    "mealCode": "D",
                    "seatsAvailable": 4,
                    "availabilityBreak": true
                  }
                }
              ],
              "id": 1,
              "governingCarrier": "DL",
              "fareAmount": 137.31,
              "fareCurrency": "USD",
              "fareBasisCode": "VA0SLOME/LN75",
              "farePassengerType": "JCB",
              "ticketDesignator": "LN75",
              "publishedFareAmount": 274.62,
              "negotiatedFare": true,
              "privateFare": true,
              "directionality": "FROM",
              "direction": "WH",
              "notValidAfter": "2019-08-31",
              "applicablePricingCategories": "5 10 15 16 18 25 35",
              "vendorCode": "ATP",
              "fareTypeBitmap": "0E",
              "fareType": "SIP",
              "fareTariff": "191",
              "fareRule": "8694"
            },
            {
              "ref": 5,
              "segments": [
                {
                  "segment": {
                    "bookingCode": "V",
                    "cabinCode": "Y",
                    "mealCode": "B",
                    "seatsAvailable": 4,
                    "availabilityBreak": true
                  }
                },
                {
                  "segment": {
                    "bookingCode": "V",
                    "cabinCode": "Y",
                    "mealCode": "B",
                    "seatsAvailable": 9,
                    "availabilityBreak": true
                  }
                }
              ],
              "id": 5,
              "governingCarrier": "DL",
              "fareAmount": 137.31,
              "fareCurrency": "USD",
              "fareBasisCode": "VA0SLOME/LN75",
              "farePassengerType": "JCB",
              "ticketDesignator": "LN75",
              "publishedFareAmount": 274.62,
              "negotiatedFare": true,
              "privateFare": true,
              "directionality": "TO",
              "direction": "WH",
              "notValidAfter": "2019-08-31",
              "applicablePricingCategories": "5 10 15 16 18 25 35",
              "vendorCode": "ATP",
              "fareTypeBitmap": "0E",
              "fareType": "SIP",
              "fareTariff": "191",
              "fareRule": "8694"
            }
          ]

A: Bargain Finder responses doesn't match prices with legs. Itineraries group segments (legs), and each itinerary have its own price.
Edit: I misunderstood the question. You are not missing something, you are right. First, you need to group legs by it's ref value, using "legs" attribute of itinerary. You need to sort segment legs using that information, after that you'll see legs count and fare component --> segment attribute count is the same. Also their indexes are same too. I mean you have 3 leg after sorting:
leg1
leg2
leg3
and you have 3 fare component:
fareComponent1
fareComponent2
fareComponent3
Here is the result:
leg1 own fareComponent1
leg2 own fareComponent2
... and so on. I hope this helps.


text:
Q: Vibrating an Android phone based on mic input I want to record the voice/sound input from the android phone and convert to specific type of vibrations of the phone. The idea is to help differently abled people with their surrounding environment and help in giving some sense of nearby obstacles (say car etc). How can I :

*

*Read the mic / sound input and save it in real-time ( to process it  further).

*Vibrate the phone with specific frequency

I am looking for the specific libraries and some sample codes to use them.

A: Im fairly certain the vibrator doesnt function with frequencys, its either on or its off. The best you could do is probably morse code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I want to create a board in C# using the Miro (https://miro.com) API I am building a .NET Core 6.0 WPF application in Visual Studio 2022 Community.
I want to create a board in C# using the Miro (https://miro.com) API.
I have obtained CliendID and ClientSecret for authentication.
I added RestSharp with NuGet and wrote the code below.
It goes through to authentication.
After that, I am posting to api.miro.com/v1/board, but I get the error Unauthorized.
How can I post?
        public string MiroUserProfileUrl = "https://miro.com/app/settings/user-profile/apps";
        public string ClientID = "myclientid";
        public string ClientSecret = "myclientsecret";

        internal async void CreateBoardAtMiro()
        {
            try
            {
                var client = new RestClient("https://miro.com/app-install/?response_type=code&client_id="+ ClientID);
                var request = new RestRequest();
                request.Method = Method.Post;
                request.AddHeader("Authorization", "Bearer " + ClientSecret);
                var response = client.ExecuteAsync(request);
                var result = response.Result;   //StatusCode: OK, Content-Type: text/html, Content-Length: )

                var boardMakeClient = new RestClient("https://api.miro.com/v1/boards");
                var boardMakerequest = new RestRequest();
                boardMakerequest.Method = Method.Post;
                boardMakerequest.AddHeader("Accept", "application/json");
                boardMakerequest.AddHeader("Content-Type", "application/json");
                boardMakerequest.AddParameter("application/json", "{\"name\":\"Untitled\",\"sharingPolicy\":{\"access\":\"private\",\"teamAccess\":\"private\"}}", ParameterType.RequestBody);
                var boardMakeResponse = boardMakeClient.ExecuteAsync(boardMakerequest);
                var boardMakeResult = boardMakeResponse.Result;   //StatusCode: Unauthorized, Content-Type: application/json, Content-Length: 135)
            }
            catch(Exception exception)
            {
                var error = exception.Message;
            }
        }

A: You are missing the Bearer token in the request to make a board. I suggest that you add the token
boardMakerequest.AddHeader("Authorization", "Bearer " + ClientSecret);


text:
Q: A RenderFlex overflowed by 41 pixels on the bottom. The relevant error-causing widget was Column I need to create a search box with the result of searching in ListView.Builder, but I have a crash! I tried to solve it with get the Container height value MediaQuery.of(context).size.height but get me the same issue!

════════ Exception caught by rendering library ═════════════════════
The following assertion was thrown during layout: A RenderFlex overflowed by 41 pixels on the bottom.
The relevant error-causing widget was
      Column  lib/pages/search.dart:78 The overflowing RenderFlex has an orientation of Axis.vertical. The edge of the RenderFlex that is
  overflowing has been marked in the rendering with a yellow and black
  striped pattern. This is usually caused by the contents being too big
  for the RenderFlex.
Consider applying a flex factor (e.g. using an Expanded widget) to
  force the children of the RenderFlex to fit within the available space
  instead of being sized to their natural size. This is considered an
  error condition because it indicates that there is content that cannot
  be seen. If the content is legitimately bigger than the available
  space, consider clipping it with a ClipRect widget before putting it
  in the flex, or using a scrollable container rather than a Flex, like
  a ListView.
The specific RenderFlex in question is: RenderFlex#1a63c
  relayoutBoundary=up1 OVERFLOWING
  ════════════════════════════════════════════════════════════

My Code:
body: Column(
        children: <Widget>[
          Container(
              width: MediaQuery.of(context).size.width,
              margin: EdgeInsets.all(10),
              padding: EdgeInsets.only(right: 10),
              decoration: BoxDecoration(
                  color: Colors.white,
                  border: new Border.all(
                    color: Colors.grey,
                    width: 1,
                  ),
                  borderRadius: BorderRadius.all(new Radius.circular(10))),
              child: DropdownButton<String>(
                value: dropdownValue,
                icon: Icon(Icons.keyboard_arrow_down),
                iconEnabledColor: Colors.grey,
                iconSize: 50,
                elevation: 16,
                isExpanded: true,
                style: TextStyle(color: Colors.black),
                underline: Container(
                  height: 2,
                ),
                onChanged: (String newValue) {
                  setState(() {
                    dropdownValue = newValue;
                  });
                },
                items: <String>["Swift", "Dart"]
                    .map<DropdownMenuItem<String>>((String value) {
                  return DropdownMenuItem<String>(
                    value: value,
                    child: Text(value),
                  );
                }).toList(),
              )),
          Container(
            margin: EdgeInsets.all(10),
            child: Column(
              children: <Widget>[
                  TextField(
                    obscureText: true,
                    onChanged: (value) {
                      filterSearchResults(value);
                    },
                    decoration: InputDecoration(
                        filled: true,
                        fillColor: Colors.white,
                        focusedBorder: OutlineInputBorder(
                            borderSide: const BorderSide(
                                color: Color.fromRGBO(111, 192, 81, 1),
                                width: 1.5),
                            borderRadius: BorderRadius.circular(10)),
                        contentPadding:
                            EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                        hintText: "Search",
                        prefixIcon: new Icon(Icons.search, color: Colors.grey),
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(10)),
                          borderSide: BorderSide(width: 1, color: Colors.grey),
                        )),
                  ),
                ListView.builder(
                  shrinkWrap: true,
                  scrollDirection: Axis.vertical,
                  itemCount: items.length,
                  itemBuilder: (context, index) {
                    return ListTile(
                      title: Text('${items[index]}'),
                    );
                  },
                ),
              ],
            ),
          ),
        ],
      ),

What is the issue and how can I solve it??

A: You need to place Expanded in two places
body: Column(
  children: <Widget>[
    Container(
      width: MediaQuery.of(context).size.width,
      margin: EdgeInsets.all(10),
      padding: EdgeInsets.only(right: 10),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border.all(
          color: Colors.grey,
          width: 1,
        ),
        borderRadius: BorderRadius.all(Radius.circular(10)),
      ),
      child: DropdownButton<String>(
        value: dropdownValue,
        icon: Icon(Icons.keyboard_arrow_down),
        iconEnabledColor: Colors.grey,
        iconSize: 50,
        elevation: 16,
        isExpanded: true,
        style: TextStyle(color: Colors.black),
        underline: Container(height: 2),
        onChanged: (String newValue) {
          setState(() {
            dropdownValue = newValue;
          });
        },
        items: <String>["Swift", "Dart"]
            .map<DropdownMenuItem<String>>((String value) {
          return DropdownMenuItem<String>(
            value: value,
            child: Text(value),
          );
        }).toList(),
      ),
    ),
    Expanded(  //TODO: Add Expanded here
      child: Container(
        margin: EdgeInsets.all(10),
        child: Column(
          children: <Widget>[
            TextField(
              obscureText: true,
              onChanged: (value) {
                filterSearchResults(value);
              },
              decoration: InputDecoration(
                filled: true,
                fillColor: Colors.white,
                focusedBorder: OutlineInputBorder(
                  borderSide: const BorderSide(
                    color: Color.fromRGBO(111, 192, 81, 1),
                    width: 1.5,
                  ),
                  borderRadius: BorderRadius.circular(10),
                ),
                contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                hintText: "Search",
                prefixIcon: new Icon(Icons.search, color: Colors.grey),
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.all(Radius.circular(10)),
                  borderSide: BorderSide(width: 1, color: Colors.grey),
                ),
              ),
            ),
            Expanded( //TODO: Add Expanded here
              child: ListView.builder(
                shrinkWrap: true,
                scrollDirection: Axis.vertical,
                itemCount: items.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text('${items[index]}'),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    ),
  ],
)


text:
Q: How does the current draw of an IC change with supply voltage? Suppose I have a device with a number of ICs (microcontroller, logic gates, MEMs sensors, etc) which can operate from a supply voltage in the range of, say, 1.7V to 3.6V. Will the current draw be different if I power the devices at the low-end (1.7V) vs the high-end (3.6V) of the operating range? Does the answer vary depending on the specific IC or is there a general rule-of-thumb?
The datasheets I've looked at don't seem to go to this level of detail, and instead only specify current draw at a single supply voltage. I'm interested because my device is battery powered and I'm considering whether to run direct from the battery or to use a LDO regulator.

A: It depends on the IC.
For ordinary digital chips, the dominant current draw is charging and discharging capacitances to full rail voltages, so current draw is likely to be roughly proportional to voltage.
For analog chips the current is also likely to be positively correlated to the voltage, but the correlation may be weaker than with digital parts as analog designs are often based around (roughly) constant currents derived from some reference.
And very occasionally you will come across a device with a built-in switched mode power supply so the current drops as the voltage increases.

A: In general, yes, working at the lower voltage range will drop the current pretty much directly proportional to the supply voltage.
However, since you are dealing with non-linear elements, there are many exceptions to this rule.
However, dropping the voltage to save current adds a couple of issues.

*

*Your supply needs to be more accurate to ensure any ripple or variation does not drop the supply below the minimum required by your devices.

*Dropping signal levels makes you more susceptible to noise. When running at the lower end of the supply, more care needs to be taken to reduce system noise.
For your specific case, which seems to have a fair amount of complexity, you will be adding a lot of heartache trying to get it to run at the lower end. If the minimum is 1.7V and you try to run it at 1.7V that means you need a perfect power source and zero system noise.


text:
Q: HTML Form elements reduces its height after form submission I have designed a simple form to send me some data as feedback. The look of the form is same on all browser. But there is one problem I'm unable to fix. Whenever I submit the form the height of all the elements of my form get very much reduced. I even fixed the height of my elements but it is still getting decreased.!
This is the image before I submit the form.
http://i.stack.imgur.com/XtVbw.jpg
This is the image after submission. See the underlined text fields.
http://i.stack.imgur.com/xZ3m9.jpg

A: Use your browser's View Source feature to inspect the HTML. I bet you have some error or invalid elements before the <DOCTYPE>.


text:
Q: CodeIgniter controller not interpreting hyphen correctly in function call I'm having an odd problem.  My controller is trying to call uri segments and is not interpreting the hyphen correctly.  I don't get any error.  Just the rest of the page beyond the call doesn't render.  This is for a CMS and I have created an edit_market function in my markets controller.  I want to be able to call the page content for a page, which is referenced in the database by the page navigation name, which is sometimes hyphenated (consumer-goods, for example).
Here is my controller:
function edit_market($page=NULL) {

// Send copy and images to page
$data['query'] = $this->markets_materials_model->get_content('markets', $page);

... load view ...

My markets_materials_model:
function get_content($table, $category) {
    $this->db->where('navigation', $category);
    return $this->db->get($table)->result();
}

This works fine for all links that don't have a hyphen, but fails when the link has a hyphen.  What is causing this?  The only way I can edit these pages right now is by using edit_market in my URI rather than being able to create a route that has "edit-market" in it.  I believe if I remember right that accessing controllers directly was a bad practice.

A: There is absolutely nothing wrong with using the controller name: not sure where it came about that it is a bad practice.


text:
Q: How can i automatically have a page save the current time to the DB in 5 minute intervals w/o postback? Basically i have a C# Web App where a user views a streaming video. While they are viewing it, i have a timer running in the code behind. When they finish viewing the video, they hit a submit button which takes the difference from the start time and end time and emails the total viewing time to me.
The issue is, if they lose their session or their internet connection drops out for a brief moment, the time is lost and i have no proof how long they viewed the 1.5 hour video for.
I was wondering where to start to have it automatically save the time to the database like every 5 minutes behind the scenes without it affecting the streaming video or posting back, that way they have record of how much viewing time there was up until they lost connection.

A: We used the information from this blog post to accomplish it in our apps.  There are code samples that show exactly how to do it.  Adjust the
window.setInterval('SaveUserInput()', 10000);

line as needed to change the interval.

A: You could store the start time in a hidden field when page loads, and then use javascript to post to a webservice at a set interval with the start time.

A: One option would be to setup an ajax call to talk to the server on an interval to say "I'm still here" - if your ajax call sends a video ID or some other type of session identifier, it can update your database with the appropriate time.
I'd suggest looking into using jQuery for this along with [WebMethods]. It makes it quite simple to accomplish.  Here's a nicely written article that talks about how to accomplish it with asp.net: http://dotnetslackers.com/articles/ajax/Using-jQuery-with-ASP-NET.aspx

A: You say "without a postback" - but does that mean a whole page postback?  Otherwise it should be pretty easy to make an AJAX call back to the server from some JavaScript.  You could use the JQuery library to easily make the call.  Here's a pretty good page discussing how to call a page method from JQuery: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

A: Suggestions to use JQuery or other AJAX library to make ajax call every 5 min are good but if you are new to this, you can use the asp.net ajax extensions Timer object (Toolbox->AJAX Extensions->Timer). its not hard to use, it follows a typical event driven model like other ASP.NET controls


text:
Q: python structs for dict of files This may be a newb question, but I'm a bit of newb with python, so here's what I'm trying to do...
I am using python2.7
I would like to assign a file path as a string into a dict in functionA, and then call this dict in functionB.
I looked at C-like structures in Python to try and use structs with no luck, possibly from a lack of understanding... The below sample is an excerpt from the link.
I also took a look at What are metaclasses in Python?, but I'm not sure if I understand metaclasses either.
So, how would I call assigned parameters in functionaA, within frunctionB such as:
class cstruct:
    path1 = ""
    path2 = ""
    path3 = ""

def functionA():
   path_to_a_file1 = os.path.join("/some/path/", "filename1.txt")
   path_to_a_file2 = os.path.join("/some/path/", "filename2.txt")
   path_to_a_file3 = os.path.join("/some/path/", "filename3.txt")

   obj = cstruct()
   obj.path1 = path_to_a_file1
   obj.path2 = path_to_a_file2
   obj.path3 = path_to_a_file3

   print("testing string here: ", obj.path1)
      # returns the path correctly here

# this is where things fall apart and the print doesn't return the string that I've tested with print(type(obj.path))
def functionB():
   obj = cstructs()
   print(obj.path1)
   print(obj.path2)
   print(obj.path3)

   print(type(obj.path))
      # returns <type 'str'>, which is what i want, but no path

Am I passing the parameters properly for the paths? If not, could someone please let me know what would be the right way to pass the string to be consumed?
Thanks!

A: You need to do something like this:
class Paths:
    def __init__(self, path1, path2, path3):
        self.path1 = path1
        self.path2 = path2
        self.path3 = path3

def functionA():
    path_to_a_file1 = os.path.join("/some/path/", "filename1.txt")
    path_to_a_file2 = os.path.join("/some/path/", "filename2.txt")
    path_to_a_file3 = os.path.join("/some/path/", "filename3.txt")

    obj = Paths(path_to_a_file1, path_to_a_file2, path_to_a_file3)
    return obj

def functionB(paths): # should take a parameter
   # obj = cstructs() don't do this! This would create a *new empty object*
   print(paths.path1)
   print(paths.path2)
   print(paths.path3)

   print(type(paths.path))

paths = functionA()
functionB(paths) # pass the argument

In any case, you really should take the time to read the official tutorial on classes. And you really should be using Python 3, Python 2 is passed its end of life.


text:
Q: Looping though column in MS Project I  am trying to import all the data from MS project to Excel using VBA in Excel.
Set aProg = appProj.ActiveProject

appProj.OutlineShowAllTasks
j = 2
For Each t In aProg.Tasks
    If (Not t Is Nothing) Then
Cells(j, 5).Value = t.Start
Cells(j, 6).Value = t.Task Name
Cells(j, 7).Value = t.%complete

j =j+1
end if

next
The code works fine if the column name/field name is not having any special character or blank.
Could anyone please let me know how we can refer field name with blanks or special characters like "t.Task Name" or "t.%complete"

A: Use Early Binding so you have IntelliSense (more info) when you are writing your code. That way you declare t As MSProject.Task and when you type t followed by a period you get a drop-down list of properties and methods.
For your specific case, the properties you want are t.TaskName and t.PercentComplete.


text:
Q: validating encrypted data from sqlite3 database i am creating a login function and a part of this includes checking a password entered by the user against the password stored in the database.
The problem is, when the password is created during the sign up step, it is stored as an encrypted string using fernet. Now I tried to see if encrypting the password entered by the user with the same key would produce the same encrypted string value as the one in the database, but fernet will create unique strings using the same key on the same plaintext.
What other ways can i check a password entered against its encrypted counterpart in the database?
import sqlite3
from cryptography.fernet import Fernet
key = Fernet.generate_key()
fernet = Fernet(key)

def loginFunc():
  email = input("What is your email: ")
  password = input("what is your password: ")
  #a variable that can be used to save the data from users database
  emailList = '''SELECT * FROM users WHERE `email` = ? and `password` = ?'''
  #takes arguments into variable
  password_checkEnc = fernet.encrypt(password.encode())
  inputs = (email, password_checkEnc)
  #executes line 62 to save the data that matches the arguments from 'inputs' and stores in emailList
  cursor.execute(emailList, inputs)
  user = cursor.fetchone()
  #if statement to check if the database holds the data that is being searched for, allowing either the user to login or not
  if user is not None:
    print("login successful")
  else:
    print("incorrect information")

A: Why not just decrypt the password and check that way? My understanding of fernet key encryption is to do exactly what you're describing, creating a random encryption of the value each time. The purpose of the key is to decrypt it later. It would probably help to see your code where you initially encrypt the password but just looking at what you have here, it looks like you're generating a new key, not using the same one as before. You have to actually save the key you create initially with something like this:
# key generation
key = Fernet.generate_key()
fernet = Fernet(key)

# string the key in a file
with open('C:/locationofyourchoosing/newkey.key', 'wb') as filekey:
    filekey.write(key)

# using the key to encrypt
f = Fernet(key)
f.encrypt(databasepassword)

Then you use this same key to decrypt the value later like this:
# opening the key
with open('C:/locationofyourchoosing/newkey.key', 'rb') as filekey:
    key = filekey.read()

f = Fernet(key)
f.decrypt(databasepassword)

Then from there you can check the equality of the password. Forgive me if this isn't what you're looking for but I'm not sure you can produce the same encrypted string each time as I believe that would defeat the purpose. I hope this helps and again, if I'm missing the mark completely, please let me know as I'm just a touch confused as to why you're wanting to check equality this way.


text:
Q: Get an error when consuming a WCF server from .Net Core 2.1 but it's fine on .NET I have a WCF service (AIF) on Microsoft Dynamics AX
I can call it without any problem using .NET 4.6.1. However, when I run the same exact code using .NET Core I get an error which states

A call to SSPI failed The target principal name is incorrect

There are many alike questions out there about this error but the solutions does not fix my problem.
    var service = new MarketplaceGetItemsDataServiceClient();
    service.ClientCredentials.Windows.ClientCredential.UserName = "UserName";
    service.ClientCredentials.Windows.ClientCredential.Password = "P@ssword";
    service.ClientCredentials.Windows.ClientCredential.Domain = "Domain";
    var result = service.GetItemsDataAsync(new CallContext(), new SearchOptionsDC() { VendorId = "0000" }).Result;

A: In Connected Services\MyService\Rference.cs file find the method GetEndpointAddress() and add the UpnEndpointIdentity with your identity account.
private static System.ServiceModel.EndpointAddress GetEndpointAddress(EndpointConfiguration endpointConfiguration)
    {
        if ((endpointConfiguration == EndpointConfiguration.NetTcpBinding_MyService))
        {
            return new System.ServiceModel.EndpointAddress(
                new System.Uri(@"net.tcp://190.188.1.2:8201/DynamicsAx/Services/MyService"),
                new System.ServiceModel.UpnEndpointIdentity("host@host.com")
                );
        }
        throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration));
    }

A: Change the DNS and replace it with the IP in the WCF tool.


text:
Q: Check if environment variable present while starting rails app or abort I would like to check if an environment is set while starting my rails app. If it's not present I would like to abort with an error message.
Where would I put this check?
In a config file or routes file?

A: Rails initialization starts from config/environment. That requires config/application and then loads the application which executes the initializers.
Depending on when in the initialization process you want to raise the error, I suggest adding it into config/application or an initializer.
routes.rb is definitely inappropriate unless the condition is directly related to routing.


text:
Q: Anonymous user grayed out, but not deleted? I'm pretty sure I have seen a user with a user name like user1234567, that had a grayed out name link, but was active.
(I did not find the example)
From Some User is Shown As Greyed Out, I understand that grayed out user names indicate deleted user accounts.
The last comment from the user was one hour ago - it feels improbable that he had been deleted in that hour.
(I noticed because I wanted to comment on something for him, but was unsure whether he can communicate at all.)
Is there something special about deleting anonymous users? I assumed an anonymous account is based on a cookie in the users browser, so even if the user lost that cookie, we would not notice.

A: It is certainly possible the user did delete their account. If it was a fairly new account, they could have done it instantly without any manual intervention by the Stack Exchange team. Users do this all the time when they ask a question that isn't well received or have an otherwise negative experience and just choose to delete their account. The only time a user would still exist is if the post was disassociated, in which case the displayed name would also be changed to "anon" to anonymize the post.
Without knowing the comment that confused you, we can't know for sure what happened. But if the display name is greyed out, there is no account connected to the post/comment.


text:
Q: Add Fake Category in Product Url Slug, like www.example.com/fake/myproduct.html how it is possible to keep a forward slash in the product url slug? Everytime Magento changes the "/" to "-", but we need a fake subpath for robots.txt rules for certain products. We cant use category path mechanic, because only some products need this special urls.

A: This can be managed in the Admin Config:
Store -> Configuration -> Catalog -> Catalog -> Search Engine Optimization -> "Use Categories Path for Product URLs" set to "Yes"


text:
Q: Intercept between an Exponential and Sinusoidal Function I need to find the intercept point between a function $V_C=325.6 e^{t/0.22}$ and $V=325.6 \sin(2\pi\cdot 50t)$. I tried solving for $t$ in both equations and then solving when $V=V_C$ but i couldn't find a way to solve it. If it helps, the first equation, $V_C$, is a capacitor discharging, and the second one is a $230$V rms AC voltage source. They both start at the peak, $325.6$V, and I need to find out at what time will the voltage of the capacitor will be the same as the voltage source again. Thanks a lot.

A: The equation
$$
325.6\ e^{t/0.22}= 325.6 \sin(2\pi \cdot 50t)
$$
has no 'nice' exact solution. However, there are numeric techniques to finding the values $t$ that satisfy the equation. There are plenty of free calculators that will find intersections for you. For instance, try this link here. A few solutions are:
$$
\begin{aligned}
t &\approx -0.0138811 \\
t &\approx -0.016207 \\
t &\approx -0.0332926 \\
t &\approx -0.0367900
\end{aligned}
$$

A: You are looking for the zero's of function
$$f(t)=\exp \left(\frac{50}{11} t\right)-\sin (100 \pi  t)$$ which has an infinite number of solutions, all of them being negative. Because of the exponential term, they will closer and closer to $t_k=-\frac k {100}$.
Building the $[1,2]$ Padé approximant of $f(t)$ around $t=-\frac k {100}$, we can obtain the approximation
$$t_k=-\frac k {100}+\frac{33 \left(1-88 \pi  e^{k/22} \left((-1)^k-11 \pi  e^{k/22}\right)\right)}{50 \left(88 \pi  e^{k/22} \left(-99 \pi
   e^{k/22}+726 \pi ^2 (-1)^k e^{k/11}+\left(3-121 \pi ^2\right) (-1)^k\right)-1\right)}$$
For the first roots, this gives
$$\left(
\begin{array}{ccc}
 k & \text{aproximation} & \text{exact} \\
 1 & -0.0135137 &  -0.0138811 \\
 2 & -0.0165562 &  -0.0162069 \\
 3 & -0.0331248 &  -0.0332926 \\
 4 & -0.0369465 &  -0.0367900 \\
 5 & -0.0527927 &  -0.0528803 \\
 6 & -0.0572777 &  -0.0571973 \\
 7 & -0.0725058 &  -0.0725543 \\
 8 & -0.0775623 &  -0.0775183 \\
 9 & -0.0922555 &  -0.0922834 \\
 10 & -0.0978095 &  -0.0977845
\end{array}
\right)$$


text:
Q: What is the use of lucene index files in DBPedia-Spotlight..? I am trying to find named entities in a given text.  For that, I have tried using DBPedia spotlight service.

*

*I am able to get a response out of that. However, the DBPedia dataset is limited, so I tried replacing their spotter.dict file with my own dictionary. My dictionary contains entities per line:
Sachin Tendulkar###PERSON
Barack Obama ###PERSON
.... etc

*Then I parse this file and build an ExactDictionaryChunker object.

*Now I am able to get the entities and their types (after modification of dbpedia code).
My Question is: DBPedia spotlight is using Lucene Index files.  I really don't understand for what purpose they are using these files?
Can we do it without using Index files? Whats the significance of the index files?

A: Lucene was used in the earlier implementation of DBpedia Spotlight to store a model of each entity in our KB. This model is used to give us a relatedness measure between the context (extracted from your input text) and the entity. More concretely, each entity is represented by a vector {t1: score1, t2: score2, ... }. At runtime we model your input text as a vector in the same dimensions and measure the cosine between input vector and entity vectors. In your case, you would have to add a vector for Sachin Tendulkar to the space (add a document to the Lucene index) in case it is not already there. The latest implementation, though, has moved away from Lucene to an in-house in-memory context store. https://github.com/dbpedia-spotlight/dbpedia-spotlight/wiki/Internationalization-(DB-backed-core)


text:
Q: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `` models.py
class Wishlist(models.Model):
    home = models.ForeignKey(Home, on_delete=models.CASCADE, blank=False, null=False)
    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, null=False)

    def __str__(self):
        return "{} - {}".format(self.user.username, self.home.address)

    class Meta:
        ordering = ('user',)

urls.py
urlpatterns = [
    path(r'wishlist/<int:pk>/', views.WishlistGetUserItems.as_view(), name='wish-user-list'),
]

views.py
class WishlistGetUserItems(APIView):

    def get(self, request, pk):
        wishlist = get_list_or_404(Wishlist, user=pk)
        data = serializers.UserWishlistSerializer(wishlist).data
        Response(data, status=status.HTTP_200_OK)

I've tried also to print message but seems like the method is not called

A: You should add return before Response.
def get(self, request, pk):
    wishlist = get_list_or_404(Wishlist, user=pk)
    data = serializers.UserWishlistSerializer(wishlist).data
    return Response(data, status=status.HTTP_200_OK)


text:
Q: Getting translation and rotation from resultant matrix I have a matrix which performs a 2D rotation around any given center. Using homogenous coordinates, I have the matrices:
$$ T = \begin{pmatrix}
1 & 0 & C_x \\
0 & 1 & C_y \\
0 & 0 & 1 \end{pmatrix}$$
where $C_x$ and $C_y$ are the coordinates of the rotation center, and
$$ R = \begin{pmatrix}
\cos(\theta) & -\sin(\theta) & 0 \\
\sin(\theta) & \cos(\theta) & 0 \\
0 & 0 & 1 \end{pmatrix}$$
Now I can obtain the matrix $X = TRT^{-1}$, which translates everything to the origin, rotates and then translates back to the given center.
My question is, given $X$, is it possible to find $C_x$, $C_y$ and $\theta$ ?
At first blush, I'd think so, since (where $c$ and $s$ are the cossine and sine, respectively)
$$ X = \begin{pmatrix}
c & -s & C_x(1-c)+C_ys \\
s & c & -C_xs+C_y(1-c) \\
0 & 0 & 1 \end{pmatrix} =
\begin{pmatrix}
c & -s & \beta \\
s & c & \gamma \\
0 & 0 & 1 \end{pmatrix} $$
It then becomes a simple matter of solving for $C_x$ and $C_y$. But the result I'm finding is
$C_y = \dfrac{\beta+C_x(c-1)}{s}$
$C_x = \dfrac{C_y(c-1)-\gamma}{s}$
However, working on from here, the results I'm getting give the center as a function of the angle of rotation, which would mean that, as the rotation occurs, the center is moving, which is obviously incorrect.
So, how can this be done?
I have seen the these questions (1, 2 and 3) but they all deal with X = TRS (S = scale). My question actually seems simpler than these, but I just can't figure it out.

A: Starting with the upper right block from the comparison $X = (..)$:
\begin{align}
X_{13} &= C_x (1-c) + C_y s=  \beta \\
X_{23} &= -C_x s + C_y(1-c) = \gamma
\end{align}
and rewriting it as matrix equation with unknowns $C_x$, $C_y$:
$$
\left(
\begin{matrix}
1-c & s \\
-s & 1-c
\end{matrix}
\right)
\left(
\begin{matrix}
C_x \\
C_y
\end{matrix}
\right)
=
\left(
\begin{matrix}
\beta \\
\gamma
\end{matrix}
\right)
$$
Using matrix inversion I get
$$
\left(
\begin{matrix}
C_x \\
C_y
\end{matrix}
\right)
=
\left(
\begin{matrix}
\frac{1}{2} & -\frac{s}{2(1-c)} \\
\frac{s}{2(1-c)} & \frac{1}{2}
\end{matrix}
\right)
\left(
\begin{matrix}
\beta \\
\gamma
\end{matrix}
\right)
\quad (*)
$$
and
$$
\theta = \arccos c = \arcsin s \quad (**)
$$
So a given $X$ gives $c = X_{11}, s = X_{21}, \beta = X_{13}, \gamma = X_{23}$ and can be used with the above equations to yield $C_x, C_y, \theta$, if $c \ne 1$.
The case $c = 1$ is for $X = I$, $\theta = 0$ where we do not need this transformation.
Example:
Given this matrix $X$:
$$
X =
\left(
\begin{matrix}
0.70712315999226 & -0.70709040200144 & 2.707024886019803 \\
0.70709040200144 &  0.70712315999226 & -0.53555028397966 \\
0 & 0 & 1
\end{matrix}
\right)
$$
we read
\begin{align}
c &= 0.70712315999226 \\
s &= 0.70709040200144 \\
\beta &= 2.707024886019803 \\
\gamma &= -0.53555028397966
\end{align}
Using equation $(**)$ gives $\theta = 0.785375$ and using equation $(*)$ gives
$C_x = 1.999999999999993$ and $C_y = $2.999999999999991.
And indeed I used a translation matrix $T$ with $C_x =2$ and $C_y = 3$ and a rotation matrix with $\theta = \pi / 4$ to generate $X = T\, R \, T^{-1}$.


text:
Q: Score of randomizedlasso() in scikit-learn I want to know what does the 'score' parameter mean in randomizedlasso().

*

*make 200 random subsets with training data (default)

*run lasso() on each subsets

*delete features of 0 parameter vector from subsets

*make union list of features from subsets

*score of feature F is (number of subsets F remains / 200). If F is remaining only one subset, the score will be 0.005

Is it right understanding?


text:
Q: jQuery Class Function not updating correctly?

jQuery.fn.areAll = function(arg) {
  return this.get().every(function(e) {
    return $(e).is(arg);
  });
};

$(document).ready(function() {

  function hidden_all() {

    if ($('.hidden_1, .hidden_2, .hidden_3').areAll(':visible')) {
      $(".togglehidden_all").removeClass("show").addClass("hide");
    } else if ($('.hidden_1, .hidden_2, .hidden_3').areAll(':hidden')) {
      $(".togglehidden_all").removeClass("hide").addClass("show");
    }
  }

  $(".hidden_all").click(function() {

    if ($(".hidden_1, .hidden_2, .hidden_3").areAll(":visible")) {
      $(".togglehidden_all").removeClass("show").addClass("hide");
    } else if ($(".hidden_1, .hidden_2, .hidden_3").areAll(":hidden")) {
      $(".togglehidden_all").removeClass("hide").addClass("show");
    }
  });

  $(".togglehidden_all").click(function() {

    if ($(".hidden_1, .hidden_2, .hidden_3").areAll(":visible")) {
      $(".hidden_1, .hidden_2, .hidden_3").slideUp("slow");
      $(".togglehidden_1, .togglehidden_2, .togglehidden_3").removeClass("show").addClass("hide");
      $(".togglehidden_all").removeClass("hide").addClass("show");
    } else {
      $(".hidden_1, .hidden_2, .hidden_3").slideDown("slow");
      $(".togglehidden_1, .togglehidden_2, .togglehidden_3").removeClass("hide").addClass("show");
      $(".togglehidden_all").removeClass("show").addClass("hide");
    }
  });

  $(".togglehidden_1").click(function() {

    if ($(".hidden_1").is(":visible")) {
      $(".hidden_1").slideUp("slow");
      $(".togglehidden_1").removeClass("show").addClass("hide");
      hidden_all();
    } else {
      $(".hidden_1").slideDown("slow");
      $(".togglehidden_1").removeClass("hide").addClass("show");
      hidden_all();
    }
  });

  $(".togglehidden_2").click(function() {

    if ($(".hidden_2").is(":visible")) {
      $(".hidden_2").slideUp("slow");
      $(".togglehidden_2").removeClass("show").addClass("hide");
      hidden_all();
    } else {
      $(".hidden_2").slideDown("slow");
      $(".togglehidden_2").removeClass("hide").addClass("show");
      hidden_all();
    }
  });

  $(".togglehidden_3").click(function() {

    if ($(".hidden_3").is(":visible")) {
      $(".hidden_3").slideUp("slow");
      $(".togglehidden_3").removeClass("show").addClass("hide");
      hidden_all();
    } else {
      $(".hidden_3").slideDown("slow");
      $(".togglehidden_3").removeClass("hide").addClass("show");
      hidden_all();
    }
  });

});
.show {
  color: white;
  background-color: green;
}

.hide {
  color: white;
  background-color: red;
}

      +/-

      1

      2

      3

      4

      5

      6

      hidden_all click function Test

Note : Click the "+/-" first to give initial classes for this example.
Clicking on "+/-" shows/hides divs 2, 4 and 6 all together
Clicking on div1 toggles show/hide div2
Clicking on div3 toggles show/hide div4
Clicking on div3 toggles show/hide div4
When div1, div2, and div3 are all opened one by one the "+/-" updates to the hide class (red). However, when they are all closed one by one it does not update to the show class (green). Ie it does not work in reverse strangely
(It will update correctly if I run the function manually via $(".hidden_all").click(function() i.e. clicking on "hidden_all click function Test". As such I tried triggering this function from within the other functions but it had no effect on the problem).
Thanks in advance.

A: LEFT THIS answer IN for ORIGINAL markup.
I found your code somewhat busy, forgive me for that so I reworked it a bit.   I also put the animation in a function to make it easier to call.
$(document).ready(function() {
  var allthem = $('.hidden_1, .hidden_2, .hidden_3');

  function hidden_all() {
    $(".togglehidden_all")
      .toggleClass("show", allthem.areAll(':visible'))
      .toggleClass("hide", allthem.areAll(':hidden'));
  }
  jQuery.fn.areAll = function(arg) {
    return this.get().every(function(e) {
      return $(e).is(arg);
    });
  };
  jQuery.fn.slideToggleBool = function(bool, options) {
    return bool ? $(this).slideDown(options, hidden_all) : $(this).slideUp(options, hidden_all);
  };
  $(".hidden_all").click(function() {
    hidden_all();
  });
  $(".togglehidden_all").click(function() {
    var isall = allthem.areAll(":visible");
    allthem.slideToggleBool(!isall, "slow");
    $(".togglehidden_1, .togglehidden_2, .togglehidden_3")
      .toggleClass("show", isall)
      .toggleClass("hide", !isall);
  });
  $(".togglehidden_1, .togglehidden_2, .togglehidden_3").on('click', function() {
    // to keep ref inside the done where "this" is the animating one
    var me = $(this);
    $(this).closest('tr').next('tr').find('td').promise().done(function() {
      // will be called when all the animations on the queue finish
      var isVis = $(this).is(":visible");
      me.closest('tr').next().slideToggleBool(!isVis, "slow");
      me.toggleClass("show", !isVis).toggleClass("hide", isVis);
    });
  });
});

I also further made the last 3 functions one reworked that to find a relatively positioned element from the one clicked.  Note the if you clicked quickly on the elements (single) they would also have issues with the toggle, the animation on that one not completing.  This also should address that in that last function.
I did minimal testing to check for other issues.

A: This is my working code.
If you are able to simplify that would be great. Ideally I would like the sub toggles to open/close all rows between sub toggles. Also some sort of counter that will work with any number of sub toggles to flip the main toggle if a % of the sub toggles are either hidden or visible.
Thanks

<!DOCTYPE html>

+/-

1

2

3

4

5

6

A: I see you have modified your structure and can/are not opposed to changes to the markup.  With that in mind, I set some classes and use them to simplify the code.  I also allowed for initial "state" with classes on the toggle buttons of "show", "hide".
You can add a new "group" of toggles just by adding a new row pair, no special "class" so no need to modify code.
A fiddle to see it in action: https://jsfiddle.net/MarkSchultheiss/ud99cf0u/5/
Revised markup:

      +/-

      1

      2

      3

      4

      5

      6

Revised code, note it has some initial "state" setting to allow for any markup/visibility and let that drive that initial visibility and class state.  That is a good bit of this code.  The last two do all the "active" work/event handling.
$(document).ready(function() {
  // simple extenders to use
  jQuery.fn.areAll = function(arg) {
    return this.filter(arg).length === this.length;
  };
  jQuery.fn.slideToggleBool = function(bool, options) {
    return (bool ? $(this).slideDown(options) : $(this).slideUp(options));
  };
  // cache these for use
  var allthem = $('.hideme');
  var allToggles = $('.toggle-hide');
  // set initial state of toggles and associated element, respects classes present
  allToggles.each(function() {
    var isShow = $(this).hasClass("show");
    if (isShow) {
      $(this).parents('tr').next().find('td.hideme').hide();
    } else {
      $(this).toggleClass("hide", !isShow);
    }
  });
  // used to set the "all" +/- button state
  function hidden_all() {
    var areVis = allthem.areAll(':visible');
    var allHidden = allToggles.filter(":hidden").length == allToggles.length;
    $(".togglehidden_all")
      .toggleClass("show", !allHidden)
      .toggleClass("hide", areVis && !allHidden);
    return !areVis;
  }

  // set initial "+/-" button color
  hidden_all();

  // these two do all the work
  $(".togglehidden_all").on('click', function() {
    var vis = hidden_all();
    $(this).toggleClass("show", !vis).toggleClass("hide", vis);
    allthem.slideToggleBool(vis, "slow");
    allToggles
      .toggleClass("show", !vis)
      .toggleClass("hide", vis);
  });
  $(".toggle-hide").on('click', function() {
    var myTarget = $(this).parents('tr').next().find('td.hideme');
    var isVis = myTarget.is(":visible");
    myTarget.slideToggleBool(!isVis, "slow");
    $(this).toggleClass("show", isVis).toggleClass("hide", !isVis);
  });
});


text:
Q: How can I call the controls of a form from another form in winforms I have a form called frmDSNMain and another form called frmChainedRun I want to access the DataGridView present in the frmChainedRun form from the frmDSNMain form. I tried to call directly by the form name as frmChainedRun.gridName.Rows.Count from the DSNMain. But I am not able to fetch:
If frmChainRun.rbtnPredefinedModule.Checked = True Then
    If frmChainRun.grdPredefined.Rows.Count > 0 Then
        For Each row As DataGridViewRow In frmChainRun.grdPredefined.Rows
            Dim isSelected As Boolean = Convert.ToBoolean(row.Cells(0).Value)
            If isSelected Then
                row.Cells(0).Value = False
            End If
        Next

    End If

ElseIf frmChainRun.rbtnCustomModule.Checked = True Then

End If


text:
Q: Django Unable to access LiveServerTestCase (code 500) I was following Django docs, but am still having problem with this example - I get 500 Internal server error when accesing the live server with Selenium.
My code:
import os

try:
    browser_driver = os.environ['BROWSER_DRIVER']
except KeyError:
    raise ValueError("BROWSER_DRIVER env variable not specified. \nPlease specify path to your "
                     "browsers driver, more information: "
                     "https://selenium-python.readthedocs.io/installation.html#drivers")

os.environ["PATH"] += browser_driver

from django.contrib.staticfiles.testing import LiveServerTestCase
from selenium import webdriver

class TestMostCommonUserActions(LiveServerTestCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.selenium = webdriver.Chrome()
        cls.selenium.implicitly_wait(10)

    @classmethod
    def tearDownClass(cls):
        cls.selenium.quit()
        super().tearDownClass()

    def test_slicing_is_possible_after_adding_and_subtracting_custom_slicing_info(self):
        # Here is the problem
        self.selenium.get('%s%s' % (self.live_server_url, '/'))
        pass

When I run my server on localhost and try to access with selenium localhost on port 8000, it works. But shouldn't be the whole point of LiveServerTestCase to not to have the real django server?

A: your home page view is probably the problem. template_name might be incorrect.
I have a similar problem, was able to access but the LiverServerTestCase/live_server_url couldn't load my context variable to display on the page...it seems like this is a django 3 problem...not many people got this problem yet


text:
Q: Rails 3.1+ nested form model not rendering properly I have a basketball app, where a Roster has many Players, and a Player belongs to a Roster.
Roster.rb
class Roster < ActiveRecord::Base
  has_many :players
  accepts_nested_attributes_for :players
  attr_accessible :class_year, :jersey_number, :player_id, :team_id
end

Player.rb
class Player < ActiveRecord::Base
  has_many :gamelogs
  belongs_to :rosters
  validates_presence_of :first_name, :last_name
  attr_accessible :first_name, :last_name, :active
end

And my view that is only rendering first part of the form, but NOT the nested one

New Player

    <%= simple_form_for @new_player, :html => { :class => 'form-horizontal' } do |f| %>
        <%=f.simple_fields_for :players do |x|%>
            <%= x.input :first_name %>
            <%= x.input :last_name %>
        <%end%>
        <%=f.input :class_year %>
        <%=f.input :jersey_number %>
        <%=f.input :team_id, :as => :hidden, :input_html => {:value => params[:id]}%>

        <%= f.button :submit, :class => 'btn-primary icon-plus-sign btn-success', :value => "Add To Team" %>

    <%end%>

Image of it not working:
http://i.stack.imgur.com/Uoirp.png
I am using Simple_Form 2.0 and Twitter Boot Strap. Is there something I am not seeing? I feel like this should be simple, but I can't seem to figure out why it is not rendering. Thanks in advance.

A: You need an equal sign on your fields_for block:
<%= f.simple_fields_for :players do |x| %>

Edit:
All of this is assuming that @new_player == Roster.new
I had to do this with Formtastic, so it may be similar with Simple Form.
Looking at the source, it gives you an option to pass the nested object down to the nested form:
def simple_fields_for(record_name, record_object = nil, options = {}, &block)

So try doing something like this:
<%= f.simple_fields_for :players, @new_player.players.build do |x| %>


text:
Q: Git checkout can't auto-complete with bash I'm using ubuntu with bash. When I typed git checkout then press tab, I expected it would show a list of branches, but I got:
git checkout
bash: eval: line 345: unexpected EOF while looking for matching `''
bash: eval: line 346: syntax error: unexpected end of file

I googled it but found nothing. And bash even doesn't tell me where is the line 345. Anyone knows what's wrong?
EDIT:
When I set -x to bash and then git checkout [tab], it outputs:
+++ case "$c$2" in
+++ printf '%s
' 'feature/capybara '
+++ for c in '$1'
+++ case "$c$2" in
+++ printf '%s
' 'feature/chinese-search '
+++ for c in '$1'
+++ case "$c$2" in
+++ printf '%s
' 'feature/comment_validation '
+++ for c in '$1'
+++ case "$c$2" in
+++ printf '%s
' 'feature/comments '

...and so on. No error. But I still can't use autocompletion normally.

A: Try set -x in bash:
-x   Print commands and their arguments as they are executed.

This should show you what code fails, as it will show what kind of work bash completion does in the background.


text:
Q: How to stop the playing of a sound in R Shiny When playing a sound I would like to have the possibility to stop this with another button. Or when pressing the play button again, the playing of the sound should stop, and then played from the beginning.
I struggled implementing this in R Shiny using shinyjs but did not succeed. This is my code:
library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),

  shiny::actionButton('sound'  ,'Play sound'),
  shiny::actionButton('stopper','Stop sound')
)

server <- function(input, output) {
  observeEvent(input$sound,
  {
    shinyjs::runjs("snd.pause();")
    shinyjs::runjs("var snd = new Audio('https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3'); snd.play();")
  })

  observeEvent(input$stopper,
  {
    shinyjs::runjs("snd.pause();")
  })
}

shinyApp(ui = ui, server = server)

The code is inspired by the code at: https://community.rstudio.com/t/how-to-stop-audio-with-shinyjs/122650.
So the idea is that after pressing the 'Play sound' button the play can be stopped prematurely with the 'Stop sound' button, or when prematurely pressing the 'Play sound' button the playing should stop and subsequently start from the beginning.
Is this somehow possible?

A: The fix is very easy, you need to define snd globally before you call in shinjs, instead of defining it in the shinyjs.
library(shiny)
library(shinyjs)

ui <- fluidPage(
    useShinyjs(),

    shiny::actionButton('sound'  ,'Play sound'),
    shiny::actionButton('stopper','Stop sound'),
    tags$script("var snd;")
)

server <- function(input, output) {
    observeEvent(input$sound,
                 {
                     shinyjs::runjs("snd.pause();")
                     shinyjs::runjs("snd = new Audio('https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3'); snd.play();")
                 })

    observeEvent(input$stopper,
                 {
                     shinyjs::runjs("snd.pause();")
                 })
}

shinyApp(ui = ui, server = server)

The reason is each runjs is inside different function call scope; when you want to use snd in another runjs, it is undefined because current scope or parent scopes do not have this variable, so you want to define it globally first. You may want to search for more details on how scoping works in JS.


text:
Q: Should I use SQL Server DMVs with NOLOCK I am trying to monitor live performance data and usage, which cannot be tracked with PerformanceMonitor. What are the consequences of reading DMVs in a production live OLTP database? : Eg: sys.dm_tran_locks, sys.dm_os_waiting_tasks, sys.dm_os_performance_counters, sys.dm_exec_connections, sys.dm_io_virtual_file_stats,  sys.dm_exec_sql_text,etc
Should I just utilize WITH (NOLOCK) when querying Dmvs? Would this resolve many of the resource issues? Is there anything such as dirty read rollbacks in DMVs. I know it can exist in applications tables eg where someone submits an order then cancels, etc. Additionally, with NOLOCK, is there higher chance query will continue forever in high volume environment since I am not locking rows, pages, and things will continue be added into DMV TableView?
Thank you,

A:
What are the consequences of reading DMVs in a production live OLTP database?

Negligible as far as my experience goes. DMV's as the name suggests are basically views or functions ( like sys.dm_db_index_physical_stats ) which get information from various caches and system tables. DMV's are very light and read data from caches. They do not cause blocking and depending on amount of data you need to fetch they very very quick. The point here is always only query data from caches which you actually need.
You may use NOLOCK hint in your DMV query you would see some people using it but frankly I do not see much of need to use it with DMV's. Its function though still remains same. So when you use NOLOCK hint you say to SQL Server that give me the data I am asking no matter what is state of the data is. It may have been changed and yet not committed so you get "dirty" data. NOLOCK hint avoids select queries taking shared lock while reading data. The drawbacks are many

Additionally, with NOLOCK, is there higher chance query will continue forever in high volume environment since I am not locking rows, pages, and things will continue be added into DMV TableView?

Query will only continue for duration until it finishes its task, unless you run a never ending loop. The NOLOCK only ensures that query is minimally blocked and also note that when using NOLOCK if required other locks like schema stability  are taken

A: I found this article whilst researching blocking on using DMV during system upgrades.
Consider:
alter table X Add (y bit)

This will take a SCH_M lock on table X (and remain until transaction is committed/rolled back)
if you try and run
select * from sys.dm_exec_query_stats
cross apply sys.dm_exec_sql_text(sql_handle)

You will be blocked until the previous transaction completes. NOLOCK won't help you here, because the locked being taken is a SCH_S which you cannot avoid.


text:
Q: Why am I getting an incorrect value for the file size in my script? I'm trying to get the size of files in a bash script on OS X.  If I explicitly specify the file's name, I get the correct answer.  If I try to do this looping thing, I get an incorrect answer.  This bash script is part of a folder action in Automator and I need to not set the name explicitly because the contents of the folder will change.
This gives me the correct answer:
function get_file_size {
    filesize1=$(stat -f%z "/Users/jcoulson/Nexus Transfer/Test.mpeg")
    echo $filesize1
}
for f in "/Users/jcoulson/Nexus Transfer/"
do
    get_file_size
done

This gives me an answer of 136:
function get_file_size {
    filesize1=$(stat -f%z "$f")
    echo $filesize1
}
for f in "/Users/jcoulson/Nexus Transfer/"
do
    get_file_size
done

EDIT: The problem must be with stat.  If I just put echo "found something" in place of get_file_size, I see the text echo.

A: Variables are OK, but you forgot the * wildcard, so you'r stat'ing directory instead of file
function get_file_size {
    filesize1=$(stat -f%z "$f")
    echo $filesize1
}
for f in "/Users/jcoulson/Nexus Transfer/*"
do
    get_file_size
done

A: I think what you want is
function get_file_size {
    filesize1=$(stat -f%z "$1")
    echo $filesize1
}
for f in "/Users/jcoulson/Nexus Transfer/"
do
    get_file_size $f
done

$1 refers to the first parameter, and putting $f after get_file_size will call it with $f as the first param

A: For anyone stumbling across this in the future, here's my finished script:
function get_file_size {
    filesize1=$(stat -f%z "$f")
    echo $filesize1
}
for f in /Users/jcoulson/NexusTransfer/*
do
    get_file_size
done


text:
Q: Android blank map I am trying to use Map Api v2 for few days but didn't have any success. Here is my code:
My HelloGoogleActivity.java:
package com.example.hellogooglemap;

import android.os.Bundle;

import com.google.android.maps.MapActivity;

public class HelloGoogleActivity extends MapActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_hello_google);
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}

My HelloGoogleMap.Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.hellogooglemap"
    android:versionCode="1"
    android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="19" />

<permission
    android:name="com.example.hellogooglemap.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />

<uses-permission android:name="com.example.hellogooglemap.permission.MAPS_RECEIVE" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

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

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="XXXXXyCWfP6QJkMxpQjITsn3IVYT1J_t8UxMohU" />

    <uses-library android:name="com.google.android.maps" />

    <activity
        android:name="com.example.hellogooglemap.HelloGoogleActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

My fragment_hello_google.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

<com.google.android.maps.MapView
    android:id="@+id/mapView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:apiKey="AIzaSyCWfP6QJkMxpQjITsn3IVYT1J_t8UxMohU"
    android:clickable="true"
    android:enabled="true" />

And my activity_hello_google.xml :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.hellogooglemap.HelloGoogleActivity"
    tools:ignore="MergeRootFrame" />

When I ran this application I got a blank map like this: http://i.stack.imgur.com/B7H4G.jpg
and i have checked several time my apiKey.
So what should I do ?

A: If you are using MapView, you need to implement this in your onCreate() method or in onResume().
MapsInitializer.initialize(Activity);
yourMapView.onCreate(savedInstanceState);


text:
Q: Is the following a subgroup of the given group? $G=(\Bbb Z, +)\times (\Bbb Q\setminus \{0\},\cdot)$ and $U=\{(a,b)\in G\mid b=2^a\}$
Can I get some help on how to approach this .
I know that the product of 2 groups is a group.
I know that I have to check: $f,g\in U\implies fg^{-1}\in U$

A: A lazy solution: Given $a\in\mathbb{Z}$, there is a unique $b\in\mathbb{Q}$ for which $(a,b)\in U$, namely $b=2^a$. The map $2^\ast:a\mapsto 2^a$ is a morphism, so $U$ is the image of the morphism $(1,2^\ast):\mathbb{Z}\to G$.


text:
Q: NavHostFragment.findNavController throw: Method addObserver must be called on the main thread I have another Fragment where this function work. But when i receive a response by the server the program crash and return this exeception. I'm new in android, so i don't really catch the meaning and the funtion of the Navigation tools. I don't know if other file are needed for a solution, by the way you can ask to post other details.
EDIT: i found out that the problem is that i tried to change fragment by another thread. I usually get this error while working with javaFX. is there any function similiar to the "Platform.runlater()"???
SOLVED:
  getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            NavHostFragment.findNavController(LoginFragment.this).navigate(R.id.action_LoginFragment_to_FirstFragment);
                        }
                    });

on the Fragment:
 @Override
        public void onResponse(Call call, Response response) throws IOException {
            String sessione = "";
            String email = "";
            try {
                String msg = response.body().string();
                JSONObject obj = new JSONObject(msg);
                sessione = obj.getString("message");
                if (sessione.equals("sessione esistente")) {
                    email = obj.getString("email");
                    NavHostFragment.findNavController(LoginFragment.this).navigate(R.id.action_LoginFragment_to_FirstFragment);
                    //intent.putExtra("user", email);
                    //startActivity(intent);
                }
                Looper.prepare();
                Toast.makeText(getContext(), sessione, Toast.LENGTH_SHORT).show();
                Looper.loop();
            } catch (JSONException e) {
                System.out.println("Errore onResponse ----> " + e.getMessage());
                Toast.makeText(getContext(), sessione, Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        }});

nav_graph.xml:
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/nav_graph"
            app:startDestination="@id/FirstFragment">

    <fragment
            android:id="@+id/FirstFragment"
            android:name="com.example.progetto.FirstFragment"
            android:label="@string/first_fragment_label"
            tools:layout="@layout/fragment_first">

        <action
                android:id="@+id/action_FirstFragment_to_SecondFragment"
                app:destination="@id/SecondFragment"/>
    </fragment>

    <fragment
            android:id="@+id/SecondFragment"
            android:name="com.example.progetto.SecondFragment"
            android:label="@string/second_fragment_label"
            tools:layout="@layout/fragment_second">

        <action
                android:id="@+id/action_SecondFragment_to_FirstFragment"
                app:destination="@id/FirstFragment"/>
    </fragment>

    <fragment
            android:id="@+id/nav_home"
            android:name="com.example.progetto.FirstFragment"
            android:label="@string/menu_home"
            tools:layout="@layout/fragment_first">
    </fragment>
    <fragment
               android:id="@+id/nav_login"
               android:name="com.example.progetto.LoginFragment"
               android:label="@string/login"
               tools:layout="@layout/activity_login_page">
        <action
                android:id="@+id/action_LoginFragment_to_FirstFragment"
                app:destination="@id/FirstFragment"/>
    </fragment>

    <fragment
        android:id="@+id/nav_myLesson"
        android:name="com.example.progetto.myLesson.myLessonFragment"
        android:label="@string/menu_myLesson"
        tools:layout="@layout/fragment_my_lesson">
    </fragment>
</navigation>

A: In android if you want a piece of code to run on the main thread, you can use a coroutine scope with dispatcher context as MAIN. eg -
CoroutineScope(Dispatchers.Main).launch {
    stuffYouWantOnTheMainThread()
}

This would run the code on the main thread regardless of whether this code is located within another thread


text:
Q: Error While decoding ! The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters Error :- Error While decoding !  "The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters."
Encoded string :-
string decode = "spfvXsVSFt8ezoBjPFYY3CO8hww4NqHbaOjagLuO3ihLhHU4HLIbxcq69IcXkWZAoauZh7PeAjlLD6ToWA1iFy0QprEG5Myrc8RlndhHOX6akN9qKhk2\/kKZkoGNlZwKtNK7d6qVRrmJHUXm3p010QaHL9zP4eE2jnwPy6OKOFUfwarx6S1eddQznRBDE+7lVZVBxPdqbqPCAVH5zumJySUD8RwmVbk4unJ1GgRnKhy+tSzcxJAdLzAT0rpZhkix7fOnqp0z6jffHDciHVcHl\/C+0gv9lSzHkckTvPRV13E0hqv7aeecYmJbJcwJ2Kjw61xkkwKpDSwCTsya0nmBs+8KXpjhviowKmwfe20p\/aYGxKI+eyzLBhijQzJ207fDpAED\/29tCPvddG\/KH3wcQMw5KoeQ3LVFcyfVTKakUJ04EVFtfQDESO+964cVIqCBoL7ZPX872vZDIJVRATtKGP9hLPBB0goK9lpSncnBgvJFK+k8UbGLPxZsQCC8dsY0059lM40LnQUQpSeqZ4tkrQfJ5eE9dNCcyoPmDFFyzCHRJNscGqUAFhWvI0PxK7PLsyeJ+Ka3TKg6Wbp5\/ApCgvqx1nhN4SJMt3a\/mWfC3wSsL6YpPsbNLzTRkwX9Ct7hv2kAiCq8R3eEmVfqmTvmQ70JCVPhKW9hUAn+QRhd1EAvEwLpDQstZrGDWmacl7h9jx5xZRXRUDSUbbLvddm3U6\/N0uUENVBf6fIfrqNkgYM=";

Calling DecryptString method:-
 string decrypted = DecryptString(decode, key, iv);

DecryptString Method Logic:-
public string DecryptString(string cipherText, byte[] key, byte[] iv)
        {
            // Instantiate a new Aes object to perform string symmetric encryption
            Aes encryptor = Aes.Create();

            encryptor.Mode = CipherMode.CBC;
            //encryptor.KeySize = 256;
            //encryptor.BlockSize = 128;
            //encryptor.Padding = PaddingMode.Zeros;

            // Set key and IV
            encryptor.Key = key;
            encryptor.IV = iv;

            // Instantiate a new MemoryStream object to contain the encrypted bytes
            MemoryStream memoryStream = new MemoryStream();

            // Instantiate a new encryptor from our Aes object
            ICryptoTransform aesDecryptor = encryptor.CreateDecryptor();

            // Instantiate a new CryptoStream object to process the data and write it to the
            // memory stream
            CryptoStream cryptoStream = new CryptoStream(memoryStream, aesDecryptor, CryptoStreamMode.Write);

            // Will contain decrypted plaintext
            string plainText = String.Empty;

            try
            {

                // Convert the ciphertext string into a byte array
           byte[] cipherBytes = Convert.FromBase64String(cipherText);  //getting Padding error

                // Decrypt the input ciphertext string
                cryptoStream.Write(cipherBytes, 0, cipherBytes.Length);

                // Complete the decryption process
                cryptoStream.FlushFinalBlock();

                // Convert the decrypted data from a MemoryStream to a byte array
                byte[] plainBytes = memoryStream.ToArray();

                // Convert the decrypted byte array to string
                plainText = Encoding.ASCII.GetString(plainBytes, 0, plainBytes.Length);
            }
            finally
            {
                // Close both the MemoryStream and the CryptoStream
                memoryStream.Close();
                cryptoStream.Close();
            }

            // Return the decrypted data as a string
            return plainText;
        }

In the above example while I'm converting the encrypt string to decrypt string I'm getting the padding error
Give me your best suggestion to achieve this without error.
I'm new to this kind of decrypt logic's.


text:
Q: How to make the Springboot's ShutdownHook wait, till all of its processing requests are completed? I am running my Spring boot web application inside the docker container and every time we safely stop the container, it abruptly shut down the running spring-boot service(Default behavior). My requirement is to process the existing requests without any issues. I have tried the below approach something like adding sleep logic for some minutes in ContextClosedEvent, so that the existing requests have time to serve the response, but the following approach doesn't stop the requests incoming even after the shutdown got initiated. is there any specific way to achieve my requirement?
@Slf4j
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(Application.class);
        application.addListeners((ApplicationListener<ContextClosedEvent>) event -> {
            log.info("Shutdown initiated...");
            try {
                Thread.sleep(TimeUnit.MINUTES.toMillis(5));
            } catch (InterruptedException e) {
                log.error("Exception is thrown", e);
            }
            log.info("Graceful Shutdown is processed succesfully");
        });
        application.run(args);
    }

A: Sharing my approach. Let's say you are using the Springboot application as a web app, and you want to process the existing requests without abruptly terminating them, spring boot provides the out-of-box solution.
An excerpt from Spring doc

Graceful shutdown is supported with all four embedded web servers (Jetty, Reactor Netty, Tomcat, and Undertow) and with both reactive and Servlet-based web applications. It occurs as part of closing the application context and is performed in the earliest phase of stopping SmartLifecycle beans. This stop processing uses a timeout which provides a grace period during which existing requests will be allowed to complete but no new requests will be permitted. The exact way in which new requests are not permitted varies depending on the web server that is being used. Jetty, Reactor Netty, and Tomcat will stop accepting requests at the network layer. Undertow will accept requests but respond immediately with a service unavailable (503) response.

NOTE:   Graceful shutdown with Tomcat requires Tomcat 9.0.33 or later.
Code Snippet
To enable graceful shutdown
server.shutdown=graceful

To configure the timeout period(here I set the time values as 1minute)
spring.lifecycle.timeout-per-shutdown-phase=1m

Console output:
[INFO] [SpringContextShutdownHook] [org.springframework.boot.web.embedded.tomcat.GracefulShutdown:53] Comme
ncing graceful shutdown. Waiting for active requests to complete

...logs of existing running API endpoints

[tomcat-shutdown]   [org.springframework.boot.web.embedded.tomcat.GracefulShutdown:78] Graceful shut
down complete
[SpringContextShutdownHook] [org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor:218] S
hutting down ExecutorService 'applicationTaskExecutor'

From the above logs, you could see that the spring boot waits for all the running requests to process and shut the server gracefully


text:
Q: VideoJS Flash Version doesn't Play Files (PHP Passthrough Stream) I am Using the newest Version of VideoJS and Put my Videos Through PHP in the Following way:
Called like: $this->streaming->handleDownload($videoPath, "video/mp4");
The Function is defined like:
public function handleDownload($file, $mime = "") {
     if (is_file($file)) {
        header("Content-Type: $mime");

        if (isset($_SERVER['HTTP_RANGE']))  { // do it for any device that supports byte-ranges not only iPhone
            header("X-Info: Starting Ranged Download of $file");
            $this->rangeDownload($file);
        } else {
            header("Content-Length: ".filesize($file));
            header("X-Info: Starting Straight Download of $file");
            readfile($file);
        }
    } else {
        header("HTTP/1.1 500 Internal Server Error");
        $msg = "The requested path was no file!";
    }
}

The rangeDownload() is defined:
private function rangeDownload($file) {
    ob_end_clean();
    $fp = @fopen($file, 'rb');

    $size   = filesize($file); // File size
    $length = $size;           // Content length
    $start  = 0;               // Start byte
    $end    = $size - 1;       // End byte

    header("Accept-Ranges: 0-$length");
    if (isset($_SERVER['HTTP_RANGE'])) {

        $c_start = $start;
        $c_end   = $end;
        // Extract the range string
        list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
        // Make sure the client hasn't sent us a multibyte range
        if (strpos($range, ',') !== false) {
            header('HTTP/1.1 416 Requested Range Not Satisfiable');
            header("Content-Range: bytes $start-$end/$size");
            exit;
        }
        header("X-Got-Range: $range, $range0");
        // If the range starts with an '-' we start from the beginning
        // If not, we forward the file pointer
        // And make sure to get the end byte if spesified
        if ($range0 == '-') {
            $c_start = $size - substr($range, 1);
        } else {
            $range  = explode('-', $range);
            $c_start = $range[0];
            $c_end   = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
        }

        // End bytes can not be larger than $end.
        $c_end = ($c_end > $end) ? $end : $c_end;
        // Validate the requested range and return an error if it's not correct.
        if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {

            header('HTTP/1.1 416 Requested Range Not Satisfiable');
            header("Content-Range: bytes $start-$end/$size");
            // (?) Echo some info to the client?
            exit;
        }
        $start  = $c_start;
        $end    = $c_end;
        $length = $end - $start + 1; // Calculate new content length
        fseek($fp, $start);
        header('HTTP/1.1 206 Partial Content');
    }

    // Notify the client the byte range we'll be outputting
    header("Content-Range: bytes $start-$end/$size");
    header("Content-Length: $length");

    // Start buffered download
    $buffer = 1024 * 8;
    while(!feof($fp) && ($p = ftell($fp)) <= $end) {

        if ($p + $buffer > $end) {

            // In case we're only outputtin a chunk, make sure we don't
            // read past the length
            $buffer = $end - $p + 1;
        }
        set_time_limit(0); // Reset time limit for big files
        echo fread($fp, $buffer);
        flush(); // Free up memory. Otherwise large files will trigger PHP's memory limit.
    }

    fclose($fp);
}

I am Passing the Video through PHP, because the Files should be only Visible when Logged In.
I do the things with the Partial Content/Ranges because I want to be able to Click in the Middle of The Position bar and The Video should start to play from there.
That all works well with Chrome, Newer Safari, iOS, but (Because of the Flash Fallback) doesn't work in IE or Firefox (Video is mp4) (Perhaps it only takes TOO long to load)
The Range Works in Chrome, but well, the Flash Version of VideoJS doesn't even Ask for the Range-Download, so it gets the other Version.
If I play the Video directly (With PHP-streaming, but Without VideoJS) in Firefox (Just call the Video-URL in the URL Bar) it Starts directly and Loads while it Plays; VideoJS doesn't
What do I need to change that the Videos starts to Play directly in VideoJS Flash-Version?

A: I have found the Solution (by accident ;-) )
The Problem was, that The Flash-Player asks for The Video as a Complete File. As Long as The Server doesn't answer, that there are Streaming-Versions Available (Accept-Ranges: 0-$size) the Player doesn't Ask for them.
So I set the Header and it Worked.
So All a small Tutorial for all that have Problems with VideoJS Flash Fallback:

*

*Videos need to be encoded via MP4Box (See MP4 in Video.js not playing until fully loaded)

*The PHP Passthrough Script needs to send following Headers:
header("Content-Type: $videoMimeType");
header("Content-Length: $videoByteCount");
header("Accept-Ranges: 0-$videoByteCount");

*If You want to handle the Range (Identified by isset($_SERVER["HTTP_RANGE"]) ) you need also to specify those headers:
header("Content-Range: bytes $startByte-$endByte/$videoByteCount");
This works for me (See Code in my Question). It works with Chrome, FF, iOS, Safari (IE not tested yet) with Flash and HTML5 with mp4-Files


text:
Q: How to dismiss keyboard before pushing UIViewController in navigationController My view contains UITableViewController which has UITextFields where some text can be entered. I adjust UITableView height when keyboard appears/disappears. It works great.
Now I have UIAlertView with UITextField in it. User enters text in UITextField in UIAlertView & when Ok is pressed, I push another  UIViewController. The problem is when I come back to the view it's screwed. The reason is with KeyboardWillHide notification is never fired & hence the height of tableView is application frame height - keyboard height.
Any suggestions for fixing it? I called [resignFirstResponder]  in - (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex but didn't help. I even forcefully called KeyboardWillHide but that also didn't help.
Any suggestions?

A: I was calling removerObserver in viewWillDisappear. viewWillDisappear was getting called before keyboardWillHide was getting called.
The solution was move removeObserver to viewDidDisappear. That did the trick.


text:
Q: How to make a loop in Android using Retrofit to avoid inserting data to database simultaneously? I insert data to a database by using (SELECT max(id) + 1 FROM data) and sometimes it cause that I try to put two object with the same id  to the database, when I do it in loop.
button.setOnClickListener {
    for ((key, value) in dataArray!!) {

            DbHelper().addData(value, key)
        }

}

DbHelper code:
fun addData(
        value: Int,
        key: Int
    )
    {

        val retrofit = Retrofit.Builder()
            .baseUrl("http://10.0.2.2:8080/app/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        valdataService: DataService = retrofit.create(
            DataService::class.java
        )

        val call: Call<Long> = valdataService.postData(
            DataBodyPost(value, key))

        call.enqueue(object : Callback<Long> {
            override fun onResponse(call: Call<Long>, response: Response<Long>) {
                if (!response.isSuccessful()) {
                    println(" response " + response.toString())
                    return
                }

            }

            override fun onFailure(call: Call<Long>, t: Throwable) {

                println(" ERROR " + t)
            }

        })
    }


text:
Q: Setting dates as nullable in laravel I am having a hard time understanding the inner workings of date fields in laravel. I have a custom date field named called_at and I set it as nullable in the schema. Since it's a date field, I would naturally want it to be a Carbon instance, so in the model I pushed this attribute to the $dates array.
protected $dates = ['called_at'];

In order to be able to set it from the controller, via the request('called_at') input, I would have to set a mutator in the model. So I set one like this:
public function setCalledAtAttribute($date){
    $this->attributes['called_at'] = Carbon::parse($date);
}

But the problem is, even if the user does not provide a date in the input field, the called_at attribute is set to the current timestamp! But I expected it to be NULL.
To get rid of it, I commented out the setCalledAtAttribute mutator. But now it won't even take the input:

InvalidArgumentException Data missing

Bottom line, how can I set my date field nullable in such a way that when a user leaves the input field blank, the called_at field wont be set to current timestamp?

A: Try to do this:
public function setCalledAtAttribute($date)
{
    $this->attributes['called_at'] = empty($date) ? null : Carbon::parse($date);
}

A: If you use parse on an empty string Carbon::parse('') or null Carbon::parse(null) Carbon will actually return the current date and time So you should check if $date is provided and not null:
$this->attributes['called_at'] = $date ? Carbon::parse($date); : null;


text:
Q: hitbox of text too big I have 2 texts on my page and both of them turn white on hover with an animation. But the hitbox of the text is too big in width, which means that it lights up way too soon (when you're not even close to the text). Does anyone know why this is happening?

body {
  margin: 0;
  padding: 0;
}

#page-header {
  padding: 0;
  margin: 0;
  background-color: #1a1a1a;
  height: 65%;
  width: 100%;
  position: absolute;
}

#start-introduction:hover {
  animation-name: changeColor;
  animation-duration: 0.5s;
  animation-fill-mode: forwards;
}

#start-introduction {
  border-style: solid;
  margin: 0;
  margin-top: 15vh;
  font-size: 7vh;
  text-align: center;
  font-family: arial;
  color: #262626;
  cursor: default;
  animation-name: reverseColor;
  animation-duration: 0.5s;
}

#introduction:hover {
  animation-name: changeColor;
  animation-duration: 0.5s;
  animation-fill-mode: forwards;
}

#introduction {
  border-style: solid;
  margin: 0;
  margin-top: 3vh;
  font-size: 18vh;
  text-align: center;
  color: #262626;
  font-family: arial;
  cursor: default;
  animation-name: reverseColor;
  animation-duration: 0.5s;
}

@keyframes changeColor {
  from {
    color: #262626;
  }
  to {
    color: white;
  }
}

@keyframes reverseColor {
  from {
    color: white;
  }
  to {
    color: #262626;
  }
}

test test

{Test test}

A: Have you tried giving it a width? Also, the font size of the above 'test text' and '{Test test}' texts are not equal.

A: Ok, a few things to go over. I'm going to make a few assumptions here and see if this helps. Paragraphs
 and Headers h1 are block level elements this means they will always span the width of their containing element which in your case is
. So when you say that you want an animation to take place when you :hover an element that includes the entire element. The point I am trying to make is: if you only want the animation to take place when you hover the text. You need to make the element only as wide as the text. In this case I place them both in their own containers and make those containers display flex so the elements inside are no longer block level elements and can easily be placed in the center using justify content.
On a side note I would be careful using Viewport height vh as a unit of measurement for margins and font size.  I understand you want your font sizes to be responsive but using viewport height is too risky and your numbers could end up  being all over the place unless you are 100% sure that everyone will have the same size screen and it will always be full size.  I personally use em and/or rem for my font sizes and margins because em is based on the parent element font size or rem which is based on the document font size.

body {
  margin: 0;
  padding: 0;
}

.container {
  display: flex;
  justify-content: center;
}

#page-header {
  padding: 0;
  margin: 0;
  background-color: #1a1a1a;
  height: 65%;
  width: 100%;
  position: absolute;
}

#start-introduction:hover {
  animation-name: changeColor;
  animation-duration: 0.5s;
  animation-fill-mode: forwards;
}

#start-introduction {
  border-style: solid;
  margin: 0;
  margin-top: 15vh;
  font-size: 7vh;
  text-align: center;
  font-family: arial;
  color: #262626;
  cursor: default;
  animation-name: reverseColor;
  animation-duration: 0.5s;
}

#introduction:hover {
  animation-name: changeColor;
  animation-duration: 0.5s;
  animation-fill-mode: forwards;
}

#introduction {
  border-style: solid;
  margin: 0;
  margin-top: 3vh;
  font-size: 18vh;
  text-align: center;
  color: #262626;
  font-family: arial;
  cursor: default;
  animation-name: reverseColor;
  animation-duration: 0.5s;
}

@keyframes changeColor {
  from {
    color: #262626;
  }
  to {
    color: white;
  }
}

@keyframes reverseColor {
  from {
    color: white;
  }
  to {
    color: #262626;
  }
}

  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" href="index.css" />
  <title>TestTest</title>

test test

{Test test}


text:
Q: Using Unicode strings in DllImport with a DLL written in Rust I am trying to call a DLL written in Rust from a C# program. The DLL has two simple functions that take stings (in different manner) and prints to the console.
Rust DLL code
#![crate_type = "lib"]
extern crate libc;

use libc::{c_char};
use std::ffi::CStr;

#[no_mangle]
pub extern fn printc(s: *const c_char){
    let c_str : &CStr = unsafe {
        assert!(!s.is_null());

        CStr::from_ptr(s)
    };

    println!("{:?}", c_str.to_bytes().len()); //prints "1" if unicode

    let r_str = std::str::from_utf8(c_str.to_bytes()).unwrap();
    println!("{:?}", r_str);
}

#[no_mangle]
pub extern fn print2(string: String) {
    println!("{:?}", string)
}

C# console program code
[DllImport("lib.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
static extern void print2(ref string str);

[DllImport("lib.dll", CallingConvention = CallingConvention.Cdecl)]
static extern void printc(string str);

static void Main(string[] args)
{
  try
  {
    var graw = "yeyeye";
    printc(graw);
    print2(ref graw);
  }
  catch (Exception ex)
  {
    Console.WriteLine("calamity!, {0}", ex.Message);
  }
  Console.ReadLine();
}

For the print2 function it keep printing garbage on screen until it causes AccessViolationException
The 2nd printc function does print the string, but only if CharSet.Unicode is not set. If it is set, it will only print the first char, hence the println!("{:?}", c_str.to_bytes().len()); will print 1.
I believe that Cstr::from_ptr function does not support Unicode, that is why it returns only the first char of the string.
Any idea how to pass Unicode string as parameters to Rust DLLs?  Is it possible to make things simpler like in print2 function?

A: If you check the documentation on CharSet, you'll see that CharSet.Unicode tells .NET to marshal strings as UTF-16 (i.e. two bytes per code point).  Thus, .NET is trying to pass printc what should be a *const u16, not a *const libc::c_char.  When CStr goes to compute the length of the string, what it sees is the following:
b"y\0e\0y\0e\0y\0e\0"

That is, it sees one code unit, then a null byte, so it stops; hence why it says the length is "1".
Rust has no standard support for UTF-16 strings, but if you're working on Windows, there are some conversion methods: search the docs for OsStrExt and OsStringExt.  Note that you must use the docs that installed with the compiler; the ones online won't include it.
Sadly, there's nothing for dealing directly with null-terminated UTF-16 strings.  You'll need to write some unsafe code to turn a *const u16 into a &[u16] that you can pass to OsStringExt::from_wide.
Now, Rust does use Unicode, but it uses UTF-8.  Sadly, there is no direct way to get .NET to marshal a string as UTF-8.  Using any other encoding would appear to lose information, so you either have to explicitly deal with UTF-16 on the Rust side, or explicitly deal with UTF-8 on the C# side.
It's much simpler to re-encode the string as UTF-8 in C#.  You can exploit the fact that .NET will marshal an array as a raw pointer to the first element (just like C) and pass a null-terminated UTF-8 string.
First, a static method for taking a .NET string and producing a UTF-8 string stored in a byte array:
byte[] NullTerminatedUTF8bytes(string str)
{
    return Encoding.GetBytes(str + "\0");
}

Then declare the signature of the Rust function like this:
[DllImport(dllname, CallingConvention = CallingConvention.Cdecl)]
static extern void printc([In] byte[] str);

Finally, call it like this:
printc(NullTerminatedUTF8bytes(str));

For bonus points, you can rework printc to instead take a *const u8 and a u32, passing the re-encoded string plus it's length; then you don't need the null terminator and can reconstruct the string using the std::slice::from_raw_parts function (but that's starting to go beyond the original question).
As for print2, that one is just unworkable.  .NET knows nothing about Rust's String type, and it is in no way compatible with .NET strings.  More than that, String doesn't even have a guaranteed layout, so binding to it safely is more or less not possible.
All that is a very long-winded way of saying: don't use String, or any other non-FFI-safe type, in cross-language functions, ever.  If your intention here was to pass an "owned" string into Rust... I don't know if it's even possible to do in concert with .NET.
Aside: "FFI-safe" in Rust essentially boils down to: is either a built-in fixed-size type (i.e. not usize/isize), or is a user-defined type with #[repr(C)] attached to it.  Sadly, the "FFI-safe"-ness of a type isn't included in the documentation.


text:
Q: Equivalent to Perl Modulino for Ruby, Python? I know Perl has a design pattern known as a modulino, in which a library module file can act as both a library and a script.  Is there any equivalent to this in Ruby / Python?
I think this design pattern would be very useful for me; I'm writing workers that are fairly short, but also require a script to run them.  I think it would be convenient to have this all run from the same place.

A: Python has __name__:
class MyClass(object):
    pass

if __name__ == '__main__':
    print("This will only run if you run the script explicitly, not import it")

If you run python myscript.py, the print function will run. If you import MyClass from myscript, the print will not.

A: This is the Ruby version:
if __FILE__ == $PROGRAM_NAME #equivalent: if __FILE__ == $0
  puts "This is the main file running, it is not being required."
end

A: Perl 6 has this feature built in. You define a subroutine named MAIN that executes if you use the file as a script:
 sub MAIN { ... }

The signature for MAIN tells Perl 6 how to parse the command-line parameters. You can have multi-subs and Perl 6 will use the one whose signature matches. Here's the example from Synopsis 6:
multi MAIN (Int $i) {...}   # foo 1
multi MAIN (Rat $i) {...}   # foo 1/2
multi MAIN (Num $i) {...}   # foo 1e6
multi MAIN ($i) {...}       # foo bar