text:
Q: angular ui-router reload / factory reload I'm developping an application with several views for y sport association.
one for listing tournaments, and one for detailed view of a tournament, were ou can register.
My data comes from a factory. Whenever i tried to refresh views, using at least the refresh button of chrome/ie/etc, it works for the tournament view but not for the detailed one.
Tournament controller  :
baclyApp.controller('tournoisCtrl',['$scope','tournois','$cookies','$state','growl',function($scope,tournois,$cookies, $cookieStore, $window,$state,growl){
    //Liste des tournois
    $scope.tournois=tournois.list();
    console.log($scope.tournois);

    $scope.reloadRoute = function() {
    $state.reload();
    };

}]);

Detailed controller snippet (as it is very long, )
baclyApp.controller('detailtournoisCtrl', ['$scope','$state','$stateParams', 'tournois','$cookies','growl', function($scope, $state,$stateParams, tournois,$cookies,growl) {
//Detail du tournoi
        $scope.tournois=tournois.list();
        console.log("tournoi : "+$stateParams.cid); // displays cid fine
        $scope.tournoi = tournois.find($stateParams.cid);
        console.log($scope.tournois);
        $scope.selectedtournoi = explodeseries($scope.tournoi);

        // console.log($scope.selectedtournoi);
        $scope.showinscris = false;
        $scope.baclyusersdouble = tournois.list();
        $scope.baclyusersmixte = tournois.list();
        $scope.forminscris={};
        // console.log($scope.baclyusersdouble.users);
        $scope.hideparticiper=true;

Factory :
baclyApp.factory("tournois",function($http){
//Provider qui recupère les données de tournois et iscriptions
    // var urlphp="http://localhost/cordova/mbacly/www/php/";
    var urlphp="http://bacly.fr/baclymphp/";
    var tournois={};
    $http.get(urlphp+"getTournois.php").success(function(data)
     {
         tournois.tournois = data;
     }).error(function(status) {
    alert("pas d accès réseau")
    });
    $http.get(urlphp+"getTournoinscriptions.php").success(function(data)
     {
         tournois.inscriptions = data;
     }).error(function() {
    alert("pas d accès réseau")
    });
    $http.get(urlphp+"getTournoinscris.php").success(function(data)
     {
         tournois.inscris = data;
         console.log(data);
     }).error(function() {
    alert("pas d accès réseau")
    });
    $http.get(urlphp+"getUsers.php").success(function(data)
     {
         tournois.users = data;
     }).error(function() {
    alert("pas d accès réseau")
    });

    return {
        list: function(){
            return tournois;
        },

        find: function(cid){
            return _.find(tournois.tournois, function(t) {return t.tournois_id === cid});
        },

        findinscris: function(cid){
            return _.filter(tournois.inscris, function(t) {return t.tournois_id === cid});
        },
        findusers: function(uid){
            return _.filter(tournois.users, function(t) {return t.user_id === uid});
        },
        findusersbyname: function(name){
            return _.filter(tournois.users, function(t) {return t.uname === name});
        },
        updateinscription: function($params){
            // var urlphp="http://localhost/cordova/mbacly/www/php/";
            var urlphp="http://bacly.fr/baclymphp/";
            var tournois={};
            var retour="retour-OK";

            $params_encoded =encodeURIComponent(JSON.stringify($params));
            $http.get(urlphp+"saveinscription.php?data="+$params_encoded).success(function(data){
                // console.log("retour-OK"+data);
                retour="retour-OK";
            });
                return retour;
       },
        insertinscription: function($params){
            // var urlphp="http://localhost/cordova/mbacly/www/php/";
            var urlphp="http://bacly.fr/baclymphp/";
            var tournois={};
            var retour="retour-OK";

            $params_encoded =encodeURIComponent(JSON.stringify($params));
            $http.get(urlphp+"saveinscription.php?data="+$params_encoded).success(function(data){
                console.log("retour-OK"+data);
                retour="retour-OK";
            });
                return retour;

        },
        deleteinscription: function($params){
            // var urlphp="http://localhost/cordova/mbacly/www/php/";
            var urlphp="http://bacly.fr/baclymphp/";
            var tournois={};
            var retour="retour-OK";
            $params_encoded =encodeURIComponent(JSON.stringify($params));
            $http.get(urlphp+"saveinscription.php?data="+$params_encoded).success(function(data){
                console.log("retour-OK"+data);
                retour="retour-OK";
            });
                return retour;

        }
    }
})

app config : detailed states
.state('tournois', {
    url: "/tournois",
    views: {
        "main": {
            templateUrl: "partials/tournois.html",
            controller: 'tournoisCtrl'

        }
    }
})
.state('detailtournoi', {
    url: "/detailtournoi/:cid",
    views: {
        "main": {
            templateUrl: "partials/detailtournoi.html",
            controller: 'detailtournoisCtrl'

Thanks for your help !


text:
Q: How to switch a SIM800L modem on/off with an ESP32-CAM, without a relay? I would like to turn a SIM800L modem on/off (to save battery), controlled with GPIO 16 on an ESP32-CAM, without a relay.
It was working OK with an electromagnetic relay, but I'd like to avoid the noisy clicking sound, so I'm trying to use some kind of BJT transistor or MOSFET based approach.
It might be relevant that pin 16 has a 10k pull up resistor.
(This is part of a more complex setup, and I only have pin 16 left.)
There is 5v on the breadboard power rail, and 3.3v appears on the output pin when turned on HIGH.
Maybe could work
I tried using and NPN transistor (2N2222A) as a switch, but that didn't turn on the SIM800L.
I was following this kind of setup and maybe that wasn't suitable?
Approaches that didn't work
IRF530N MOSFET
As @vir explains: The 3.3V from the module is not enough to turn on the IRF530, which has a threshold voltage of 2-4V.
I wired it up like below, but HIGH on GPIO 16 doesn't turn on the SIM800L.
Can this possibly work?
There was another question where someone got a similar mosfet to work, and I saw a breakout-board with this on/off function which used an IRF520.
This guide also indicates some techniques but honestly it's over my head how the pieces might have to fit together to make it work.

I was following this tutorial where he includes this diagram:

A: The 3.3V from the module is not enough to turn on the IRF530, which has a threshold voltage of 2-4V.  5V should be enough, which gives you options.  You could change the IRF530 for another device (BJT, 3.3V logic level MOSFET) that will work directly from a 3.3V signal or add in a cheap gate driver chip that will apply 5V to the gate of the IRF530.  It might not be a great idea to low-side switch the SIM800L so a small SSR or PMOS with appropriate gate driver could be indicated here.

A: The problem with the IRF530N was that its gate voltage is too high (~4v) for the ESP32 pin signal (3.3v) to open it.
I replaced it with an IRLZ24NPBF, the datasheet says Vgs 2v.
This FET did open with the lower voltage, but when drain and source was connected to the power rail (5v), some voltage was lost in the FET and only 4v appeared on the SIM800L, which is not quite enough.
Connecting the FET to a 9v battery worked.
The FET however stays open even with LOW signal from the ESP32 pin. It only turns off when the ESP32 goes into deep sleep.

*

*ESP32 on: 6-7v on the SIM800L

*ESP32 in deep sleep: 3v and 60µA on the SIM800L

(This is acceptable for my use case, as I wanted the SIM800L not to draw battery power while the ESP32 is sleeping.)
I tried to control the FET gate with a BJT transistor, using the ESP32 pin to open/close the BJT, but then again the FET doesn't open enough to drive the SIM800L (or it doesn't get enough current?).
So this works to the extent that ESP32 on normal power turns the SIM800L on, and deep sleep turns it off:

redpajama_set_name: RedPajamaStackExchange


text:
Q: spark-submit: Passing java properties file gives FileNotFoundException I have a spark job that I am running in yarn cluster mode. I need to pass my application specific java properties file.
I am doing this java FileInputStream.
But I am facing FileNotFoundException for /home/aiman/config/my-file.properties
My java properties file is: /home/aiman/config/my-file.properties
mongo_server=my.mongo.server
mongo_port=1530
mongo_user=mongoadmin
mongo_password=readONLYpass
mongo_db=testdb

My spark-submit looks like:
spark-submit --master yarn --deploy-mode cluster --class mongo.MongoRead --jars /home/aiman/ojdbc-7.jar /home/aiman/app/jars/MongoRead-0.1-jar-with-dependencies.jar /home/aiman/config/my-file.properties

Code snippet:
public static void main(final String[] args) throws Exception
    {
        if(args.length<1){
            System.out.println("Please provide properties file path");
            System.exit(1);
        }

        System.out.println("Mongo Import Begins...");

        Properties prop = new Properties();
        InputStream in = null;
        try{
            in = new FileInputStream(args[0]);
            prop.load(in);
        }
        catch(Exception e){
            e.printStackTrace();
            System.exit(1);
        }

        /*Reading the properties*/
        String mongoServer = prop.getProperty("mongo_server");
        String mongoPort = prop.getProperty("mongo_port");
        String mongoUser = prop.getProperty("mongo_user");
        ....
        ...

        String mongoAddress = "mongodb://"+mongoUser+":"+mongoPassword+"@"+mongoServer+":"+mongoPort+"/"+mongoDb+"."+tableNm;

        SparkSession spark = SparkSession.builder()
            .appName("MongoSparkRecordReader")
            .config("spark.mongodb.input.uri", mongoAddress)
            .config("spark.mongodb.output.uri", mongoAddress)
            .getOrCreate();

        JavaSparkContext jsc = new JavaSparkContext(spark.sparkContext());
        ...
        ..

}

Please suggest what is going wrong. Am I reading the properties file in a wrong manner, that it isn't finding the file?

A: Running this in --deploy-mode client resolves the issue. The Driver is getting launched where the properties file is present. So file is getting read and not getting any Exception.

A: You should pass the local file via the "--file /home/aiman/config/my-file.properties" spark-submit's argument, which will distribute the file to the containers launched by YARN that will find the "my-file.properties" in their JVM's classpath. You should then be able to read it as a JVM's local resource.


text:
Q: C# SmtpException - problem with sending mails Sending mails doesn't work. I'm not sure if it's something with client settings or mail server...
When using Gmail SMTP server I got "Connection closed" exception, when changing port to 587 I get "Authentication required" message. What's more interesting when changing SMTP server to something different (smtp.poczta.onet.pl) I get "Time out" exception after ~100s
Here's the code:
protected void SendMessage(object sender, EventArgs e)
{
    // receiver address
    string to = "******@student.uj.edu.pl";

    // mail (sender) address
    string from = "******@gmail.com";

    // SMTP server address
    string server = "smtp.gmail.com";

    // mail password
    string password = "************";

    MailMessage message = new MailMessage(from, to);

    // message title
    message.Subject = TextBox1.Text;

    // message body
    message.Body = TextBox3.Text + " otrzymane " + DateTime.Now.ToString() + " od: " + TextBox2.Text;

    SmtpClient client = new SmtpClient(server, 587);
    client.Credentials = new System.Net.NetworkCredential(from, password);
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.UseDefaultCredentials = false;
    client.EnableSsl = true;

    try
    {
        client.Send(message);

        // ui confirmation
        TextBox3.Text = "Wysłano wiadmość!";

        // disable button
        Button1.Enabled = false;
    }
    catch (Exception ex)
    {
        // error message
        TextBox3.Text = "Problem z wysłaniem wiadomości (" + ex.ToString() + ")";
    }
}

I've just read that google don't support some less secure apps (3rd party apps to sign in to Google Account using username and password only) since 30/05/22. Unfortunately can't change it because I have two-stage verification account. Might it be connected? Or is it something with my code?

A: Gmail doesn't allow, or want you to do that with passwords anymore. They ask you to create a credentials files and then use a token.json to send email.
Using their API from Google.Apis.Gmail.v1 - from Nuget. Here is a method I made and test that is working with gmail.
void Main()
{
    UserCredential credential;

    using (var stream =
        new FileStream(@"C:\credentials.json", FileMode.Open, FileAccess.Read))
    {
        // The file token.json stores the user's access and refresh tokens, and is created
        // automatically when the authorization flow completes for the first time.
        string credPath = "token.json";
        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            Scopes,
            "user",
            CancellationToken.None,
            new FileDataStore(credPath, true)).Result;
        Console.WriteLine("Credential file saved to: " + credPath);
    }

    // Create Gmail API service.
    var service = new GmailService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = ApplicationName,
    });

    // Define parameters of request.
    UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me");

    // List labels.
    IList labels = request.Execute().Labels;
    Console.WriteLine("Labels:");
    if (labels != null && labels.Count > 0)
    {
        foreach (var labelItem in labels)
        {
            Console.WriteLine("{0}", labelItem.Name);
        }
    }
    else
    {
        Console.WriteLine("No labels found.");
    }
    //Console.Read();
    var msg = new Google.Apis.Gmail.v1.Data.Message();
    MimeMessage message = new MimeMessage();

    message.To.Add(new MailboxAddress("", "toemail.com"));
    message.From.Add(new MailboxAddress("Some Name", "YourGmailGoesHere@gmail.com"));
    message.Subject = "Test email with Mime Message";
    message.Body = new TextPart("html") {Text = "
This
 is a body..."};

    var ms = new MemoryStream();
    message.WriteTo(ms);
    ms.Position = 0;
    StreamReader sr = new StreamReader(ms);
    string rawString = sr.ReadToEnd();

    byte[] raw = System.Text.Encoding.UTF8.GetBytes(rawString);
    msg.Raw = System.Convert.ToBase64String(raw);

    var res = service.Users.Messages.Send(msg, "me").Execute();

    res.Dump();

}
static string[] Scopes = { GmailService.Scope.GmailSend, GmailService.Scope.GmailLabels, GmailService.Scope.GmailCompose, GmailService.Scope.MailGoogleCom};
static string ApplicationName = "Gmail API Send Email";

A: Can you ping the smpt server from your machine or the machine you deploy the code from? THis could be a DNS issue.

A: Enable 2FA on your email and generate a password for your application using the link. As far as I know, login and password authorization using unauthorized developer programs is no longer supported by Google.


text:
Q: Dynamic INTO clause in OpenSQL? I'm attempting to write a program that will grab the content from fields from a table both specified by the user on the selection screen.
For example, the user could specify the fields equnr, b_werk, b_lager from the table eqbs.
I've been able to accomplish this like so:
" Determine list of fields provided by user
DATA(lv_fields) = COND string(
  WHEN p_key3 IS NOT INITIAL AND p_string IS NOT INITIAL THEN
    |{ p_key1 }, { p_key2 }, { p_key3 }, { p_string }|
  WHEN p_key2 IS NOT INITIAL AND p_string IS NOT INITIAL THEN
    |{ p_key1 }, { p_key2 }, { p_string }|
  WHEN p_key2 IS NOT INITIAL AND p_string IS NOT INITIAL THEN
    |{ p_key1 }, { p_string }| ).

DATA: lv_field_tab TYPE TABLE OF line.
APPEND lv_fields TO lv_field_tab.

" Determine table specified by user and prepare for Open SQL query
DATA t_ref TYPE REF TO data.

FIELD-SYMBOLS: <t>    TYPE any,
               <comp> TYPE any.

CREATE DATA t_ref TYPE (p_table).
ASSIGN t_ref->* TO <t>.
ASSIGN COMPONENT lv_fields OF STRUCTURE <t> TO <comp>.

" Prepare result container
DATA: lt_zca_str_to_char TYPE TABLE OF zca_str_to_char,
      ls_zca_str_to_char TYPE zca_str_to_char.

SELECT (lv_field_tab) FROM (p_table) INTO (@ls_zca_str_to_char-key1, @ls_zca_str_to_char-key2, @ls_zca_str_to_char-key3, @ls_zca_str_to_char-string).
  APPEND ls_zca_str_to_char TO lt_zca_str_to_char.
ENDSELECT.

This will correctly populate lt_zca_str_to_char with data from the table specified by the user.
However, this implies that the user is always providing p_key1, p_key2, and p_key3. I could perform a different selection statement based on how many key fields the user provides, but what's the fun in that?
I set out to solve this like this:
DATA(lv_results) = COND string(
  WHEN p_key3 IS NOT INITIAL AND p_string IS NOT INITIAL THEN
    |(@ls_zca_str_to_char-key1, @ls_zca_str_to_char-key2, @ls_zca_str_to_char-key3, @ls_zca_str_to_char-string)|
  WHEN p_key2 IS NOT INITIAL AND p_string IS NOT INITIAL THEN
    |(@ls_zca_str_to_char-key1, @ls_zca_str_to_char-key2, @ls_zca_str_to_char-string)|
  WHEN p_key2 IS NOT INITIAL AND p_string IS NOT INITIAL THEN
    |(@ls_zca_str_to_char-key1, @ls_zca_str_to_char-string)| ).

SELECT (lv_field_tab) FROM (p_table) INTO (@lv_results).
  APPEND ls_zca_str_to_char TO lt_zca_str_to_char.
ENDSELECT.

This will activate, and when I get to my Open SQL query (from a Z table, only filling out the first two of three possible key fields), the values are the following:
lv_field_tab = GUID, TEXT_ID, TEXT_DATA (Good)
p_table = ZCR_TRANS_TEXT (Good)
lv_results = (@ls_zca_str_to_char-key1, @ls_zca_str_to_char-key2, @ls_zca_str_to_char-string) (Good, 3 = 3!)
But, since I'm assuming the compiler is seeing (@lv_results) as one single variable, the program dumps with the following error:

The current ABAP program attempted to execute an Open SQL statement
  containing a dynamic entry. The parser returned the following error:
  "The  field list and the INTO list must have the same number of
  elements."

Is it possible for me to use the new Open SQL syntax to accomplish my dynamic  INTO clause in harmony with my dynamic field list?

A: The brackets on the INTO do not do what you expect, from the ABAP help:
... INTO (@dobj1, @dobj2, ... )
Effect
If the results set consists of multiple columns or aggregate expressions specified explicitly in the SELECT list, a list of elementary data objects dobj1, dobj2, ... (in parentheses and separated by commas) can be specified after INTO.
In your case you only have one value in there so you can only select one column and the data will be passed in the variable LV_RESULT. Not what you are looking for. Since you want to fill the fields of an existing structure the INTO CORRESPONDING FIELDS OF construct will work here. And you can use TABLE to make your command more efficient as well. This leads to:
SELECT (lv_field_tab) FROM (p_table)
       INTO CORRESPONDING FIELDS OF TABLE @lt_zca_str_to_char.

A: As said previously, you may use INTO CORRESPONDING FIELDS OF ..., but it's not mandatory, it's only for simplifying the code.
So, instead of using CORRESPONDING FIELDS, you may create a structure dynamically (RTTC) with its components corresponding to the columns in LV_FIELD_TAB, and you may then use:
SELECT (lv_field_tab) FROM (p_table) INTO @<structure> ... ENDSELECT.

But of course, as explained by Gert Beukema, you should better do only one SELECT, by creating an internal table dynamically with the same logic as for the structure above, and you may then use:
SELECT (lv_field_tab) FROM (p_table) INTO TABLE @<internal table> ...

Refer to the many examples in the web how to create data objects dynamically with RTTC.

A: Do not use a fields list for your INTO clause.
Try with
INTO CORRESPONDING FIELDS OF TABLE
 must be a FIELD-SYMBOL type any table, and the rest of the logic is up to you (to put the proper information from your generic and almost-empty  to your specific destination one).


text:
Q: Ruby variable initialisation In the following code there is an execution path where "bar" is not set before it is tested, is doing this safe in Ruby? will "bar" have a default initialisation?
if foo
  bar = true
end

if bar
  puts "true"
end

A: Yes
Yes, it is safe, in the sense that the worst that can happen when an uninitialized local is referenced is that a NameError exception will be raised.
Yours is a bit of a special-case, actually. Since the parser will have seen bar before it is referenced, then the method will not raise NameError, even if foo is false, but rather the value of bar will be nil.


text:
Q: Symfony3 Image validation for working If I don't validate what I am uploading things work fine but the moment I add validation to the image field I get an error of
Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed

The only thing at the moment I have inside my validation.yml is as following
AppBundle\Entity\User:
    properties:
        firstName:
            - NotBlank: {message: "user.firstname.not_blank"}
        lastName:
            - NotBlank: { message: "user.lastname.not_blank" }
        profileImage:
            - Image:

Inside my Entity
use Symfony\Component\HttpFoundation\File\File;
    public function setProfileImage(File $profileImage = null)
    {
        $this->profileImage = $profileImage;

        return $this;
    }

What am I missing here? This used to work fine in Symfony 2.7


text:
Q: Factoring $x^2+4$ [Elementary] The real factors of $ x^2+4$ are:
How to factor this without being complex?

A: Hint:  we have $$x^2+4=x^2\color{blue}{+4x}+4\color{blue}{-4x}=(x+2)^2-(2\sqrt{x})^2$$
which can be factored as a difference of squares.
The answer would be

$$x^2+4=(x-2\sqrt{x}+2)(x+2\sqrt{x}+2)$$

A: The factorization of a polynomial in monic binomials is unique. As $x^2+4=(x+2i)(x-2i)$, there is no other option.


text:
Q: pseudo selector :target CSS I'm using (:target{}) to trigger different states for the main navigation and the filter. The code works like I expect it to for the filter section, but when I take that same code and change a couple of parameters it doesn't work.
Here's the html

Adopt

Post

Shelters

Favorites

My Pets

Login

Log out

<form id="filter" class="filter" action="http://localhost/petlist/public/site/index" accept-charset="utf-8" method="post">
  <select name="petsDropDown" id="form_petsDropDown">
    <option value="allPets">All Pets</option>
    <option value="dogs">Dogs</option>
    <option value="cats">Cats</option>
    <option value="other">Other</option>
  </select>
  <input name="petName" value="City, state or zip" type="text" id="form_petName" />
  <select name="breedDropDown" id="form_breedDropDown">
    <option value="allBreeds">All Breeds</option>
    <option value="yorkie">Yorkshire Terrier</option>
    <option value="pit">Pit-Bull</option>
    <option value="poodle">Poodle</option>
  </select>
</form>

And here is the CSS
.page-wrap{
  width: 100%;
  transition: all 0.3s ease;
  -webkit-transition: 0.3s ease;
}

.main-header{
  width: 100%;
  overflow: hidden;
  position: fixed;
  z-index: 1000;
  transition: all 0.3s ease;
  -webkit-transition: 0.3s ease;
  background-color: $topNavBlack;
  margin-bottom: $ten;
  border-bottom: 1px solid $petListBlue;
h1{
    font-family: steelfishregular;
    font-size: 35px;
    letter-spacing: 1px;
    width: 60px;
    color: $logoWhite;
    padding: $ten;
    margin: 0 auto;
}
.open-nav{
    display: block;
    width: 35px;
    height: 35px;
    background-image: url('../img/nav.svg');
    background-repeat: no-repeat;
    background-position: center;
    float: left;
    border-radius: 3px;
    margin: $ten;
    background-color: $petListBlue;
}
.close-nav{
    display: none;
    width: 35px;
    height: 35px;
    background-image: url('../img/nav.svg');
    background-repeat: no-repeat;
    background-position: center;
    float: left;
    border-radius: 3px;
    margin: $ten;
    background-color: $petListBlue;
}
.open-filter{
    display: block;
    width: 35px;
    height: 35px;
    background-image: url('../img/settings.svg');
    background-repeat: no-repeat;
    background-position: center;
    float: right;
    margin: $ten;
    border-radius: 3px;
    background-color: $petListBlue;
}
.close-filter{
    display: none;
    width: 35px;
    height: 35px;
    background-image: url('../img/settings.svg');
    background-repeat: no-repeat;
    background-position: center;
    float: right;
    margin: $ten;
    border-radius: 3px;
    background-color: $petListBlue;
  }
 }

.main-nav{
  position: fixed;
  top: 0;
  left:0;
  width: 0;
  height: 100%;
  z-index:2000;
  background-color: #303030;
  overflow: hidden;
  transition: height none;
  transition: width 0.3s ease;
  -webkit-transition: 0.3s ease;
  &:after {
   content: "";
   position: absolute;
   top: 0;
   height: 100%;
   width: 34px;
  }
}
#main-nav:target{
  width: 80%;
}
#main-nav:target + .page-wrap {
  margin-right: -80%;
  .open-nav {
    display: none;
  }
  .close-nav {
    display: block;
  }
  .main-header {
    width: 100%;
  }
}

This is the CSS that actually works like I want it to.
.filter{
  position: fixed;
  top: 0;
  right: 0;
  width: 0;
  height: 100%;
  z-index:2000;
  background-color: #303030;
  overflow: hidden;
  transition: height none;
  transition: width 0.3s ease;
  -webkit-transition: 0.3s ease;
  &:after {
    content: "";
    position: absolute;
    top: 0;
    height: 100%;
    width: 34px;
  }
}
#filter:target {
  width: 80%;
}
#filter:target + .page-wrap {
  margin-left: -80%;
  .open-filter {
    display: none;
  }
  .close-filter {
    display: block;
  }
  .main-header {
    width: 100%;
  }
}

A: Try changing this
#main-nav:target + .page-wrap

to this
#main-nav:target ~ .page-wrap

since .page-wrap is not placed immediately after #main-nav


text:
Q: Creating new Soap Web Service with .NET 3.5 I haven't really looked into the new .NET stuff since 2.0, but I'm wondering what the preffered way is for creating Web Services is now (SOAP, not RESTful).  I remember in the old days, you created a ASP.NET Web Service.  Now, I've been looking at WCF, but it seems like there's some added complexity.
  I've GOOGLED for some sample code, have 30 tabs open, but there's no consistency in what the best way is to do somethings: some examples are for .NET 2.0, .NET 1.1, etc.  Any one know where some good simple CRUD-based examples are?  (I've been scanning MSFT's site, but also haven't stumbled -- yet -- upon that golden article.)
Thanks

A: A couple of things.
1) It's still OK to do Add -> New Web Service (asmx).
2) It's equally easy to do that with WCF (and it's still just SOAP).
The benefit of going WCF is that you're 'future-compatible' if you want to change some features (such as the transport type, etc).

A: I really think MSDN's Getting Started Tutorial is worthwhile. It walks you through defining a contract, implementing the contract, hosting the service, and then consuming it. It starts from zero and walks you through each step without wizards, so you get a feel for what you're doing and why. If you want more info, there are links to deeper treatments of each subject.
If all you'll ever do is expose a SOAP web service, WCF isn't really necessary. The old-school .asmx web services are still available in 3.5. The real strength of WCF shows when you realize you can expose the same contract implementation using anything from a binary protocol to various web protocols - hosted inside IIS or out. That's a whole lot of flexibility that may not even be valuable if you're already happy with SOAP.


text:
Q: Solving the one-dimensional heat equation in an infinite rod by separation of variables and comparing to Fourier Transform I want to solve the the one-dimensional heat equation in an infinite rod with the initial condition that all the heat is initially concentrated at $x=0$, so
 $u(x,0)=\delta(x)$. The boundary condition is $u(\infty,t) = 0$
In the first 3 pages of the following paper, the one-dimensional heat equation in an infinite rod is solved by separation of variables.
https://ocw.mit.edu/courses/mathematics/18-303-linear-partial-differential-equations-fall-2006/lecture-notes/fourtran.pdf
It is specifically mentioned in the first line of the second page that $u \to 0$ ad $x \to \infty$
This does not seem to be consistent with the fact that
 $$X(x) = A \cos (\sqrt{\lambda}x) + B \sin (\sqrt{\lambda}x) \ne 0 $$
as $\ x \to \infty $
If I however apply my initial condition to the final result (equation 8 in the paper) then I obtain a Gaussian type function that does have the right boundary conditions: $u \to 0$ as $|x| \to \infty$.
Other threads on this forum have indicated that this problem should be solved with the Fourier transform method.
My question then becomes: How does this paper seem to get the right final answer through separation of variables, even with the boundary condition $u(\infty,t) = 0$? The solution in the paper for $X(x)$ does not satisfy the boundary condition, but the final solution does. It seems like this paper is cutting some corners in a mathematically less rigorous way to obtain the right answer, but I can't find out exactly where.


text:
Q: How to receive file from user in telegram bot? i use Telegram SDK for laravel
how to receive file from user ??

A: if you want to receive a file from a user, have a look at this API section
https://core.telegram.org/bots/api#getfile:

Use this method to get basic info about a file and prepare it for
  downloading


text:
Q: "Close encounters" between two big powers: how to solve? Given integer N, I wander is there is a method to find integers a,b,n,m > 1 such that $N = a^n - b^m$
When N is tiny and a,b,n,m are big the result sounds more interesting, like these examples
$2^{15} - 181^2 = 7$
$13^3 - 3^7 = 10$
$12^3 - 41^2 = 47$
$101^3 - 1015^2 = 76$
$6^7 - 529^2 = 95$
There is another relate question to the previous: can any integer N be written like difference of powers > 1 ?
$1 = 3^2 - 2^3$
$2 = 3^3 - 5^2$
$3 = 2^7 - 5^3$
$4 = 5^3 - 11^2$
$5 = 2^5 - 3^3$
$6 = ??$
$7 = 2^{15} - 181^2  = 2^7 - 11^2$
...


text:
Q: Display breadcrumbs of pages in a website I am very new to struts2 I want know how can I display navigation of pages in a website like
home->login->your account->xx-> etc in the current JSP page

A: I made it like this

 <s:a action="actionName_resultName" id="nav">Retailers </s:a> - Coupon      Options


text:
Q: How to insert extra rows into the same table using cursor and increase a column value of the new records In SQL Server, I want for every SELECT result to insert three new rows in the same table with itemid = max itemid + counter every time.
For example:
(ItemID, PackageID, ItemTypeID, ServiceID, ItemName, CreatedDate)
VALUES
    (17891, 5352, 7007, 2011, N'Firewall''s Lan NIC', '11/11/2015 6:50:51  PM'),
    (17892, 5352, 7008, 2011, N'Firewall''s Mng NIC', '11/11/2015 6:50:51 PM'),
    (17893, 5352, 7006, 2011, N'Firewall''s Wan NIC', '11/11/2015 6:50:51 PM')

*

*ItemID = primary key

*PackageID = from select query

*ItemTypeID = as it is

*ServiceID = from select query

*ItemName = as it is

*CreatedDate = now

I am trying this one to loop through SELECT results.
DECLARE @item_id int,
@package_id nvarchar(50),
@itemtype_id varchar(80),
@item_name varchar(80),
@service_id nvarchar(50);

DECLARE @message nvarchar(150)
PRINT '-------- Service Items Report --------';

DECLARE serviceitems_cursor CURSOR FOR
SELECT PackageID, ItemID
FROM ServiceItems
WHERE ItemTypeID = '7004'
ORDER BY ItemID;

OPEN serviceitems_cursor

FETCH NEXT FROM serviceitems_cursor
INTO @package_id, @itemtype_id

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT ' '
    SELECT @message = '-----Service Items from serviceitems_cursor  - packageId: ' + @package_id
    PRINT @message
        -- I want here to add three new rows
        -- For every new item row I want itemid to be SELECT MAX(ItemID) + thecounter  FROM ServiceItems
        -- /thecounter is the new counter after each insertion
    FETCH NEXT FROM serviceitems_cursor
    INTO @package_id, @itemtype_id
END
CLOSE serviceitems_cursor;
DEALLOCATE serviceitems_cursor;

How could I perform all new records to have current max itemid + the counter
SELECT MAX(ItemID) + 1  FROM ServiceItems )

For, example if the max itemId is 17890, new records will have
 17891, 17892, 17893

(first three rows insertion)
17894, 17895, 17896

(second three rows insertion) etc.

A: By two ways you can achieve this,
(1) Get the max of ItemId and put it in one local variable.
Declare @max_itemid int =(select max (itemid ) from services )

Already through cursor loop you have all the remaining column values in local variables. (From select query )
Now all you need to do is Insert. (Using union all )
Insert into services (
<column list >)
Select @max_itemid+1 as item_id, @pkg, @service_id, get date()
UNION ALL
Select @max_itemid+2 as item_id, @pkg, @service_id, get date()
UNION ALL
Select @max_itemid+3 as item_id, @pkg, @service_id, get date()

All the codes mentioned above should reside inside while @@fetch status block
(2) Approach two is simple, you don't need to get the max and increment it every time, make item_id as identity column. (Not sure your business needs accordingly you decide )


text:
Q: AWS API to upload file in S3 and write record in DB I need to implemnt a AWS backend API that allows the users of my mobile app to upload a file (image) in Amazon S3.
Creating an API directly interfaced with the Amazon S3 is not an option because i will not be able to correlate the uploaded file to the record of the user on DynamoDB.
I've thought to create a Lambda function (Java) triggered by an API that performs the following steps:
1) calls the Amazon S3 functionality to upload the file
2) write the record into my Dynamo DB with the reference of the file
Is there a way to provide a binary file in input to my Lambda function exposed as API?
please let me know. thank you!
davide

A: The best way to do this is with presigned URLs. You can generate a URL that will let the user upload files directly to S3 with specific name and type. This way you don't have to worry about big files slowing down your server, lambda limits, or double charges for bandwidth. It's also faster for the user in most cases and supports S3 transfer acceleration.
The process can look something like:

*

*User requests link from your server

*Your server writes an entry in DynamoDB and returns a presigned URL

*User uploads file directly to S3 using presigned URL (with exact name of your server's choice)

*Once upload is done you either get a notification using Lambda, or just have the user tell your server the upload is done

*Your server performs any required post-processing and marks the file as ready

And to answer your actual question, yes, there is a way to pass binary data to Lambda functions. The link is a step-by-step tutorial, but basically in API Gateway you have to set "Request body passthrough" to "When there are no templates defined (recommended)" and fill in your expected content types. Your mapping should include "base64data": "$input.body", and you need to setup your types under "Binary Support". In your actual lambda function, you should have access to the data as "base64data".


text:
Q: List all the cached keys in Flask Cache I have written an appliacation using Flask, and am caching the response of various api calls.
following is the configuration of my flask app
from flask import Flask
from flask_caching import Cache

app = Flask(__name__)

APICache = Cache(config={'CACHE_TYPE': 'filesystem','CACHE_DIR': "/cache"})
APICache.init_app(app)

How do I list all the key_prefix of all the cached data that has been stored until now ?

A: In the background, Flask-Caching uses cachelib, viewing how the cache system is implemented, filesystem doesn't have a dict or a way to access every key, the only way would be to list the directory, and call the get method for every file, like this:
for p in cache.cache._list_dir():
    k = os.path.split(p)[-1] # Getting just the key
    print(k, cache.get(k))


text:
Q: Browser windows are blank I have a very old laptop with Ubuntu on it and a few days before I updated it to version 22.04. After I did it all the windows that my browser create are completely blank. Before that I used 20.04 version and Chromium worked properly.

*

*I can see all the windows below browser window, sometimes a bit glitchy.

*There is no usual window border, but it works properly - I can resize a window or close it by pushing the place where close button usually is.

*Activity manager shows that the window is present, so does the dock.

I tried different browsers (Chromium, Chrome, Opera, Firefox) and they all created blank windows. I tried rebooting, clearing cache and reinstalling the app (from Software store) but nothing helped.
When starting Chromium from the command line it shows a lot of errors responding to the fact that my laptop doesn't have any GPU. However, when starting it with "--disable-gpu" flag I see the following:

*

*Gtk-message: Failed to load module "canberra-gtk-module" is outputted twice. I couldn't fix it myself.

*The blank window appears.

*After a few seconds [Error:udev_watcher.cc(98)] Failed to begin udev enumeration. appears.

*After that process doesn't stop until I press Ctrl+C or close the browser window.

Current Ubuntu version is 22.04.1, Chromium version is 105.0.5195.52 Snap.
Thank you for any help!


text:
Q: UITableViewCell - distinguish full edit mode and delete row mode I have UITableViewController and after user pres desired button, I have "full edit" mode. To enable this, I call this:
@objc func btnEditPressed(sender: UIButton) {
   sender.isSelected = !self.isEditing
   self.setEditing(!self.isEditing, animated: true)

   self.tableView.beginUpdates()
   self.tableView.endUpdates()
}

for each UITableViewCell, I have override func setEditing(_ editing: Bool, animated: Bool) method. In this, I hide some parts of cell in "full edit" mode.
Now, when the user swipe single table row, I show the delete button. However, in this "delete row mode" I dont want to hide any information from the cell. The problem is, that the same override func setEditing(_ editing: Bool, animated: Bool) for the cell is called as in the first case, leading to hiding cell content.
Is there an easy way, how to solve this, or I have to keep weak reference to UITableViewController and check the mode from the cell myself?

A: You have two options to handle this.

*

*Check showingDeleteConfirmation in the cell's setEditing method.

*Override willTransition(to:) and didTransition(to:) in your cell class.

If your table view is not in editing mode and the user performs a swipe-to-delete gesture, then your cell will experience the following sequence:

*

*willTransition(to:) will be called with the mask including the value UITableViewCell.StateMask.showingDeleteConfirmation

*setEditing will be called with editing set to true. The cell's showingDeleteConfirmation will be equal to true

*didTransition(to:) will be called with the mask including the value UITableViewCell.StateMask.showingDeleteConfirmation
So the simplest solution is to update your cell's setEditing:
override func setEditing(_ editing: Bool, animated: Bool) {
    super.setEditing(editing, animated: animated)

    if showingDeleteConfirmation {
        // User did a swipe-to-delete
    } else {
        // The table view is in full edit mode
    }
}


text:
Q: Fetching json from MVC Controller I am trying to fetch some records from database in ASP.Net MVC and KnockoutJs.
Following is my controller method in MVC
public JsonResult FetchAccountCodes(string code = "")
        {
            var coaCode = db.ChartOfAccounts.Where(m => m.ACCOUNT_CODE.StartsWith(code)).Select(x => new { x.ACCOUNT_CODE }).ToList();
            return Json(coaCode, JsonRequestBehavior.AllowGet);
        }

and KnockoutJs code
self.selectedSubAccount.subscribe(function (newValue) {
                var likeCode = newValue.substring(0, 2);
                var param = { code: likeCode };
                $.ajax({
                    type: "post",
                    url: "/ChartOfAccounts/FetchAccountCodes",
                    contentType: "application/x-www-form-urlencoded",
                    dataType: "json",
                    data: param,
                    success: function (data) {
                        self.ACCOUNTCODES(data)
                    },
                    error: function (error) {
                        alert("Could not load the Account Codes" + error.status + "<--and--> " + error.statusText);
                    }
                });
                var accType = "Control";
                self.ACCOUNT_CODE(GenrateAccountCode(likeCode, accType));
            });

The problem is that ACCOUNTCODES observable array did not populated with the returned json.
and remains null.

A: When returning a list from the controller, I've found that sometimes I need to wrap the list in an anonymous object for things to work properly. The named property seems to help.
public JsonResult FetchAccountCodes(string code = "")
{
    var coaCode = db.ChartOfAccounts.Where(m => m.ACCOUNT_CODE.StartsWith(code)).Select(x => new { x.ACCOUNT_CODE }).ToList();
    return Json(new {AccountCodes = coaCode}, JsonRequestBehavior.AllowGet);
}

self.selectedSubAccount.subscribe(function (newValue) {
            var likeCode = newValue.substring(0, 2);
            var param = { code: likeCode };
            $.ajax({
                type: "post",
                url: "/ChartOfAccounts/FetchAccountCodes",
                contentType: "application/x-www-form-urlencoded",
                dataType: "json",
                data: param,
                success: function (data) {
                    self.ACCOUNTCODES(data.AccountCodes)
                },
                error: function (error) {
                    alert("Could not load the Account Codes" + error.status + "<--and--> " + error.statusText);
                }
            });
            var accType = "Control";
            self.ACCOUNT_CODE(GenrateAccountCode(likeCode, accType));
        });

A: Here is my Http Header:
Request URL:http://localhost:20613/ChartOfAccounts/FetchAccountCodes?code=21
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Connection:keep-alive
Content-Type:application/x-www-form-urlencoded
Cookie:__iswl_localhost:20613=0; __RequestVerificationToken=0rHILZnMkH6IJ7JK0CUF26vxcZP-RmuoZFGPHwhmQyGL_k_UCJCpxORbOQxUnyjVXeGLRZvG64ICgCb5B47Sqaqotbvin6snSg-ojWaLi7o1; instance0|session_id=%223bb6b256463042ada79bbec7934180ed%22; last_used_database=acompany; sid=7e671736a7a7fd3903a90716f2fc6d76c09e84a2; __iswl_localhost:20613=0; .AspNet.ApplicationCookie=HbluCWr03lY5R2jEvC_25yDkMMIrIXOrpajLFV2RJORdMAidF49lNH9tYhRGYc8KZpAJsolViQ3Igw5fc1vPoxGUwtWe3EXPWQCpcrVjtl6BzJ85CmMNNjF2hOQCSyIrT8bJHhEysirnH-c106mTe1LFT7bTyDeAsxhYxn1oPTqtLBzrY4uqtrywxclgveVP8gKmbhkeCRNLzPSShjUMbatAfHy7LirRsyTvqICntIIcci6tMKl8jQd8d65XhHgfKXmOFZGkHQTwdgqAWu2fb_6KkbK5fkoT9jXmgPZJ-8MeCLZ7dWQY7VygknXIgLHHu1mq2AX3ogXVuO0whb4DoqX6k8U_ac8G_4sM6djuPtF4vvrq89mkXSsx1UyJG-idMHzaPn8BziIRtamJP9cCLonyLszxSfuu-jSk1YAQcp1Az-28LUKNq7gFph3a23D3b0wMjJDwG1aqvnthfXYs_U93-FKw7u0JJO1FQkJBx2A
Host:localhost:20613
Referer:http://localhost:20613/ChartOfAccounts/Index
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36
X-Requested-With:XMLHttpRequest
Query String Parametersview sourceview URL encoded
code:21
Response Headersview source
Cache-Control:private
Content-Length:74
Content-Type:application/json; charset=utf-8
Date:Thu, 06 Feb 2014 13:34:45 GMT
Server:Microsoft-IIS/8.0
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:5.0
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?RTpcUHJvamVjdHNcRG90TmV0XE1WQzVcVU1NSVRleHRpbGVcVU1NSVRleHRpbGVcQ2hhcnRPZkFjY291bnRzXEZldGNoQWNjb3VudENvZGVz?=

and Response:
 {"AccountCodes":[{"ACCOUNT_CODE":"21000000"},{"ACCOUNT_CODE":"21010000"}]}

this the array in http response


text:
Q: Type mismatch error when assigning a variable to an object of the same type I'm working on an Iterator for a linked list class. I am assigning nodes to variables within an inner class and am getting a "Type mismatch" error. Relevant code is below.
public class RegLinkList<T> implements Iterable<T>{
    private Node<T> head;
public RegLinkList() {
        head = null;
    }
 public class Node<T> {
   public Node<T> next = null;
   public T data = null;

   Node(T data){
        this.data = data;
    }
  }
    public class ListIterator<T> implements Iterator<T>{
    Node<T> current = head;
    Node<T> previous = head;

I get this:
    Type mismatch: cannot convert from
    RegLinkList<T>.Node<T> to RegLinkList<T>.Node<T>

Edit:
My current solution is an unchecked cast of
    public class ListIterator<T> implements Iterator<T>{
    Node<T> current = (Node<T>) head;
    Node<T> previous = (Node<T>) head;

A: The reason why you get this error is that the compiler does what you say and not what you mean. The T for ListIterator and the T of the RegLinkList are seen as two different types. It would become more clear if you used e.g. U instead of T.
A solution to your problem could be making the classes static and pass the head element to the constructor. That way you still declare different Ts but because you pass the original element (and therefor "telling" the compiler that the one T is the same as the other), it will be happy. The following code is happily compiled (I added missing method implementations with no functionalities):
import java.util.Iterator;

public class RegLinkList<T> implements Iterable<T> {
    private Node<T> head;

    public RegLinkList() {
        head = null;
    }

    public static class Node<T> {
        public Node<T> next = null;
        public T data = null;

        Node(T data) {
            this.data = data;
        }
    }

    public static class ListIterator<T> implements Iterator<T> {
        Node<T> current;
        Node<T> previous;

        public ListIterator(Node<T> head) {
            current = head;
            previous = head;
        }

        @Override
        public boolean hasNext() {
            return false;
        }
        @Override
        public T next() {
            return null;
        }
    }

    @Override
    public Iterator<T> iterator() {
        return new ListIterator<T>(head);
    }
}


text:
Q: MSSQL - Loop through table and use field value in new query I have a factory table with factoryname: select factoryname from factory
I then have a products table: select productcode from products
I want to create a list that has products for all factory.
so output :
mill 1 product 1
mill 1 product 2
mill 1 product 3
mill 2 product 1
mill 2 product 2
mill 2 product 3
mill 3 product 1
mill 3 product 2
mill 3 product 3

I have something like this:
DECLARE @numrows int
DECLARE @i int
DECLARE @department int

 SET @numrows = (SELECT COUNT(*) FROM factory)
WHILE (@i <= @numrows)
    BEGIN
        SELECT factoryname,product FROM products,factory )
        SET @i = @i + 1
    END

I am obviously off the mark, here, any advice? Thanks as always.

A: SQL is a set based language, so you should try not to use loops in SQL whereever possible.  It will hurt performance.
What you want to do, is use a JOIN to JOIN 2 tables together:
SELECT factory.factoryname, products.productcode
FROM factory, products
INNER JOIN products.factory_id = factory.factory_id

Something like this.
This will give you a collection of products that are made in a certain factory.
Displaying this in a nice way to the user should be done in your UI layer in your application.  Do not try to use SQL to properly format data.

A: If you want to list all the factory names and all products, you can use a cross join like this:
    select factoryname, productname from factory cross join products

A Cross Join is basically a Cartesian product of 2 tables, resulting in (m * n) records if table 1 has m and table 2 has n records.

A: JOIN will be effective solution for the above but there should be common column in both the tables.
INNER JOIN is most suitable if for all factories you have some product.
LEFT JOIN will work if you want all factories to be listed though there are factories for which there is no product.
RIGHT JOIN will work if you want all products to be listed and there are products for which there is no corresponding factory in factory table.
Hope it helps....someway..........


text:
Q: NativeCrashListener: Exception dealing with report when Gridview Scrolling please help, when i scroll down the gridview and up suddenly the app goes out i try to see the error log, which i get error like this. Thank you for your help
E/NativeCrashListener: Exception dealing with report
                                                      android.system.ErrnoException: read failed: EAGAIN (Try again)
                                                          at libcore.io.Posix.readBytes(Native Method)
                                                          at libcore.io.Posix.read(Posix.java:169)
                                                          at libcore.io.BlockGuardOs.read(BlockGuardOs.java:230)
                                                          at android.system.Os.read(Os.java:367)
                                                          at com.android.server.am.NativeCrashListener.consumeNativeCrashData(NativeCrashListener.java:240)
                                                          at com.android.server.am.NativeCrashListener.run(NativeCrashListener.java:138)


text:
Q: Mutagen raise error while trying to read m4b file this is my first post here on SO. I am trying to read a m4b file using Mutagen on Python 3. Here is the code I am using.
for file in os.listdir(workingdir):
    if file.endswith('.m4b'):
      workingdirectory = 'my/directory/'
      commandtoexecute = ""
      metadata = MP4(file)
      print('read')
      xa9ART1 = metadata['\xa9ART']
      xa9nam1 = metadata['\xa9nam']
      xa9alb1 = metadata['\xa9alb']

and here is the error Im getting,
Traceback (most recent call last):
  File "C:\Python37\lib\site-packages\mutagen\mp4\_as_entry.py", line 183, in _parse_esds
    decSpecificInfo = ES_Descriptor.parse(fileobj)
  File "C:\Python37\lib\site-packages\mutagen\mp4\_as_entry.py", line 240, in parse
    instance = cls(fileobj, length)
  File "C:\Python37\lib\site-packages\mutagen\mp4\_as_entry.py", line 278, in __init__
    self.decConfigDescr = DecoderConfigDescriptor.parse(fileobj)
  File "C:\Python37\lib\site-packages\mutagen\mp4\_as_entry.py", line 240, in parse
    instance = cls(fileobj, length)
  File "C:\Python37\lib\site-packages\mutagen\mp4\_as_entry.py", line 315, in __init__
    self.decSpecificInfo = DecoderSpecificInfo.parse(fileobj)
  File "C:\Python37\lib\site-packages\mutagen\mp4\_as_entry.py", line 243, in parse
    raise DescriptorError("descriptor parsing read too much data")
mutagen.mp4._as_entry.DescriptorError: descriptor parsing read too much data

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python37\lib\site-packages\mutagen\mp4\__init__.py", line 1014, in _parse_stsd
    entry = AudioSampleEntry(entry_atom, entry_fileobj)
  File "C:\Python37\lib\site-packages\mutagen\mp4\_as_entry.py", line 79, in __init__
    self._parse_esds(extra, fileobj)
  File "C:\Python37\lib\site-packages\mutagen\mp4\_as_entry.py", line 185, in _parse_esds
    raise ASEntryError(e)
mutagen.mp4._as_entry.ASEntryError: descriptor parsing read too much data

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\aud.py", line 944, in <module>
    my_function()
  File "C:\Users\Administrator\Desktop\aud.py", line 336, in create_rar
    metadata = MP4(file)
  File "C:\Python37\lib\site-packages\mutagen\_file.py", line 49, in __init__
    self.load(*args, **kwargs)
  File "C:\Python37\lib\site-packages\mutagen\_util.py", line 140, in wrapper
    return func(self, h, *args, **kwargs)
  File "C:\Python37\lib\site-packages\mutagen\mp4\__init__.py", line 1061, in load
    self.info.load(atoms, fileobj)
  File "C:\Python37\lib\site-packages\mutagen\_util.py", line 169, in wrapper
    return func(*args, **kwargs)
  File "C:\Python37\lib\site-packages\mutagen\mp4\__init__.py", line 976, in load
    self._parse_stsd(atom, fileobj)
  File "C:\Python37\lib\site-packages\mutagen\mp4\__init__.py", line 1016, in _parse_stsd
    raise MP4StreamInfoError(e)
mutagen.mp4.MP4StreamInfoError: descriptor parsing read too much data

I have tried it several times on several audios, but seems its stuck this way for me. Id be very glad to get help from here.
Thankyou.


text:
Q: System.IO.IOException: Connection timed out In Mailkit I used MailKit.Net.Imap to read email in my mail box.
Sometimes I get an exception like that I shared below
System.IO.IOException: Connection timed out ---> System.Net.Sockets.SocketException (110): Connection timed out at MailKit.Net.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 count) --- End of inner exception stack trace ---
Is there any suggistion to solve this problem?
   ImapClient client;

    client = new ImapClient();
    client.Timeout= (int)TimeSpan.FromMinutes(1).TotalMilliseconds;

Also, I can use timeout property of Imap, this can help me to solve this problem?

A: You have 2 options:

*

*Increase the timeout using the ImapClient.Timeout property. (That said, 1 minute is less than the default timeout which is 2 minutes)

*As Max points out in the comments below, properly handle exceptions and retry (which often will require reconnecting the ImapClient).


text:
Q: cryptocoin address generation Recently have been looking at crypto currencies, mostly Bitcoin and Dogecoin. I'm using this source for my project. I've got Bitcoin to work perfectly, and since the Bitcoin gem did not have native support for Dogecoin I had to self-implement it.
Also noticed that another githubber had opened tried to implement dogecoin support, which as of now did not generating address correctly.
The problem seems to  be in this particular line. (corresponding to the format of the crypto address)
:address_version => "30"

:address_version = PUBKEY_ADDRESS in base58.h

base58.h
PUBKEY_ADRESS contains value 30.
Specifying this particular number will give address beginning with letter 'L' (litecoin address), where Dogecoin requires 'D'.
Does this have anything to do with Doge using scrypt, I have no technical expertise in this field. How do I go about generating dogecoin pubkey/private key pair?

A: 30 in decimal will give you a address begins with a letter D
30 in hexadecimal (48 in decimal) will give you a address begins with letter L
I think that bitcoin-ruby first changes PUBKEY_ADDRESS from hexa to decimal so :address_version should be 1E (30 in decimal)


text:
Q: Cannot get bash variable changed in sourced script after pipe? I constructed a simple example to illustrate the problem:
caller.sh:
#!/usr/bin/env bash
state="loaded"
source "sh/callee.sh" 2>&1
echo "$state"

callee.sh:
#!/usr/bin/env bash
state="integrated"

when I run caller.sh, it gives the result I want:
integrated

But if I add a pipe after the source command:
caller.sh:
#!/usr/bin/env bash
state="loaded"
source "sh/callee.sh" 2>&1 | cat
echo "$state"

The result becomes:
loaded

Question: How can I preserve/retrieve the changed value of $state in caller.sh?

A: You can't use a pipe. The source command runs in a subshell that exits after the pipe completes, so state is never set in the shell that calls echo "$state". You can use process substitution to "invert" the pipeline:
state="loaded"
source "sh/callee.sh" 2>&1 > >(cat)
echo "$state"

Now source executes in the same shell.


text:
Q: What is the use of firebase messaging in telegram I downloaded the android version source code from here.
Part of the instructions are:
Go to https://console.firebase.google.com/, create two android apps with application IDs org.telegram.messenger and org.telegram.messenger.beta, turn on firebase messaging and download google-services.json, which should be copied to the same folder as TMessagesProj.
Does anyone know what is the use of this?
I have a problem with missing chats and messages and I think I may be related to this.
Thanks

A: Those are instructions to create your own version of Telegram.
It is obviously using the Firebase Cloud Messaging. The won't give you access to theire FCM project settings so you need to create your own project and use them for your notifications.
If you have issues with Telegram installed on your device this won't help you.


text:
Q: What are __darwin_obsz() and __darwin_obsz0()? On MacOS, several functions including memcpy, memmove, memset, and others are implemented as such, making use of a mysterious __darwin_obsz0() function:
#if __has_builtin(__builtin___memcpy_chk) || defined(__GNUC__)
#undef memcpy
#define memcpy(dest, src, len)                  \
  __builtin___memcpy_chk (dest, src, len, __darwin_obsz0 (dest))
#endif

#if __has_builtin(__builtin___memmove_chk) || defined(__GNUC__)
#undef memmove
#define memmove(dest, src, len)                 \
  __builtin___memmove_chk (dest, src, len, __darwin_obsz0 (dest))
#endif

#if __has_builtin(__builtin___memset_chk) || defined(__GNUC__)
#undef memset
#define memset(dest, val, len)                  \
  __builtin___memset_chk (dest, val, len, __darwin_obsz0 (dest))
#endif

Similarly, strcpy makes use of a mysterious __darwin_obsz function:
#if __has_builtin(__builtin___strcpy_chk) || defined(__GNUC__)
#undef strcpy
#define strcpy(dest, src)                   \
  __builtin___strcpy_chk (dest, src, __darwin_obsz (dest))
#endif

What are these (macros?) functions and what do they do? I could not find any documentation about them.

A: Seems to me like they are simple macros that expand to compiler built-ins to calculate the size of an object at compile time. This file include/secure/_common.h from Apple Open Source has their definition:
#define __darwin_obsz0(object) __builtin_object_size (object, 0)
#define __darwin_obsz(object) __builtin_object_size (object, _USE_FORTIFY_LEVEL > 1 ? 1 : 0)

__builtin_object_size should be equivalent between Clang and GCC. The GCC documentation describes it in this page.
These sizes are passed as last argument to the *_chk() alternative of common memory copying functions such as memcpy() and strcpy(), supposedly in an effort to make the code more secure, trying to avoid memory corruption in case the wrong size is passed by the user, since the destination object size is checked by those functions.


text:
Q: Mock UIView extension "ApiProtocol" in test - swift4 Given a protocol and extension that is "injected" into MyUIView.
The func stubMePlease() can be called and it returns "hello world" as expected.
When doing unit test stubMePlease() needs to be mocked in 3 different test.
What would be the best approach?
Protocol & Extension
protocol ApiProtocol {
    func stubMePlease() -> String
}

extension ApiProtocol {
    func stubMePlease() -> String {
        return "hello world"
    }
}

UIView "inject/extend" ApiProtocol
class MyUIView: UIView, ApiProtocol {

    override init(frame: CGRect) {
        super.init(frame: frame)
        foo()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    public func foo() -> String {
        return self.stubMePlease() // returns "hello world"
    }
}

Test class
import XCTest
class test: XCTestCase {
    var myview: MyUIView!

    override func setUp() {
        super.setUp()
        myview = MyUIView()
    }

    func testA() {
        let kom = myview.foo()
        XCTAssertEqual(kom, "hello") // how do I mock this with "hello"
    }

    func testB() {
        let kom = myview.foo()
        XCTAssertEqual(kom, "weekend") // how do I mock this with "weekend"
    }

    func testC() {
        let kom = myview.foo()
        XCTAssertEqual(kom, "swift") // how do I mock this with "swift"
    }
}

Thanks

A: You shouldn't use "extension" to implement functions of a protocol, you should use it to extend your protocol, i.e. add new functions. Normally you extend your own protocol with some convenience method overloads and implement them in terms of methods in the protocol so that each class that implements that same protocol can avoid implementing them (while clients benefit from the overloads).
First of all you need to have actual implementations of your protocol:
class ApiProtocolForTests: ApiProtocol {
    func stubMePlease() -> String {
        return "fake hello world in test"
    }
}

class ApiProtocolForRealz: ApiProtocol {
    func stubMePlease() -> String {
        return "hello world in real life"
    }
}

Then in MyUIView instead of inheriting/implementing ApiProtocol, which doesn't make sense conceptually, you should pass it in your init constructors, for example:
class MyUIView: UIView {
    let api: ApiProtocol

    override init(frame: CGRect, api: ApiProtocol) {
        super.init(frame: frame)
        self.api = api
        foo()
    }
    ...

In the tests you would create MyUIView by providing it a ApiProtocolForTests version of the protocol: myview = MyUIView(frame: frame, api: ApiProtocolForTests())
This is also known as "injecting" a dependency "ApiProtocol".


text:
Q: Unable To install Ubuntu on MSI Laptop I have recently bought an MSI PE62 7RD laptop. The problem is that I'm not able to install Ubuntu on my laptop. The installation is freezing during the booting into USB. The culprit for this kind of behavior seems to originate from a BIOS bug.
I have completely updated my BIOS and still I cannot install Ubuntu.
I am currently running Windows 10 in legacy-mode and I plan to dual-boot my system.
This occurs during initial boot from USB: https://imgur.com/a/OT2RZ

A: I have found the solution for the problem. First During the initial boot time
press e in the grub or tab during installation and add acpi=off after quiet splash This turns off the acpi functionality. after entering the os install updates in ubuntu with
sudo apt update
sudo apt upgrade
after installing update turn off computer using manual power-off button since acpi shutdown  wont work. Now you can use your ubuntu without any problem


text:
Q: magento security patch I download magento security patch and install in my site
domain.com/patch.php

Below i mention patch.php file
<?php
    print("<PRE>");
    passthru("/bin/bash PATCH_SUPEE-6788_CE_1.9.0.1_v1-2015-10-26-11-46-45.sh");
    print("</PRE>");
    echo "Done";
?>

After that i got this
Checking if patch can be applied/reverted successfully...
ERROR: Patch can't be applied/reverted successfully.

patching file .htaccess
Hunk #1 FAILED at 207.
1 out of 1 hunk FAILED -- saving rejects to file .htaccess.rej
can't find file to patch at input line 38
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git .htaccess.sample .htaccess.sample
|index b8821af..383313a 100644
|--- .htaccess.sample
|+++ .htaccess.sample
--------------------------
File to patch:
Skip this patch? [y]
Skipping patch.
1 out of 1 hunk ignored
patching file app/code/core/Mage/Admin/Model/Block.php
patching file app/code/core/Mage/Admin/Model/Resource/Block.php
patching file app/code/core/Mage/Admin/Model/Resource/Block/Collection.php
patching file app/code/core/Mage/Admin/Model/Resource/Variable.php
patching file app/code/core/Mage/Admin/Model/Resource/Variable/Collection.php
patching file app/code/core/Mage/Admin/Model/Variable.php
patching file app/code/core/Mage/Admin/etc/config.xml
patching file app/code/core/Mage/Admin/sql/admin_setup/upgrade-1.6.1.1-1.6.1.2.php
patching file app/code/core/Mage/Adminhtml/Block/Permissions/Block.php
patching file app/code/core/Mage/Adminhtml/Block/Permissions/Block/Edit.php
patching file app/code/core/Mage/Adminhtml/Block/Permissions/Block/Edit/Form.php
patching file app/code/core/Mage/Adminhtml/Block/Permissions/Block/Grid.php
patching file app/code/core/Mage/Adminhtml/Block/Permissions/Variable.php
patching file app/code/core/Mage/Adminhtml/Block/Permissions/Variable/Edit.php
patching file app/code/core/Mage/Adminhtml/Block/Permissions/Variable/Edit/Form.php
patching file app/code/core/Mage/Adminhtml/Block/Permissions/Variable/Grid.php
patching file app/code/core/Mage/Adminhtml/controllers/Permissions/BlockController.php
patching file app/code/core/Mage/Adminhtml/controllers/Permissions/VariableController.php
patching file app/code/core/Mage/Adminhtml/etc/adminhtml.xml
patching file app/code/core/Mage/Catalog/Model/Product/Option/Type/File.php
patching file app/code/core/Mage/Core/Controller/Request/Http.php
Hunk #1 succeeded at 291 (offset -7 lines).
patching file app/code/core/Mage/Core/Controller/Varien/Router/Admin.php
Hunk #1 FAILED at 131.
1 out of 1 hunk FAILED -- saving rejects to file app/code/core/Mage/Core/Controller/Varien/Router/Admin.php.rej
patching file app/code/core/Mage/Core/Helper/UnserializeArray.php
patching file app/code/core/Mage/Core/Model/Email/Template/Filter.php
patching file app/code/core/Mage/Core/Model/Resource/Setup.php
patching file app/code/core/Mage/Core/etc/config.xml
patching file app/code/core/Mage/Core/etc/system.xml
patching file app/code/core/Mage/Customer/Block/Account/Changeforgotten.php
patching file app/code/core/Mage/Customer/Block/Account/Resetpassword.php
patching file app/code/core/Mage/Customer/controllers/AccountController.php
Hunk #1 succeeded at 36 with fuzz 1 (offset 3 lines).
Hunk #2 succeeded at 78 (offset 3 lines).
Hunk #3 succeeded at 276 (offset 9 lines).
Hunk #4 succeeded at 313 (offset 9 lines).
Hunk #5 succeeded at 389 (offset 9 lines).
Hunk #6 succeeded at 397 (offset 9 lines).
Hunk #7 succeeded at 764 (offset 9 lines).
Hunk #8 succeeded at 807 (offset 9 lines).
Hunk #9 succeeded at 838 (offset 9 lines).
Hunk #10 succeeded at 848 (offset 9 lines).
Hunk #11 succeeded at 1033 (offset 9 lines).
patching file app/code/core/Mage/Downloadable/Model/Product/Type.php
patching file app/code/core/Mage/Eav/Model/Resource/Attribute/Collection.php
patching file app/code/core/Mage/Sales/Model/Resource/Order/Item/Collection.php
patching file app/code/core/Mage/Sales/controllers/DownloadController.php
patching file app/code/core/Mage/SalesRule/Model/Resource/Coupon/Collection.php
patching file app/code/core/Zend/Soap/Server.php
patching file app/code/core/Zend/Xml/Exception.php
patching file app/code/core/Zend/Xml/Security.php
patching file app/code/core/Zend/XmlRpc/Request.php
patching file app/code/core/Zend/XmlRpc/Response.php
patching file app/design/adminhtml/default/default/layout/admin.xml
patching file app/design/frontend/base/default/layout/customer.xml
patching file app/design/frontend/base/default/template/customer/form/register.phtml
patching file app/design/frontend/base/default/template/customer/form/resetforgottenpassword.phtml
patching file app/design/frontend/base/default/template/page/js/cookie.phtml
patching file app/design/frontend/base/default/template/persistent/customer/form/register.phtml
patching file app/design/frontend/default/iphone/layout/customer.xml
patching file app/design/frontend/default/modern/layout/customer.xml
patching file app/design/frontend/rwd/default/layout/customer.xml
patching file app/design/frontend/rwd/default/template/customer/form/resetforgottenpassword.phtml
patching file app/design/frontend/rwd/default/template/persistent/customer/form/register.phtml
patching file cron.php
patching file errors/processor.php
Hunk #1 succeeded at 463 with fuzz 2.
patching file lib/Unserialize/Parser.php
patching file lib/Unserialize/Reader/Arr.php
patching file lib/Unserialize/Reader/ArrKey.php
patching file lib/Unserialize/Reader/ArrValue.php
patching file lib/Unserialize/Reader/Bool.php
patching file lib/Unserialize/Reader/Dbl.php
patching file lib/Unserialize/Reader/Int.php
patching file lib/Unserialize/Reader/Str.php
patching file lib/Varien/Data/Collection/Db.php
Done

But i don't know what it's can anyone explain security patch applied or not
I am using Magento 1.9.0.1

A: The patch is failing because of a modified .htaccess file and a missing .htaccess.sample file
patching file .htaccess     <==== This failed to apply
Hunk #1 FAILED at 207.
1 out of 1 hunk FAILED -- saving rejects to file .htaccess.rej
can't find file to patch at input line 38
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git .htaccess.sample .htaccess.sample <==== This is missing
|index b8821af..383313a 100644
|--- .htaccess.sample
|+++ .htaccess.sample
--------------------------
File to patch:
Skip this patch? [y]
Skipping patch.
1 out of 1 hunk ignored

This can be recovered from by backing up your .htaccess file to somewhere safe, downloading the full installation archive for your version (1.9.0.1), extracting these two files and uploading them to the server you are trying to patch.
You will need to merge the changes between your previous .htaccess file and the patched .htaccess file
======
The next issue
And SUPEE-5994 needs to be installed before running this patch install.  The file app/code/core/Mage/Core/Controller/Varien/Router/Admin.php does not exist until SUPEE-5994 creates it. The SUPEE-5994 patch seems to have been applied because the file exists, but the file was not created properly. I'm guessing that it was downloaded from elsewhere and uploaded to the site.
patching file app/code/core/Mage/Core/Controller/Varien/Router/Admin.php
Hunk #1 FAILED at 131.
1 out of 1 hunk FAILED -- saving rejects to file app/code/core/Mage/Core/Controller/Varien/Router/Admin.php.rej

And SUPEE-5994 install can be problematic, for more information => Error after successful SUPEE-5994 install
Once you have the .htaccess and .htaccess.sample files in place and the SUPEE-5994 patched file returned to what its original state should have been, then you can try running SUPEE-6788
USUAL WARNINGS APPLY ON NOT RUNNING THIS ON YOUR LIVE SITE FIRST

A: Most files are patched, but if you look closely:

patching file
app/code/core/Mage/Core/Controller/Varien/Router/Admin.php Hunk #1
FAILED at 131. 1 out of 1 hunk FAILED -- saving rejects to file
app/code/core/Mage/Core/Controller/Varien/Router/Admin.php.rej

Before doing anything else : please backup your whole site (especially when patching or changing code).
Maybe this could help you: Patch without SSH 6788 (be sure to download correct version).
Unzip it and replace files (files patch couldn't patch) on your server.
PS. That patch should work (and it worked on all sites). So: backup first.


text:
Q: ASP.NET super fast data search for autocomplete, please guide me Thanks for your time and attention.
I have ajaxtookit Autocomplete and requriment is to make it super fast. Currently data is in database and on every request it is fetched and come from database. This data are contacts and addresses and often new records will be added in the tables. There are 3 solutions that come to mind. Please guide me what you suggest and  what you feel is the best.

*

*Let the data in database, just do indexing and if possible do some connection polling so that connection establishing time can be saved.

*Cache data in application server. Use Linq to query.

*Do search on sorted data in some file.
Please guide and help me.
Thanks

A: If your data doesn't change very often, I'd go with server-side caching.

A: Here's a few tips:

*

*Use a stored procedure for the database work - optimize it as well as reasonably possible (use indexes, hints, views, etc). Using a stored procedure will allow the execution plan to be "cached" in the DB engine so it doesn't have to be re-calculated each time. Don't use LINQ or ADO.NET - these are provider translation overheads which you cannot afford in this particular scenario - go straight to native SQL. Using a stored procedure means your writing native SQL from the get go, as opposed to LINQ-SQL/LINQ-Entities where the expression tree needs to be translated to native SQL. You can't afford this overhead (you don't need to). Of course depending on your ORM (if you have one), there are steps to counter-act this such as compiled queries in Entity Framework.

*Cache Option #1 - "Recent Queries". We have a "SearchQuery" cache table. We keep track of searches, and what "matched" record is kept against it. (So "New York" might have "NY", "New York", "new york", "nyc" all related to it). This way, we don't have to keep on "figuring out" the matching record(s) for the autocomplete user query (however you do it, be it SQL Server FTS, a T-SQL LIKE, or basic LINQ/string operations). This can save you a lot of time. You can cache "the last 100 searches" in memory to add some bonus speed.

*Cache Option #2 - "Data". Cache the result of the database call on the web server. The cache key should match the parameters to the stored procedure.

*Cache Option #3 - "Output (JSON/XML)". I assume you are using ASP.NET Web Forms, and not MVC. So im guessing you have a ASMX/WCF Web Service responding to your auto complete calls. You can cache the output of this web method call, in addition to caching the actual data. Just be wary that combined output/data caching can cause "stale" data if the expirations aren't handled effectively.
HTH


text:
Q: What should I do to force the root filesystem check (and optionally a fix) at boot? Yesterday, one of our computers dropped to grub shell or honestly, I am unsure what shell it was when we turned on the machine.
It showed that it can't mount the root filesystem or something in this sense, because of inconsistencies.
I ran, I believe:
fsck -fy /dev/sda2

Rebooted and the problem was gone.
Here comes the question part:
I already have in her root's crontab:

@reboot /home/ruzena/Development/bash/fs-check.sh

while the script contains:
#!/bin/bash
touch /forcefsck

Thinking about it, I don't know, why I created script file for such a short command, but anyways...
Further, in the file:
/etc/default/rcS

I have defined:

FSCKFIX=yes

So I don't get it. How could the situation even arise?

What should I do to force the root filesystem check (and optionally a fix) at boot?
Or are these two things the maximum, that I can do?
OS: Linux Mint 18.x Cinnamon 64-bit.
fstab:
cat /etc/fstab | grep ext4

shows:

UUID=a121371e-eb12-43a0-a5ae-11af58ad09f4    /    ext4    errors=remount-ro    0    1

grub:

fsck.mode=force

was already added to the grub configuration.

A: Further investigation and updates upon existing answer
I now just wanted to check, whether the above still works on Ubuntu 20.04 LTS based systems (directly tested on Linux Mint 20 Cinnamon amd64 desktop and Ubuntu MATE 20.04 amd64 desktop), and I found out a few things, let's start with the file system check interval (I ran all commands as root (as you might notice ~# in front of commands):

File system check interval
~# LC_ALL=C tune2fs -l /dev/nvme0n1p2 | grep 'Check interval'

Check interval:           0 (<none>)

Well, this was unexpected. I thought we took care of it, but can be fixed very easy luckily. Take note, the number it takes as an argument is by default in days, so be sure to use 1s (1 seconds) instead of just 1 which would mean 1 day (86400 seconds):
~# LC_ALL=C tune2fs -i 1s /dev/nvme0n1p2

tune2fs 1.45.5 (07-Jan-2020)
Setting interval between checks to 1 seconds

Now, if we repeat the above check, we get:
Check interval:           1 (0:00:01)

This does not mean the file system will be checked every one second, of course. Rather, in effect it will force the file system check on every file system mount. (As there is no way of booting any system twice in one second .)

File system maximum number of mounts before check
Default setting:
~# LC_ALL=C tune2fs -l /dev/nvme0n1p2 | grep 'Maximum mount count'

Maximum mount count:      -1

This setting adjusts how many mounts it takes till the file system gets checked. It's ok what is written in the original answer:
~# LC_ALL=C tune2fs -c 1 /dev/nvme0n1p2

tune2fs 1.45.5 (07-Jan-2020)
Setting maximal mount count to 1

Just make sure you do not use 0 or -1 as it would become disregarded.

I will probably add more info later on... So, keep checking (pun intended).
Information sources:

*

*tune2fs man page

A: ext4 filesystem check during boot
Tested on OS: Linux Mint 18.x in a Virtual Machine
Basic information
/etc/fstab has the fsck order as the last (6th) column, for instance:
<file system>    <mount point>    <type>    <options>    <dump>    <fsck>
UUID=2fbcf5e7-1234-abcd-88e8-a72d15580c99 / ext4 errors=remount-ro 0 1

FSCKFIX=yes variable in /etc/default/rcS
This will change the fsck to auto fix, but not force a fsck check.
From man rcS:

FSCKFIX
    When  the  root  and all other file systems are checked, fsck is
    invoked with the -a option which means "autorepair".   If  there
    are  major  inconsistencies then the fsck process will bail out.
    The system will print a  message  asking  the  administrator  to
    repair  the  file  system manually and will present a root shell
    prompt (actually a sulogin prompt) on the console.  Setting this
    option  to  yes  causes  the fsck commands to be run with the -y
    option instead of the -a option.  This will tell fsck always  to
    repair the file systems without asking for permission.

From man tune2fs

If you are using journaling on your filesystem, your filesystem
will never be marked dirty, so it will not normally be checked.

Start with
Setting the following

FSCKFIX=yes

in the file
/etc/default/rcS

Check and note last time fs was checked:
sudo tune2fs -l /dev/sda1 | grep "Last checked"

These two options did NOT work

*

*Passing -F (force fsck on reboot) argument to shutdown:
shutdown -rF now

Nope; see: man shutdown.

*Adding the /forcefsck empty file with:
touch /forcefsck

These scripts seem to use this:
/etc/init.d/checkfs.sh
/etc/init.d/checkroot.sh

did NOT work on reboot, but the file was deleted.
Verified by:
sudo tune2fs -l /dev/sda1 | grep "Last checked"
sudo less /var/log/fsck/checkfs
sudo less /var/log/fsck/checkroot

These seem to be the logs for the init scripts.
I repeat, these two options did NOT work!

Both of these methods DID work

*

*systemd-fsck kernel boot switches
Editing the main grub configuration file:
sudoedit /etc/default/grub

GRUB_CMDLINE_LINUX="fsck.mode=force"

sudo update-grub
sudo reboot

This did do a file system check as verified with:
sudo tune2fs -l /dev/sda1 | grep "Last checked"

Note: This DID a check, but to force a fix too, you need to specify fsck.repair="preen", or fsck.repair="yes".

*Using tune2fs to set the number of file system mounts before doing a fsck, man tune2fs

tune2fs' info is kept in the file system superblock

-c switch sets the number of times to mount the fs before checking the fs.
sudo tune2fs -c 1 /dev/sda1

Verify with:
sudo tune2fs -l /dev/sda1

This DID work as verified with:
sudo tune2fs -l /dev/sda1 | grep "Last checked"

Summary
To force a fsck on every boot on Linux Mint 18.x, use either tune2fs, or fsck.mode=force, with optional fsck.repair=preen / fsck.repair=yes, the kernel command line switches.


text:
Q: Webpack can not use __dirname? I am trying to use node-postgres to hook my app up to Postgres. The code I use is:
import React from 'react';
import pg from 'pg';
import fs from 'fs';
var cn = {
  host: 'localhost', // server name or IP address;
  port: 5432,
  database: 'my_db',
  user: 'myname',
  password: 'mypass'
};

and it produces the error:
index.js:5 Uncaught ReferenceError: __dirname is not defined
up  @ index.js:5
__webpack_require__ @ bootstrap 539ecc7…:19
(anonymous function)  @ client.js:4
__webpack_require__ @ bootstrap 539ecc7…:19
(anonymous function)  @ index.js:3
console.EventEmitter._events  @ index.js:81
__webpack_require__ @ bootstrap 539ecc7…:19
(anonymous function)  @ app.js:26957
__webpack_require__ @ bootstrap 539ecc7…:19
content @ bootstrap 539ecc7…:39
__webpack_require__ @ bootstrap 539ecc7…:19
(anonymous function)  @ bootstrap 539ecc7…:39
(anonymous function)  @ bootstrap 539ecc7…:39
webpackUniversalModuleDefinition  @ universalModuleDefinition:7
(anonymous function)  @ universalModuleDefinition:10

The path on index.js provided in the console is webpack:///./~/pg/~/pgpass/lib/index.js:5
I tried @Renzo Poddighe solution at how to write file with node webkit js? but I still get the same error. I think it may have something to do with the discussions at https://github.com/nwjs/nw.js/wiki/Differences-of-JavaScript-contexts#resolving-relative-paths-to-other-scripts and https://github.com/nwjs/nw.js/issues/264. They say that
// __dirname is not defined in webkit context, this is only node.js thing
console.log(__dirname); // undefined

and
__dirname works in Node.js modules, i.e. in JavaScript code that was called with require().
__dirname doesn't work only in WebKit scripts, i.e. in JavaScript code that was called with HTML , or jQuery's $.getScript(), or any other similar method.
Any ideas? Let me know what other information I need to include.
edit
I think my target is
var config = {
  entry: { app: './src/index.jsx'},
  output: {
     libraryTarget: 'umd',
     path: path.join(__dirname, 'dist'),
     filename: '[name].js'
  }, ...

My webpack.config.js looks like:
...
  node: {
    console: true,
    __dirname: true,
    dns: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty'
  }
...

A: In that case, add this to your webpack config:
{
  node: {
    __dirname: true
  }
}

This will tell webpack to replace __dirname instances with the path of the module. This path relative to context

A: Try this:
    node: { __dirname: "mock" }

Check this reference out


text:
Q: Minimal subfield of two fields Suppose $\Bbb F \subset \Bbb K_1 , \Bbb K_2 \subset \Omega$ all fields.
Denote by $\Bbb K_1\Bbb K_2$ the minimal field containing both $\Bbb K_1$ and $\Bbb K_2$
I need to prove that if $[\Bbb K_1:\Bbb F]$ and $[\Bbb K_2:\Bbb F]$ both finite then $[\Bbb K_1 \Bbb K_2 : \Bbb F]\le [\Bbb K_1:\Bbb F][\Bbb K_2:\Bbb F]$.
Not sure how to do it, hints/partial solution would be great.
Thanks !

A: Hint:
If $\;\{v_1,...,v_n\}\,,\,\,\{w_1,...,w_m\}\;$ are basis of $\;\Bbb K_1/\Bbb F\,,\,\,\Bbb K_2/\Bbb F\;$ resp., then
$$\;\Bbb K_1\Bbb K_2=\text{Span}_{\Bbb F}\,\{\,v_iw_j\}_{1\le i\le n,\,1\le j\le m}\;$$


text:
Q: If $\mu_i \xrightarrow{w} \mu \Rightarrow \int_X f d\mu_i \to \int_X f d\mu$ for all convergent sequences, does it imply $f$ is continuous? Let $(X,d)$ be a metric space and $\mu, \mu_i $ be Borel probability measures on $X$ for $i \in \Bbb N$.
If for all weakly convergent sequences $\mu_i \xrightarrow{w} \mu$ in $\Delta(X)$ we have $\int_X f d\mu_i \to \int_X f d\mu$, is it necessarily the case that $f$ is continuous?

A: Let $x \in X$ arbitrary. For every sequence $(x_n)_{n \in \mathbb{N}}$ in $X$ converging to $x$, we have
$$\delta_{x_n} \xrightarrow{w} \delta_x,$$
where $\delta_y$ is the point mass in $y$. The assumption now implies that
$$f(x_n) = \int_X f d\delta_{x_n} \to \int_X f d\delta_x = f(x),$$
and that means $f$ is sequentially continuous in $x$. $x$ was arbitrary, so $f$ is sequentially continuous. For metric spaces, sequential continuity is equivalent to continuity, hence $f$ is continuous.


text:
Q: @staticmethod used in qiksit hybrid neural network I am very new to python. I was studing some code from qiskit - https://qiskit.org/textbook/ch-machine-learning/machine-learning-qiskit-pytorch.html.
I have a lot of doubt in the below code. After doing some study of neural network, I can intrepret that below code is for back progpogation.  But above the function backward, the @staticmethod is written. I did some study and came to know that these are decorators. They run before the backward function is executed. Not sure what exactly this function do. I studied the neural network code for classical computer. They donot add this. I would be really if someone can explain me its use.
@staticmethod
    def backward(ctx, grad_output):
        """ Backward pass computation """
        input, expectation_z = ctx.saved_tensors
        input_list = np.array(input.tolist())

        shift_right = input_list + np.ones(input_list.shape) * ctx.shift
        shift_left = input_list - np.ones(input_list.shape) * ctx.shift

        gradients = []
        for i in range(len(input_list)):
            expectation_right = ctx.quantum_circuit.run(shift_right[i])
            expectation_left  = ctx.quantum_circuit.run(shift_left[i])

            gradient = torch.tensor([expectation_right]) - torch.tensor([expectation_left])
            gradients.append(gradient)
        gradients = np.array([gradients]).T
        return torch.tensor([gradients]).float() * grad_output.float(), None, None

A: The @staticmethod decorator indicates that this method is static, which means that it can be run without being attached to a particular instance of the class.
It simply means that you can consider it as a normal function, the only thing to remember is that you will call it with Class.backward(ctx, grad_output), with Class being the name of the class this method is declared in.
For instance, consider the following code:
class MyClass:
    def my_method(self, a):
        print(a)

    @staticmethod
    def my_second_method(a):
        print(a)

    def my_third_method(a):
        print(a)

my_instance = MyClass()
my_instance.my_method(2) # Prints 2
MyClass.my_second_method(3) # Prints 3
my_instance.my_third_method(4) # Error

When callig a method in Python, a reference to the calling object is passed as the first argument, this is the self in the first call. When a @staticmethod decorator is used, this is not the case, and the method should be called using the class name.
As a proof, the last line throws an error:  my_third_method expects a single argument, but is being passed my_instance as a first_argument and 4 as a second argument.
A better explanation of this decorator can be found on Software Engineering SE and on StackOverflow directly.


text:
Q: Add editor tag [badge:...]
Possible Duplicate:
Add badges to Markdown?

We already have editor tag [tag:] to insert tags to editted text: some-tag
For some posts here on Meta it would be nice and useful to have editor tag like [bronze-badge:Benefactor]
or [gold-badge:Unsung hero], that would draw the badge in the edited text.

A: Well I would not use [color-badge:etc...] but it would be noce to quickly link badges in some way.
Maybe a dropdown or something in the meta editor?


text:
Q: MySQL - Storing variables inside CREATE FUNCTION I'm trying to figure out how to store variables inside a function in mySQL. I am trying to create a function that capitalizes a field name. Creating a function works if I don't create variables. The problem is this is difficult to read, and is easy to make mistakes with.
CREATE FUNCTION capitalize(string TEXT)
    RETURNS TEXT
    RETURN CONCAT(UPPER(LEFT(string,1)), LOWER(RIGHT(string, LENGTH(string) - 1)));

When I try to add variables using the DECLARE and SET keywords, it no longer works.
CREATE FUNCTION capitalize(string TEXT)
    RETURNS TEXT
    DECLARE first_letter TEXT;
    DECLARE last_letters TEXT;
    SET first_letter = UPPER(LEFT(string,1));
    SET last_letters = LOWER(RIGHT(string, LENGTH(string) - 1));
    RETURN CONCAT(first_letter, last_letters);

I get this error message

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 4

I've fiddled around with it, removing semicolons, and double/triple checking parentheses. I've fiddled with BEGIN and END statements but nothing seems to work at all.
I have searched extensively on this topic but cannot figure out where the problem lies.

A: The body of a CREATE FUNCTION can consist of only a single statement, which is why the first version works and the second doesn't. Fortunately, that single statement can be a compound statement enclosed in a BEGIN ... END block.
You need to enclose the function body in a BEGIN ... END block to allow MySQL to see it as a single statement; you'll also perhaps need to precede and follow it with DELIMITER statements (depending on your client, as Mr. Berkowski points out):
DELIMITER //

CREATE FUNCTION capitalize(string TEXT)
    RETURNS TEXT
    BEGIN
      DECLARE first_letter TEXT;
      DECLARE last_letters TEXT;
      SET first_letter = UPPER(LEFT(string,1));
      SET last_letters = LOWER(RIGHT(string, LENGTH(string) - 1));
      RETURN CONCAT(first_letter, last_letters);
    END; //

DELIMITER ;

(Note especially the space between the last DELIMITER and the semicolon.)


text:
Q: Using a subquery in a where clause to find the second smallest value I'm trying to find the second smallest value for a list to put it into SSRS as a way to highlight that value. This issue is there are multiple minimum values for a given element. The data is presented such that there is an overarching group A that encompasses smaller groups B and I am wanting the second smallest value for each of the smaller groups.
I have a query set up right now that uses a subquery in the where clause to exclude the minimum value from the search so that the second smallest value will be considered the new minimum value. This seemed to work but the subquery only rules out the minimum value for the larger A group, which may or may not be the minimum value for each B group. Here is my query:
Select
BPosition,
Min(Value) as SecondMinimum
From Table
Where Value > (Select
               Min(Value)
               From Table
               Where APosition = @AName)
      and APosition = @AName
Group By BPosition

I was expecting a list of the second smallest values for each B group, but it is pulling in the smallest value in each B group that is greater than the smallest value of the A group. This is right for the one B group that contains the true smallest value but incorrect for the others.

A: If you want the second largest value, use dense_rank():
Select distinct BPosition, Value as SecondMinimum
From (select t.*,
             dense_rank() over (partition by Aposition, Bposition order by value) as seqnum
      from table
     ) t
where seqnum = 2;


text:
Q: limit resolution with arcsin function This o sth exercise:
$\lim_{x\to 1} {\frac{2\arcsin(x)-\pi}{x-1}}$
Considerint $x\to 1^+$ My first move was try to substitute $x-1$ with $y$, obtaining:
$\lim_{y\to 0^+} {\frac{2\arcsin(y+1)-\pi}{y}}$
and using the sum formula for $\arcsin(a+b)$ I haven't gained nothig usefull, the same trying to divide factors by $\arcsin(x)$...
It's the last exercise i've to do and i'm stucked, any suggestion?
I've to solve this limit with only algebric passages

A: Let
$$f(x)=2\arcsin x$$
then
$$\lim_{x\to 1} \frac{2\arcsin(x)-\pi}{x-1}=\lim_{x\to1}\frac{f(x)-f(1)}{x-1}=f'(1)=\frac{2}{\sqrt{1-x^2}}\bigg|_{x\to1}=\infty$$

A: $x=\sin\left(y+\frac{\pi}{2}\right)\quad\Rightarrow\quad y=\arcsin(x)-\frac{\pi}{2}$
$$\lim_{x\to 1} {\frac{2\arcsin(x)-\pi}{x-1}}=\lim_{y\to 0} {\frac{2y}{\sin\left(y+\frac{\pi}{2}\right)-1}}=\lim_{y\to 0} {\frac{2y}{\cos(y)-1}}=\lim_{y\to 0} {\frac{2}{\frac{\cos\left(y\right)-1}{y}}}=\infty\ .$$


text:
Q: prevent application from closing before all threads are done So this is what I've got:
extern crate time;

use std::thread;

fn main() {

    let start = time::get_time();
    println!("Starting application");
    do_stuff();
    println!("Total {:?}", time::get_time() - start);

}

fn do_stuff() {

    for i in 0..4i32 {
        thread::spawn(move || {
            thread::sleep_ms(1);
            println!("doing stuff {:?}", i);
        });
    }

}

For some reason that I am not familiar with application doesn't wait for the threads in function do_stuff() to finish and closes. So this is the output I get:
Starting application
Total Duration { secs: 0, nanos: 808482 }

Instead of something like
Starting application
doing stuff 1
doing stuff 2
doing stuff 3
doing stuff 4
Total Duration { secs: 0, nanos: 808482 }

How do I make the application to wait for the threads to finish even when threads don't return anything?

A: The spawn function returns a JoinHandle. You can collect all the handles in a vector and call join on them:
extern crate time;

use std::thread;

fn main() {

    let start = time::get_time();
    println!("Starting application");
    do_stuff();
    println!("Total {:?}", time::get_time() - start);
}

fn do_stuff() {
    let handles: Vec<_> = (0..4).map(|i| {
        thread::spawn(move || {
            thread::sleep_ms(1);
            println!("doing stuff {:?}", i);
        })
    }).collect();

    for h in handles {
        h.join().unwrap();
    }
}


text:
Q: Cassandra inserts timestamp in UTC time I have json logs with timestamp(UTC TIME) in it. I map keys and values to Cassandra Table keys and Insert the record. However, Cassandra converts the already UTC timestamps to UTC again by subtracting 5 hours from the timestamp. The timezone here is (GMT + 5).
cqlsh> INSERT INTO myTable (id,time) VAlUES (abc123, 2018-01-12T12:32:31);

Now the time is already UTC time and its still inserts a timestamp of 5 hours ago.
How can I resolve this?

A: If you're using cqlsh to insert data, then you can specify default timezone in the cqlshrc file using the timezone parameter (see default cqlshrc as example).
If you insert dates programmatically, then you need to convert your time into corresponding type matching to the Cassandra's timestamp type (java.util.Date for Java, for example).  In your case change could be simple - just append Z to timestamp string as pointed by Ralf


text:
Q: CSS background-image reference in javascript using codigniter I am working in codeigniter my folder structure something like that.
application
assets
    css
    js
    img
system
index.php

I've to make my bootstrap carousel full window height.
my approach is that make my div.item layer to full height of window using jquery.
then remove image from div.item layer and set this image as div.item background image using jquery.
here is my jquery code.
$('.carousel').find('.item img').each(function () {
    var $this = $(this),
        src = $(this).attr('src');
        imageName = 'url(assets/img/' + $(this).attr('src').split('/')[6]+')';
    $this.parent().css('background-image',imageName);
    $this.remove();
});

my reference in not working please let me what's wrong with my code.

A: your should use full reference. Try this.
$('.carousel').find('.item img').each(function () {
    var $this = $(this),
    src = $this.attr('src');
    $this.parent().css('background-image',src);
    $this.remove();
});