What is a reasonable maintenance schedule for Windows PCs?

Question: I am in charge of maintaining around 25 PCs with various versions of Windows (Vista, 7, 8).
I was thinking something along the following lines:

Every 4–6 months:

Take an image of the system partition so that installed programs with their various license requirements can be restored easily if a hard disk fails. (I am thinking of Clonezilla for this.)
Physically clean the machine, get rid of dust on the fans etc.

Every 2 months:

Do a software check on things like backups still running ok, anti-virus up to date, Windows updating itself, firewall set up correctly.

Every day:

Automatic backups of things like emails and documents.

What kind of schedule do you recommend?
What kind of software tools to use? Ideally I would like to automate as much of this as possible.
What other things should I be doing?
UPDATE:
Thanks for all the great answers so far, the advice to not do backups/images of individual machines doesn't really work in my case.
The licensing costs would be prohibitive, since there are at least 5 different software configurations for the different roles in the company -- finance, sales, management, production (3 types here alone) and having licenses for everyone for everything wouldn't make sense.
Also we have to keep some old versions of software for compatibility with some of our customers - the installation disks (with the license keys) have been lost or buried before my time.
Comment: Whatever schedule you use, if you have a spare PC, try restoring one of your backups to it.  Go through the sequence at least once.  You'd be surprised at the number of sys admins who have been backing up systems for years and don't know how to restore them.  Even worse - there is only one tape drive and it only lives on the backup system.
Comment: @Loopo - I'm not suggesting you install every application on every computer. I'm suggesting that you should create automated software installations to apply to "generic" images. The more specific images you have to maintain the worse off you're going to be, in terms of sinking time into image maintenance. Insofar as the old software you no longer have media or keys for: You're going to be in trouble when you need to replace machines. You can't keep that software running forever. You'd do well to start figuring out a mitigation strategy now before it bites you.
Comment: ... and while it's easy to say "this deployment stuff don't apply to me, I just support a small business with 20 or 30 machines", I would suggest that if anything, fast deployment of a machine might even be *more* important to a small business where you might not have lots of 'spare' machines that can easily be put on someone's desk the moment they report a fault.
Comment: This is, as others have suggested, a perfectly simple problem that has already been solved. There are plenty of methods for trivially creating a simple to deploy baseline OS image, possibly with one or two apps on it that you use everywhere and then adding (or for that matter removing) packages as an automated part of the deployment process to account for machines having different roles. It might take a day or two to set up and test but the time will be paid back when it takes 40 mins instead of half a day to deploy a new machine.
Answer: Here are some "pages" out of my personal "operations manual":

All user data is saved on servers, period. It might be replicated to client computers via functionality like "Offline Files" (for laptop computers, particularly) and Outlook's "Cached Exchange Mode", but there is no primary storage of data on client computers, ever.
No recurring backups of client computers are performed. No data is stored there. Users are instructed (ideally by corporate policy documents) to save data in approved areas and that anything saved outside those areas is not backed-up.
Software should be automatically installed via an automated mechanism wherever economically feasible. (The "break even" has been, for purposes of my Customers, a program being installed on five (5) or more computers. If it goes on fewer I'll probably just do the installation manually.)  The Active Directory security group membership and location (OU) are sufficient to determine a machine's software load.
I have taken an image of a client computer being used in a very business-critical role now and again, but in general the majority of client computers I work with are built-up from their factory load and automated software installs. Where I've seen it done I've felt that maintaining a "library" of disk images of client computers has been cumbersome and error-prone.
Since Windows 7 added software RAID-1 to the "Professional" OS I have made use of that, increasingly, for client computers that are in more "mission-critical" roles. Windows software RAID is much more forgiving and workable than "motherboard RAID" (which is nothing but trouble).
Antivirus software should use a "management console" that can provide centralized, automated alerting for fault or anomaly conditions. This often means buying "enterprise"-oriented antivirus software.
Computer environment settings (firewall, security options, etc) are pushed out via Group Policy. (Anything that can be done with Group Policy is done that way.)
No maintenance of the hardware (fans, etc) is done except when the environment is harsh, and even then only in a reactive manner. Hardware has gotten pretty solid in the last 10-15 years.
Updates are installed via WSUS. Compliance is tracked in WSUS and, if the environment warrants (for PCI compliance, for example) with whatever auditing tool is financially appropriate. (SCCM is nice, for example, but not always appropriate from a cost perspective.)

Edit (now that I have a couple more minutes to write):

My definition of "user data" includes user profiles. I use Folder Redirection to get the big folders out of the profile. I generally redirect AppData, which seems to be heavily discouraged throughout the industry (because dimwit software developers make assumptions about the AppData folder being local that may not be true... >cough< Apple >cough< iTunes >cough<).
Users never have "Administrator" rights on client computers for their day-to-day user accounts. Dealing with small privately-held businesses, as I do, can often require some finesse in explaining to the owner why their user account doesn't have Administrator rights. (With the advent of scary-as-heck malware, though, making this argument has become a lot easier. Score one for malware, I guess...)  I do create secondary local Administrator accounts for users who are technically competent and who have a legitimate need on a case-by-case basis (after consulting with my contact and weighing the pros and cons). Making this one change drastically decreases "software maintenance". If you do nothing else, do this.

Some of the goals of this methodology are:

Allow for a user to "hot desk" if they have major failure (smoke rolling out of the computer, etc). All their software might not be available (because of licensing limitations that limit installed seats, etc), but they should have basic functionality. (I support a reasonable number of client computers throughout my Customer-base. I need a simple PC failure to be a non-emergency event or I can't scale to any significant number of Customers.)
Reduces most troubleshooting for user issues simply to determining if the problem is user profile-specific or machine-specific. User profile-specific issues are resolved either by restoring the profile from a known-good backup or, in drastic situations, starting with a clean profile. Machine-specific problems are resolved by bringing out a spare machine or wiping / re-imaging the failed computer.
There is no data loss impact when the eventual failure of client computer hard disk drives occurs.
Computer replacement (and keeping the Customer sticking to a computer lifecycle plan) is easy.
Answer: Keeping a separate image of each machine sounds like a very labor and cost intensive plan.  How are you going to store all those images and keep them matched to each machine.  Will you even be able to restore them properly when the old hardware dies and is replaced with new, different hardware?
I don't backup end user machines.  All their important data is stored on our file servers, exchange and sharepoint.  Each user has their own personal network share as well as departmental ones.  We educate all the users not to store data on their local machine.
All the machines are imaged with the software they need when we deploy them.  Microsoft offers tools to do this for free, like Microsoft Deployment Toolkit and Windows Deployment Services.  Or you can get System Center Configuration Manager which also monitors the health of the machines, allowing you to ensure updates are applied and unauthorized software isn't installed.  All the machines are set by domain policy to automatically apply updates from our WSUS server.
When a machine dies or gets a virus, we just replace/repair the hardware and reimage it.  The new machine already has all the software they need, their network drives get automatically mapped by group policy as soon as they login.  Printers are automatically installed, etc.  So the machines are basically disposable.
For the most part I don't do ANY maintenance to the end user machines unless their is a problem with them.  System center helps identify problems that the users don't report.  WSUS and our antivirus software give reports on which machines are missing updates.  When there IS a problem with a machine, it gets dusted out and hardware checked over while we repair it.
Comment: WDS saved my company countless hours! The previous guy did the clonezilla thing, and it took at least 4 hours to refresh a system. Drivers were a nightmare, and every ran horribly. Now with WDS, I can do a full system prep in 45 minutes with all software installed and registered. I ended up replacing the other guy, he was let go.
Answer: Rethink your strategy. Don't backup client devices.
Spend your time doing the following:

Create an OS image that can be deployed automatically over the network with WDS/MDT. When a computer gets hosed, just reimage it. This image should have all of your software/configuration in it.
Centralize your user data on servers. This means having a proper mail server and not using POP3 with individual user backups. Just backup the mail server and you're done. This also means centralizing user files on file servers. You can use Group Policy to transparently redirect the desktop, documents, appdata, and other folders to this file server. You can use offline files to sync this data locally so users can still work remotely. Now, you have one machine to back up and not 25.
Centralize your patching. Use WSUS so that you can generate reports on what clients have which patches. Then, you only need to "spot check" machines that aren't compliant. You should do this every month after Patch Tuesday.

As for physical maintenance, unless you're in an exceptionally filthy environment (factory floor, inside of a vacuum cleaner, etc) don't open computers and dust/vacuum them out. In some instances, this can potentially void the warranty. In other cases, it's just a waste of time. If you must do this to sleep soundly at night, do it every few years.
Comment: Not sure what you're talking about. OS images have been hardware independent since Vista. A single image can be used across any number of hardware models.
Comment: 25 computers with 3 OS versions suggests adhoc computer procurement.  I suspect Loopo probably has a mess of different computer models and would end up having to create almost as many clean images as individual computers.  Under those conditions prepping images for all the existing machines in advance seems like a lot of work that will mostly go unused.  Save clean images for any new systems or old ones that need fresh installs; beyond that is probably more time than it's worth for non mission critical machines.
Comment: You can use MDT which is a glorified file share. I think you're overestimating the work and underestimating the benefit. But, to each their own.
Comment: @MDMarra, methinks it be depending on what he's using to backup the image, I'm not sure if Clonezilla will handle hardware independent images, using imagex (or now DISM) yes, but who knows what kind of format clonezilla will do it in. With that said, not only the creation and maintenance of images would be more of a hassle than a help in such a small environment, but with 25 computers, I can't imagine you have more servers to set up the infrastructure for a decent imaging system. Yes, maybe you can install the WDS role on your exchange server too, but still, no.
Answer: (Wow-- I've never added a second answer to a question before... This is surreal!)
Everything else that I said in my other answer applies, pretty much, except that I'm going to go out on a limb and suggest client computer backup. (Yikes!)
The Client Computer Backup functionality in Windows Server 2012 R2 Essentials might just be up your alley. Functionally it's a block-level deduplicated backup store that sits on a server computer, combined with a client application that performs the backups and uploads data to the server. It's actually pretty slick, as solutions like it go. There is a bare-metal restore ISO image that will allow you to restore a machine from a empty hard disk drive. (I've used it before and it works rather well.)
Windows Server 2012 R2 Essentials requires no Client Access Licenses (CALs) for up to 25 clients. If you needed more clients than than (which it sounds like you might) you should look at licensing Windows Server 2012 R2 Standard, purchasing the necessary CALs, and adding the Essentials Experience feature to the server.
Planning for disk utilization is going to be difficult because you're not going to know how much "win" you're going to get from the deduplication. Your environment is going to determine how well that will work so there's no guideline to give you here.
For the cost of some software and a small server computer you could cobble together a pretty good PC backup solution. While I am somewhat "morally opposed" to the idea of client computer backups I think it could be a viable strategy in your environment given the amount of work it would take to transition it into a more "normal" corporate Windows environment.
If you perform backups of the server computer itself (which you should, obviously) you can also get an effective off-site backup of all the client computers using this tool. That would certainly be an attractive add-on, given that right now a fire or flood in your office would probably represent complete destruction of all your company's data.
Comment: Thanks for this second answer. Pity I can only accept one of them. I will accept your other answer as it applies more generally.
Answer: I don't use windows, but a lot of the basics carry over, and the main thing that you should try to do is set up a system that will alert you if a part of it fails.
For instance, if I was backing up a folder to another computer every day, I might have a separate script running on the destination to check the latest timestamp, and if no file has been modified in the past day it sends an email to say the back is no longer running. This is just a vague example, but in general you can't remember to do everything yourself - murphys law says the one thing you forget will usually be the wrong thing that goes wrong, so it's best to have some sort of automation to detect failures.
Similarly, set up an automatic testing suite for system stuff, like antivirus version, firewall functionality, etc. I'd back up any important files on an hourly basis if at all possibly, daily as a minimum, but it depends on how fault-tolerant your business is - how much will losing a day's worth of emails cost you?
If you're worried about hard disk failure, look into RAID. Backups are for catastrophic failures (flood, fire, etc) and user-error (help, I deleted the wrong file!). Raid is for disk failure.
Comment: RAID on desktop class systems often causes more problems than it solves, causing data loss when the controller or motherboard fail and identical replacements aren't available.  Sometimes even WHEN identical replacements are available.
Comment: I've been really happy with Windows software RAID-1. Since becoming available for the "professional" class OS in Windows 7 (or Vista, I can't remember-- and never used Vista in Customer sites anyway) I've been happy to use it for machines that need some fault tolerance for hard disk drive failure. I certainly wouldn't deploy it to just any ol' client PC, but for more critical machines I like the feature. OTOH, "motherboard RAID" is nothing more than a device used to destroy data and I wouldn't wish it on anybody.


How to create a custom stack in sliver appear in flutter?

Question: Hi Everyone I am creating a profile page for a flutter app.
The SliverAppBar needs to show the below view when in the expanded state:

And below view when the user scrolls the silver list.

As you see this is a custom stack that I can create.
I don't know how to do it in slivers in a flutter.
Any links would also be highly appreciated to learn in-depth about flutter and slivers especially.
Code for the collapsed stack:
             Stack(
                  alignment: Alignment.topRight,
                  children: <Widget>[
                    Container(
                        margin: EdgeInsets.only(top: 12),
                        width: 2000,
                        height: 80,
                        decoration: BoxDecoration(boxShadow: [
                          BoxShadow(blurRadius: 5.0, color: Colors.black87)
                        ])),
                    Container(
                      margin: EdgeInsets.only(right: 20, top: 5),
                      decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          boxShadow: [
                            BoxShadow(blurRadius: 5.0, color: Colors.black87)
                          ],
                          border: Border.all(color: Colors.cyan, width: 3.0)),
                      child: CircleAvatar(
                        backgroundImage: AssetImage(
                            "assets/images/food/avocado-f.jpg"),

                        radius: 50,
                      ),
                    )
                  ],
                ),

Answer: You should use SliverPersistentHeader and create your own SliverPersistentHeaderDelegate.
In the build method you add your Stack view and you can use Transform or SizedBox to scale and transform the circle depending on the height of the header.
There is a nice tutorial that explains how to use this widget
https://medium.com/flutter-community/how-to-code-a-dynamic-header-in-flutter-e171ec2231bf


Is possible for fluent-ffmpeg to take WebRTC stream as input?

Question: I am exploring fluent-ffmpeg and saw that in the Shell version (ffmpeg) is possible to use a RTMP streaming as parameter and take a frame-by-frame collection
I wanted to know if that is possible in fluent-ffmpeg and if it can be made with a WebRTC MediaStream instead of a RTMP url
Thanks in advance
Comment: do you mean taking snapshots from the streaming rtmp server
Comment: Yes, just with media stream, media recorder and ffmpeg
Answer: Nope, FFMPEG doesn't supports WebRTC for now.
You can use GStreamer, it supports WebRTC. But there is no node.js bindings for GStreamer for now.


Why bzr branch keep on being killed?

Question: I am trying to branch the emacs trunk:
$ mkdir emacs
$ bzr init-repo emacs
Shared repository with trees (format: 2a)
Location:
  shared repository: emacs
$ bzr branch bzr://bzr.savannah.gnu.org/emacs/trunk trunk
Killed39KB  2666KB/s | Fetching revisions:Inserting stream

After launching the bzr branch command, the download begins, after a while it is killed and the trunk directory is empty. Relaunching the same command does not help, it seems it is not able to recover for intermediate states. As a consequence I must remove the directory and re-start from scratch which does not help in making the branching go further.
Possible issue: my internet connection is not great but it does seems to be the cause. I tried from various location, as well as from a remote hosted VPS: same behavior!
I may try multiple time in a row (removing the folder), it is impossible for it to complete.
How does people branch the emacs trunk repository? Is that a tool(bzr) or repository server issue? Do you think it is anyway related to my setup? Bad command?
Comment: What about RAM consumption?  Perhaps it allocates and uses too much.
Comment: @MischaArefiev You're right. From /var/log/syslog : ```Feb 22 12:43:11 xxxxxx kernel: [584519.697873] OOM killed process 21740 (bzr) vm:676940kB, rss:513028kB, swap:88164kB``` . That's just a shame. I will see how do deal with that. Anyway feel free to post a real answer I'll accept it as a gratification!! :-)
Answer: Perhaps the process tries to allocate and use too much RAM, and is killed by the kernel after the memory pool is exhausted (you can check dmesg for such message).  Googling for «bzr killed out of memory» yields a number of bug reports:

https://bugs.launchpad.net/bzr/+bug/488141
https://bugs.launchpad.net/bzr/+bug/456077

I guess you can try a machine with more RAM as a workaround, or, if it is a repository format issue (such as mentioned in the bug reports above) perform the steps suggested in comments to these reports.

Why bzr branch keep on being killed?


Issue to open dialog: Yii

Question: I have used ajaxSubmitButton in my form.On click of button i am trying to open dialog When i click the button ,the dialog opens and it displays entire code written for that form . How to resolve this?
my code for button is :

    <?=CHtml::ajaxSubmitButton('Mail to Client', Yii::app()->createUrl('reply/composeMail'),
        array('type'=>'POST',
              'data'=> 'js:{"data1":callData()}',
            //'success' => 'function(response){afterSubmitForm(response);}'
              'success'=>'js:function(string){ alert(string);$.fn.yiiGridView.update("my-grid"); }'
        ),

        array('class' => 'btn btn-primary'));
    ?>

my controller code:

public function actionComposeMail()
{
if(Yii::app()->request->isAjaxRequest){
    print_r($_POST['data1']);
        if(isset($_POST['data1'])){
            $model=new Reply;
            $model->scenario = 'compose';

            EQuickDlgs::render('_compose',array(
            'model'=>$model,
            ));
            }else{
            echo "Please select row to Mail.";
        }
    }
    else
    {
        echo "The request is invalid.";
    }
}

my dialog form code is:

<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'reply-form',
    'enableAjaxValidation'=>true,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
 )); ?>

Fields with * are required.For multiple recipients please seperate by comma

<?php echo $form->errorSummary($model); ?>

    <?php echo $form->labelEx($model,'email_from'); ?>
    <?php echo $form->textField($model,'email_from',array('size'=>50,'maxlength'=>50,'readonly'=>'readonly')); ?>
    <?php echo $form->error($model,'email_from'); ?>

    <?php echo $form->labelEx($model,'email_to'); ?>
    <?php echo $form->textField($model,'email_to',array('size'=>60,'maxlength'=>150)); ?>
    <?php echo $form->error($model,'email_to'); ?>

    <?php echo $form->labelEx($model,'email_cc'); ?>
    <?php echo $form->textField($model,'email_cc',array('size'=>60,'maxlength'=>250)); ?>
    <?php echo $form->error($model,'email_cc'); ?>

    <?php echo $form->labelEx($model,'subject'); ?>
    <?php echo $form->textField($model,'subject',array('size'=>60,'maxlength'=>250)); ?>
    <?php echo $form->error($model,'subject'); ?>

    <?php echo $form->labelEx($model,'message'); ?>
    <?php echo $form->textArea($model,'message',array('rows'=>6, 'cols'=>50)); ?>
    <?php echo $form->error($model,'message'); ?>

    <?php echo CHtml::submitButton($model->isNewRecord ? 'Send' :         'Send',array('class' => 'btn')); ?>

<?php $this->endWidget(); ?>

Image of dialog
Answer: You must use renderPartial() instead of render() and try to call Yii::app()->end() at the end in your mail form view
public function actionComposeMail()
{
if(Yii::app()->request->isAjaxRequest){
    print_r($_POST['data1']);
        if(isset($_POST['data1'])){
            $model=new Reply;
            $model->scenario = 'compose';

            $this->renderPartial('_compose',array(
            'model'=>$model,
            ));
            }else{
            echo "Please select row to Mail.";
        }
    }
    else
    {
        echo "The request is invalid.";
    }
}

Comment: see updated code... Forgot to use `$this` while renderPartial

Issue to open dialog: Yii


Imagens com uri vindo da API React Native

Question: No banco de dados eu guardo o path da imagem junto com as outras informações da postagem, ai na pagina que quero que apareça as imagem uso um flatlist listando as postagem e mostrando a sua imagem se esse post tiver:
Flatlist mostrando as postagem que tem no banco de dados
<FlatList
      data={postList}
      keyExtractor={item => item.id.toString()}
        renderItem={({item}) => {
          return(

            <View style={styles.postagemRed}>

                <View style={styles.postCima}>

                  <Text style={styles.iconPost}></Text>
                  <View style={styles.separador}>
                    <View style={styles.nomeDate}>
                      <Text style={styles.postText}>{item.nome}</Text>
                      <Text style={[styles.postText, styles.dateText]}>
                        { // tratamento da variável de data
                          item.data.substring(8,10)+'/'+ // dia
                          item.data.substring(5,7) +'/'+ // mes
                          item.data.substring(0,4)       // ano
                        }
                      </Text>
                    </View>
                    <View>
                      <Text style={[styles.postText, styles.cargoText]} >{item.identificacao}</Text>
                    </View>
                  </View>
                </View>

                {item.nomeImage &&

                    //por algum motivo a imagem não aparece
                    <Image style={styles.imagePost}  source={{uri : item.path}} />
                  }

                <TouchableHighlight style={styles.postBaixo}
                underlayColor='#FFFFFF00'
                onPress={() => navigation.navigate('OpenPost', {idPost : item.id })}>
                  <View>

                    <Text numberOfLines={2} ellipsizeMode={'tail'} style={styles.tituloText}>{item.titulo}</Text>
                    <Text style={[styles.tituloText, styles.temaTexto]} >{item.tema}</Text>

                    <View style={styles.corpoPost}>
                      <Text numberOfLines={3} ellipsizeMode={'tail'} style={styles.postTexto}>
                      {item.texto}
                      </Text>
                    </View>
                  </View>
                </TouchableHighlight>

          </View>

          );
        }}
        />

Parte dentro do flatlist que faz a comparação se o post tem imagem e deveria mostrar a imagem (mas aparece so o espaço da imagem no pagina sem nada)
{item.nomeImage &&
<Image style={styles.imagePost}  source={{uri : item.path}} />
}

se eu der um console log nesse "item.path" ele retorna o caminho certo da imagem e se usar um
{item.nomeImage &&
<Image style={styles.imagePost}  source={require("caminho que ta na variavel 'item.path'")} />
}

ele mostra a imagem
exemplo de valor do item.path:
../../img/postagemPhoto/postagemPicture1628191387071.jpg
obs: como faço pra redimensionar a imagem original pro tamanho dessa tag image, desse jeito que ta so mostra a parte central da imagem.
Answer: Olá
Acredito que o resizeMode resolva seu problema, as opções aceitas são: cover, contain, stretch, repeat, center.
O valor padrão é: cover


Joomla Fatal error: Allowed memory size after joomla update

Question: hi i am facing some error in my joomla site after update joomla version to 3.4
Server Info :
Php 5.4.41
MySQL 5.6.17
Apache 2.2.27
Site Name : http://www.yousfis.com/
i enable display error by add these link in configuration.php
ini_set( 'display_errors', true );
error_reporting( E_ALL );
and facing these error in frontend
Warning: preg_replace_callback(): Requires argument 2, '', to be a valid callback in /home/yousfisc/domains/yousfis.com/public_html/libraries/joomla/filter/input.php on line 988
Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 2474379033 bytes) in /home/yousfisc/domains/yousfis.com/public_html/libraries/joomla/filter/input.php on line 995
Please help me to solve this problem
Comment: You get it on all pages or just some? It might be caused by extension not Joomla core. Try to open other pages of your site.
Answer: Dissable eaccelerator from 'Select PHP Version' of your cpanel. Problem solve.
Answer: Your web page is not very big and you don´t have any complicated funcionality on page.
So probably you have this memory issue because you are doing "live" resizing of very large photos.
Try 2 things:

htaacess - add line
php_value memory_limit 32M
** (or 64M or 128M)
Review your images and try to reduce image size wtih some external program (ex. Photoshop)


Conflito entre âncora e rolagem suave

Question: Quando clico na âncora e rolo a página acontece um conflito entre o script de rolagem suave e o de âncora fazendo com que o site role para o topo, já tentei de todo jeito resolver isso e não consigo de forma alguma, se alguém puder me ajudar ficarei extremamente grato
SITE:
https://circuito-da-saude.herokuapp.com/web
SCRIPT SMOOTH SCROLLBAR:

function smooth(){
    new WSmoothScroll(document,120,12);
}

// var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

function WSmoothScroll(target, speed, smooth) {
    if (target == document)
        target = (document.documentElement || document.body.parentNode || document.body) // cross browser support for document scrolling
    var moving = false
    var pos = target.scrollTop
    if(navigator.userAgent.indexOf("Firefox") > -1) {
        target.addEventListener('DOMMouseScroll', scrolled, {passive: false});
    } else {
        if(navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {

        } else {
            target.addEventListener("wheel", scrolled, {passive: false} );
        }
    }

    function scrolled(e) {
        e.preventDefault(); // disable default scrolling

        var delta = normalizeWheelDelta(e)

        pos += -delta * speed
        pos = Math.max(0, Math.min(pos, target.scrollHeight - target.clientHeight)) // limit scrolling

        if (!moving) update()
    }

    function normalizeWheelDelta(e){
        if(e.detail){
            if(e.wheelDelta)
                return e.wheelDelta/e.detail/40 * (e.detail>0 ? 1 : -1) // Opera
            else
                return -e.detail/8 // Firefox 3
        }else
            return e.wheelDelta/360 // IE,Safari,Chrome 120
    }

    function update() {
        moving = true
        var delta = (pos - target.scrollTop) / smooth
        target.scrollTop += delta
        if (Math.abs(delta) > 0.5)
            requestFrame(update)
        else
            moving = false
    }

    var requestFrame = function() { // requestAnimationFrame cross browser
        return (
            window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.oRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            function(func) {
                window.setTimeout(func, 1000 / 50); // 1000 / 50
            }
        );
    }()
}

SCRIPT ÂNCORA:

var links = document.getElementsByClassName('scroll-link');

for (var k = 0; k < links.length; k++) {
    links[k].onclick = scroll;
}

function scroll(e) {
    e.preventDefault();
    var id = this.getAttribute('href').replace('#', '');
    var target = document.getElementById(id).getBoundingClientRect().top;
    animateScroll(target);

    // recolhe menu após smoothScroll

    if(document.querySelector('.sandwich-trigger').classList.contains('sandwich-open') == true) {
        document.querySelector('.menu ul').classList.remove('nav-open');
        document.querySelector('.sandwich-trigger').classList.remove('sandwich-open');
    }

}

function animateScroll(targetHeight) {
    targetHeight = document.body.scrollHeight - window.innerHeight > targetHeight + scrollY ?
        targetHeight : document.body.scrollHeight - window.innerHeight;
    var initialPosition = window.scrollY;
    var SCROLL_DURATION = 40;
    var step_x = Math.PI / SCROLL_DURATION;
    var step_count = 0;
    requestAnimationFrame(step);
    function step() {
        if (step_count < SCROLL_DURATION) {
            requestAnimationFrame(step);
            step_count++;
            window.scrollTo(0, initialPosition + (targetHeight - 70) * 0.25 * Math.pow((1 - Math.cos(step_x * step_count)), 2));
        }
    }
}
Answer: Vou te dar um work around. Hoje é possível fazer ancoras suaves apenas com CSS usando o scroll-behavior, então vc não precisa necessariamente usar um Script para a Ancora Suave, usa o CSS para isso, assim eliminando um dos Scripts e prevenindo esse conflito.
Aqui vc pode ler sobre o scroll-behavior https://developer.mozilla.org/pt-BR/docs/Web/CSS/scroll-behavior
Suporte dos Browsers: https://caniuse.com/#feat=css-scroll-behavior
Segue um exemplo prático de rolagem suave só com CSS, não tem JS aqui.

html {
    overflow-y: scroll;
    scroll-behavior: smooth;
}
body {
 background-image: linear-gradient(to bottom, #00f 0%, #000 100%);
}
html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}
a {
 font-size: 40px;
 color: #fff;
}
#ancoragem {
 height: 100px;
 background-color: red;
 margin-top: 150vh;
    display:block;
    position:relative;
}
ancora

VOLTAR PRO TOPO!
Comment: Olá muito obrigado por disponibilizar seu tempo, a questão da âncora com css é o suporte que ainda é limitado e o público alvo do site é composto por pessoas leigas que usam browsers mais antigos, por isso preciso de uma solução em js que seja crossbrowser
Comment: @RenanHugo sim ainda é algo com pouco suporte, é mais um paliativo caso vc não consiga alguma resposta mais precisa.
Answer: essa linha (linha 9 do script de scroll) transforma a variavel target em um valor boolean
target = (document.documentElement || document.body.parentNode || document.body)
sendo assim na linha 11 target.scrollTop retorna undefined o que causa o comportamento
Comment: Olá Guilherme, comentei essa linha mas o código parou de funcionar... Qual seria a sugestão para sanar esse problema?

Conflito entre âncora e rolagem suave


Dicionario para lista de dicionários

Question: Eu tenho um dicionario como a seguinte:
{'Eva': [4], 'Ana': [53], 'Ada': [12]}

E pretendo transformar numa lista de dicionarios neste tipo :
[{'Nome do Dono': 'Eva', 'Media de idades' : '4'},{'Nome do Dono':'Ana':'Media das Idades':'53'},{'Nome do Dono': 'Ada', 'Media de idades' : '12'}]

Podem ajudar de como obter a lista de dicionarios como pretendo
Answer: Para obter a lista de dicionários faça assim:
dict_1 = {'Eva': [4], 'Ana': [53], 'Ada': [12]}
lista_dict = [{'Media de Idade':idade.pop(), 'Nome do Dono':nome} for nome, idade in dict_1.items()]

Answer: Supondo que você tenha obtido o valor 4,666 a partir da divisão de 28 por 6, você pode usar a função ceil para efetuar o arredondamento:
import math

age_avg = 28 / 6.0 # 4.666666666666667
print age_avg # imprime 4.666666666666667
print math.ceil(age_avg) # imprime 5

Dicionario para lista de dicionários


Site for slice sheaf topos

Question: The fundamental theorem of topos theory states that the slice categories $\mathcal{E}/A$ of a (Grothendieck) topos $\mathcal{E}$ are again (Grothendieck) toposes.
If $\mathcal{E}$ is of the form $\mathrm{Sh}(C, J)$ for some subcanonical site $(C,J)$, then if $A$ is some object of $\mathcal{E}$, can we write $\mathcal{E}/A$ as sheaves on $C/A$ (identifying $C$ with the representable sheaves) with an appropriate choice of topology on $C/A$?
Answer: Yes, we can! For reference requests like this I'd always turn to the nLab. The statement you're looking for is on theiry entry about over-toposes, in the version for presheaves. They reference page 194 of MacLane/Moerdijk for the version for sheaves.

Site for slice sheaf topos


user_register_form not give pre filled form

Question: I have created a module for user listing. when I edit any user then call drupal_get_form('user_register_form', $existing_account);, its not give me form with user data.
I used Profile2 module to add some custom filed in user registration page. Now in admin , I need those custom fields with user data in it.
for that I used drupal_get_form('user_register_form', $existing_account); function where $existing_account = user_load($uid, $reset = TRUE);
<code>  function mymodule_create_subscriber() {
  ....

  $existing_account = user_load($uid, $reset = TRUE);

  .......
  $extra =drupal_get_form('user_register_form', $existing_account);

   $form = array_merge($form,$extra);

     $form[actions]['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Update Subscriber'),
      '#weight' => 30
$form['#validate'][] = 'mymodule_create_subscriber_validate';
  $form['#submit'][] = 'mymodule_create_subscriber_submit';
....
}

function mymodule_create_subscriber_validate(&$form, &$form_state) {

 ....some code

  return;
}

function mymodule_create_subscriber_submit(&$form, &$form_state) {
$account = array();
  $account = $form_state['values'];

......
 $account = user_save($existing_account, $account, $category);
   .....
}
</code>
Please help me where I am doing wrong or what should I do?
Answer: You are trying to hack user registration instead of extending the feature in a right way.
If your requirement is additional validations on user registration form try using hook_form_alter.
More about hooks here.
Comment: Thanks anil for your suggestion, but here I am using user_register_form in a custom form.....ok let me explain it.

In Admin I have user listing (custom) and when I edit any user then I can see form with username, email, password, status textboxes

I created First Name and Last Name and Profile custom fields using Profile2 module.
Custom fields are displaying i user edit form but its not pre filled mean all fields come blank....and also its give ne already existing email id when I submit the form after fill all fields.
Comment: Drupal does provide Edit User functionality out of the box .. Why are you recreating separate page for that ? Normally path for user edit is user/{uid}/edit...
Comment: :), its a different module using user listing but have more functionality in edit section. so please help me to use "user_register_form" function in my form


Pigeonhole principle - cutting a square out of a rectangle

Question: Paper sized 10cm x 100cm was filled with 999 points. Show that you can cut a 1cm x 1cm square out of the paper without touching any of the points.
Can anyone help me understand this problem..I know how to solve problems where you have to show that some points are less than some unit away from each other but how to show that there is at least 1cm between 4 of them.
Comment: Instead of that, put a 1cm x 1cm grid on the paper and argue that there aren't enough points to cover each of them. Then you're done.
Answer: A 10 * 100 rectangle would have 1000 squares of side 1 cm.

If all points were clustered into one of these squares, then the remaining 999 could be safely cut out.
If we were to take it as 1 point per square, there's still 1 square left without a point.

All other permutations lie between these 2 extremes. Therefore, you can cut one 1*1 square without touching any of the points.


Apache runs several processes slows server, MYSQL can't connect, always fixed after reboot

Question: My WordPress Web Server will run for 30 - 60 minutes (then go down, and run very slowly as a server, difficult to input using Putty, or KVM terminal), after a reboot it will run fine, then Apache will run several processes (screenshot:) and go down again.
The WordPress debug.log will fill with errors (screenshot:).
I have been able to resolve a few of the errors:
[29-Dec-2019 20:27:34 UTC] PHP Notice:  Use of undefined constant REQUEST_URI - assumed 'REQUEST_URI' in /var/www/wordpress/wp-content/themes/Divi/Divi/functions.php on line 73
I added '  (missing single quotes) to 'REQUEST_URI' on line 71, which seems to have fixed things.
I've also done the following:
Limited the Apache Processes in /etc/apache2/apache2.conf.  I used this guide:
Tuning an Apache Server in 5 Minutes
<IfModule prefork.c>
StartServers       4
MinSpareServers    3
MaxSpareServers   10
ServerLimit      256
MaxClients       256
MaxRequestsPerChild  10000
</IfModule>
Comment: Additional information request.
RAM size, # cores, any SSD devices on MySQL Host server?
Post on pastebin.com and share the links.
A) complete (not edited) my.cnf or my.ini
From SSH login root, Text results of:
B) SHOW GLOBAL STATUS;    after minimum 24 hours UPTIME
C) SHOW GLOBAL VARIABLES;
AND Optional very helpful information, if available includes -
htop OR top  for most active apps,
ulimit -a       for a Linux/Unix list of limits,
iostat -xm 5 3 for IOPS by device and core/cpu count,
for server workload tuning analysis to provide suggestions.
Answer: 256 Clients in Apache is causing the trouble; shrink that to 30.
Swapping is terrible for performance, especially for MySQL.
As the screenshot says, do not use the mysql_* interface.  Also, do not mix the mysql_* and mysqli_* calls.
Set innodb_buffer_pool_size to only 700M.
If you still have trouble after those changes, come back for more advice.


React array.splice on state array does not update dom properly?

Question: I have an object like this
const obj =  {
      a:'something',
      b:'something else',
      c : [
        {
          a:'something',
          b:'something else',
        },
        {
          a:'something2',
          b:'something else2',
        },
      ]
    }

when i call the function to remove one element from the array c like this
//where index is 0 for example
const removeItem = index => setObj({...obj,c:obj.c.splice(index,1)})

the item gets removed from the array and the page however on the page the element left that i mapped from c have the values of c[0] but if i console.log(obj.c) i get this
const obj =  {
      a:'something',
      b:'something else',
      c : [
        {
          a:'something2',
          b:'something else2',
        },
      ]
    }

which is actually what i want but it's not reflected on the page..... what am i doing wrong?
Comment: Is your object passed as either state or props?
Comment: yes i'm passing c[n] as prop
Answer: When Array.splice() removes items, it mutates the original array, and returns an array of the removed items.
Use another method to remove the item, such as filter, which returns a new array without the item:
const removeItem = index => setObj(o => ({
  ...o,
  c: obj.c.filter((_, i) => i !== index)
}))

Or clone the array with array spread, and then splice it:
const removeItem = index => setObj(o => {
  const c = [...o.c]

  c.splice(index,1)

  return { ...obj, c }
})

Comment: i tried but i get the same result,the item gets successfuly removed from the array but on the page the element left is not the one i want, for example if i remove c[0] it gets removed from the array but on the page the one who gets removed is c[1]
Comment: What are you using as the key of the item when rendering it? If you're using the index, react won't know that it needs to re-render the item.
Comment: yes i'm actually using the index as keys....but i don't have anything else to use since when i pass c[n] as prop the properties c:a and c:b they are empty
Comment: problem 1 - The slice method returns the item that you remove, which you assign to `c`.
problem 2 - Using the index as key, react won't re-render items at existing indexes. ie - only added items, or items removed from the end would change.
Comment: You'll to add items with an some kind of a fake `id`.
Comment: i fixed it, i added an id property on c which is id : c[n] and it works now, thanks!


Javascript Date - set just the date, ignoring time?

Question: I have a bunch of objects, each of which has a timestamp, that I want to group by date, into a JSON object. The ultimate goal is something like this:
myObject = {
    "06/07/2012" : [
        {
            "timestamp" : "07/06/2012 13:30",
            ...
        },
        {
            "timestamp" : "07/06/2012 14:00",
            ...
        }
    ],
    "07/07/2012 [...]
}

To get the date, I'm testing each timestamp object and using:
var visitDate = new Date(parseInt(item.timestamp, 10));
visitDate.setHours(0);
visitDate.setMinutes(0);
visitDate.setSeconds(0);

..then I'm using that to store as a name for the JSON object. It seems messy, and I'm sure there should be an easier way of doing things.
Advice / suggestions welcomed!!
Comment: You should always store your dates with `.toISOString()` you're going to have issues with timezones storing dates with the strings you have. The only time you want to use that format is when you display it.
Comment: I can't imagine `new Date(parseInt("07/06/2012 13:30",10));` would work. Or am I missing something?
Comment: Yeah, you're right - sorry, this is pasted out of some of my existing code and not proof-read! The current code stores the timestamp as the 'milliseconds from epoch' format, so it made more sense in its original context...
Comment: You're correct @justin.m.chase - these days you should. When this question was written we still had to support IE8 which didn't support `toISOString()`. Hallelujah we live in a modern world now!
Answer: How about .toDateString()?
Alternatively, use .getDate(), .getMonth(), and .getYear()?
In my mind, if you want to group things by date, you simply want to access the date, not set it.  Through having some set way of accessing the date field, you can compare them and group them together, no?
Check out all the fun Date methods here: MDN Docs

Edit: If you want to keep it as a date object, just do this:
var newDate = new Date(oldDate.toDateString());

Date's constructor is pretty smart about parsing Strings (though not without a ton of caveats, but this should work pretty consistently), so taking the old Date and printing it to just the date without any time will result in the same effect you had in the original post.
Comment: Note: scroll down a bit to find the *full* list of methods. So many variants of toString, your head will pop.
Comment: That's probably a more sensible way to do it, I was thinking of leaving it as a Date object, although it's stored as text in JSON anyway I guess!

The original reason for not using `.toDateString()` was being unsure about having spaces in the field. Don't suppose that matters though really
Comment: ooh `.valueOf()` - that's also useful! Thanks!
Comment: Happy to help. If you like, I edited the question to give a way to keep them as Date objects, if it suits your fancy
Answer: new Date().toISOString().split('T')[0]

Comment: This will provide the IST. not the local time
Comment: toISOString uses GMT/UTC, not local time. You get the wrong time, unless your timezone is actually GMT/UTC.
Comment: This is one the solid solution, like if you pass this to an endpoint that has validation its will surely success.
Answer: If you don't mind creating an extra date object, you could try:
var tempDate = new Date(parseInt(item.timestamp, 10));
var visitDate = new Date (tempDate.getUTCFullYear(), tempDate.getUTCMonth(), tempDate.getUTCDate());

I do something very similar to get a date of the current month without the time.
Comment: I think it should be getUTCDate.  getUTCDay returns the day of the week (0,6). getUTCDate returns the day of the month (1,31)
Answer:

var today = new Date();
var year = today.getFullYear();
var mes = today.getMonth()+1;
var dia = today.getDate();
var fecha =dia+"-"+mes+"-"+year;
console.log(fecha);
Answer: If the date is in ISO string format, the date part can be seperated using
'2022-06-01T00:00:00'.split('T')[0]

result
2022-06-01

Answer: Just split the local date string to array by "/" and arrange them to accordingly,very simple.
var date=new Date();
var datearray=date.toLocaleString().split("/");
var sqldate= datearray[2].slice(0,4)+"-"+(datearray[0]<=9?"0"+datearray[0]:datearray[0])+"-"+(datearray[1]<=9?"0"+datearray[1]:datearray[1]);

Answer:

let date = new Date((new Date("07/06/2012 13:30")).toDateString())
console.log(date)
Answer: Date handling is unavoidably tricky. First off, you will save a lot of trouble if you send datetimes as UTC ISO strings ("yyyy-MM-dd hh:mm:ss.000Z"). If you're storing dates as strings, store them as ISO strings. Parsing dates with slashes is locale dependent and so error prone. (Europeans put the day first, americans the month.)
To get a date string from a datetime ISO string, use myDatetimeString.substring(0,10). To get a date object from a date string, just add the zeros...
myUtcMidnightDateObject = new Date( myDateString + ' 00:00:00Z' )

To then format your UTC midnight date object, use toLocaleString() with the UTC option...
myFormattedDate = myUtcMidnightDateObject.toLocaleDateString({},{ timeZone: "UTC" })

Much more detail can be found here.
Answer: Since no good solution has been presented:
It actually depends on whether you want to achive 00:00:00.000 in UTC or LocalTime.
If you have a datetime-variable somedate (var somedate = new Date()), you can just do:
somedate.setHours(0, 0, 0, 0);

and somedate will now be 00:00:00.000.
If you want a new date that is 00:00:00.000 (and not modify the original-value), you do:
var nd = new Date(somedate.getTime());
nd.setHours(0, 0, 0, 0);

The above is for localtime.
Now, if you want the GMT-representation to be 00:00:00.000, you can do it like this:
var myDate = new Date(Date.parse("2023-11-30T23:59:59.000"));
var timePortion = myDate.getTime() % 86400000;
var dateOnly = new Date(myDate - timePortion);

You could think, I'm very clever and doint it with the GMT-method for localtime, like:
var myDate = new Date(Date.parse("2023-11-30T23:59:59.000"));
var timePortion = myDate.getTime() % 86400000;
var dateOnly = new Date(myDate - timePortion + myDate.getTimezoneOffset()*60000);

And think this works.
But that would actually be stupid, because if you pass 2023-11-30T00:00:00.000", and your UTC/GMT-offset is less than zero, then you're off by about 24 hours, because the GMT will be 23:XX:YY.000 of the previous day, and that's the date that will be set to 00:00:00, meaning if you transform it to localtime, you get the wrong day.
Also, if you want to transform your newly time-cleared date into an iso-string (but in localtime) be aware that somedate.toISOString() will
A) be in GMT
and
B) it will have a Z at the end
, which is not ISO 8601, because ISO 8601-format is yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff and not yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'.
So if you need it as ISO-8601 in localtime, you can use this function:
    function removeTime(your_date)
    {
        var nd = new Date(your_date.getTime());
        nd.setHours(0, 0, 0, 0);

        function pad(number, num)
        {
            // Convert number to string
            var str = number.toString();

            // Calculate the number of zeroes to pad
            var zeroCount = num - str.length;

            // Pad with zeroes
            for (var i = 0; i < zeroCount; i++)
            {
                str = '0' + str;
            }

            return str;
        };

        return nd.getFullYear() +
            '-' + pad(nd.getMonth() + 1, 2) +
            '-' + pad(nd.getDate(), 2) +
            'T' + pad(nd.getHours(), 2) +
            ':' + pad(nd.getMinutes(), 2) +
            ':' + pad(nd.getSeconds(), 2) +
            '.' + pad(nd.getMilliseconds(), 3)
    };


Sum, product and scalar multiples of random variables are random variables?

Question: I am taking a course on Advanced Probability Theory. The definition of a random variable on a probability space $(\Omega, S, P)$ is as follows:

$X\colon \Omega\to\mathbb R$ is a random variable iff for every $\alpha\in \mathbb R$, we have that $(X\le \alpha) :=\{\omega\in \Omega: X(\omega)\le \alpha\}\in S$.

The professor then commented that for any random variables $X$, $Y$ on $(\Omega, S, P)$ and any real $c$, we have that $X + Y$, $cX$, and $XY$ (all defined pointwise on $\Omega$) are random variables. It was said that the proof of this requires a "lot of analysis", and was thus deferred.
However, I couldn't find a proof of these facts anywhere.
Any help or a reference to a resource?
Comment: Proving those facts are usually left as exercises in many courses and can be found on this site, for example [link](https://math.stackexchange.com/questions/305989/how-do-i-show-that-the-sum-of-two-random-variables-is-random-variable).
Comment: A measurable function of a measurable function is...a measurable function.
Answer: These facts are proven in almost every measure theory or probability theory book. The result doesn't really require any hard analysis; the result is  almost immediate from the continuity of addition and multiplication, modulo the proof that $(f, g)$ is measurable if and only if $f$ and $g$ are both measurable. You can see these facts proved using this strategy in theorem 1.91 on page 40 of "Probability Theory: A Comprehensive Course" by Klenke.


Legendre's Proof (continued fractions) from Hardy's Book

Question: I'm tryng to understand the proof given in Hardys book A Theory of Numbers from the chapter on continued fractions. It states that
If $$\left|\frac{p}{q}-x\right| < \frac{1}{2q^2}$$ then $\frac{p}{q}$ is a convegent to $x$.
Proof:
I the above inequality holds then $$\frac{p}{q} - x = \frac{\epsilon \alpha}{q^2},$$
$\epsilon = \pm 1$ and $ 0 < \alpha < \frac{1}{2}.$ This part makes sense   but then he says
We write $\frac{p}{q}$ as a finite continued fraction say $[a_0,a_1,...,a_n];$ and  by  Theorem 158  we can choose n even or odd, we may assume that $\epsilon = (-1)^{n-1}.$ x can be written as
$$x = \frac{\omega p_n + p_{n-1}}{\omega q_n + q_{n-1}}$$
This equality is what I dont understand. Where does $\omega$ come from?
The book says that  $\omega = \frac{1}{\alpha} - \frac{q_{n-1}}{q_n}.$
but I've tried staring at it for the last hour and I dont get where it comes from.
Answer: Consider $\omega$ as an unknown for a moment. Solve $x = \frac{\omega p_n + p_{n-1}}{\omega q_n + q_{n-1}}$ for $\omega$:
$$
\omega = \frac{q_{n-1}x - p_{n-1}}{-q_nx+p_n}
$$
Now insert
$$
x = \frac{p}{q} - \frac{\epsilon\alpha}{q^2}
$$
and note $p=p_n, q=q_n$ as well as $q_{n-1}p_n-p_{n-1}q_n = \epsilon$. This gives immediately the stated value for $\omega$.


How to pass Get parameter to url when url has "?" mark

Question: In my site clean urls is not working. As a result ?q is getting appended to the url.
My site url is http://abc.com/?q=user
I wrote a form in a page, and redirect to another view which is http://abc.com/?q=listings.
When I click on submit button in form page GET parameter are not getting appended correctly:
They are getting appended as http://abc.com/?field_list=3 which has to be like this http://abc.com/?q=listings&field_list=3.
I must use GET method in the form.
How should I redirect to URLs that contains "?q="?
How to do this.
Answer: If you are redirecting from the form submission handler, you need to use code similar to the following one.
$form_state['redirect'] = array(
  'listings',
   array(
     'query' => array(
     'field_list' => '3',
   ),
);

That code is equivalent to calling drupal_goto('listings, array('query' => array('field_list' => '3')) which should never be used inside a form submission handler. In both the cases, the function that is called to build the URL is url(), which works when clean URLs are enabled, or not.
  // With Clean URLs.
  if (!empty($GLOBALS['conf']['clean_url'])) {
    $path = drupal_encode_path($prefix . $path);
    if ($options['query']) {
      return $base . $path . '?' . drupal_http_build_query($options['query']) . $options['fragment'];
    }
    else {
      return $base . $path . $options['fragment'];
    }
  }
  // Without Clean URLs.
  else {
    $path = $prefix . $path;
    $query = array();
    if (!empty($path)) {
      $query['q'] = $path;
    }
    if ($options['query']) {
      // We do not use array_merge() here to prevent overriding $path via query
      // parameters.
      $query += $options['query'];
    }
    $query = $query ? ('?' . drupal_http_build_query($query)) : '';
    $script = isset($options['script']) ? $options['script'] : '';
    return $base . $script . $query . $options['fragment'];
  }


Check if string contains word at start of string

Question: I am starting to learn a little bit more advanced js and i want to check if string contains a word at the start of the line.
Something like this would be good!:
var string = "Hello world";
if (string.contains("Hello", start) == true)
{
console.log("success");
}

Comment: Im sorry about not mentioning that i want it to work in node js
Answer: Very easy Method:
var str = "Hello World";

if (str.startsWith("Hello")){
    do stuff;
}

You could also make two arrays and compare the single letters using a for loop, slightly more creative :D
Comment: Thx it worked great
Comment: But not in node js now when i tested it sorry
Comment: You could do it "manually",but I'll post it in another answer so I have the code format.
Comment: var str = "Hello World"; var test = "Hello";       var size = test.length;              if ( test ==   str.substring(0,size)){ do stuff;}
Answer: if (fullString.substring(0, stringToFind.length) == stringToFind) {

}

Comment: This worked to but it was a little long
Comment: Seems to not work in node.js tho
Answer: In ES6, you can use startsWith: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith.
Otherwise you can use RegExp with '^' which matches the beginning of input (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) like this: /^Hello/.test('Hello World')


Loading CSV in Neo4j is time consuming

Question: I want load a CDR csv file with 648000 records to neo4j (4.4.10), But it is about 4 days and And it is not yet completed.
My CSV have 648000 records with 7 columns. and the size of file is about 48 MB.
My computer have 100 GB RAM and intel Zeon E5 CPU.
the columns of CSV are:

OP_Name
TP_Name
Called_Number
OP_ANI
Setup_Time
Duration
OP_Price

the code that I use to load CSV in Neo4j is:
```Cypher
:auto load csv with headers from 'file:///cdr.csv' as line FIELDTERMINATOR  ','
    with line
    where line['Called_Number'] is not null and line['OP_ANI'] is not null
    with line['OP_ANI'] as OP_Phone,
        (CASE line['OP_Name']
            WHEN 'TIC' THEN 'IRAN'
            ELSE 'Foreign' END) AS OP_country,
        line['Called_Number'] as Called_Phone,
        (CASE line['TP_Name']
            WHEN 'TIC' THEN 'IRAN'
            ELSE 'Foreign' END) AS TP_country,
        line['Setup_Time'] as Setup_Time,
        line['Duration'] as Duration,
        line['OP_Price'] as OP_Price

    call {
        with  OP_Phone, OP_country, Called_Phone, TP_country, Setup_Time, Duration, OP_Price

MERGE (c:Customer{phone: toInteger(Called_Phone)})
            on create set c.country = TP_country
            WITH c, OP_Phone, OP_country, Called_Phone, TP_country, Setup_Time, Duration, OP_Price
            CALL apoc.create.addLabels( c, [ c.country ] ) YIELD node

MERGE (c2:Customer{phone: toInteger(OP_Phone)})
            on create set c2.country = OP_country
            WITH c2, OP_Phone, OP_country, Called_Phone, TP_country, Setup_Time, Duration, OP_Price, c
            CALL apoc.create.addLabels( c2, [ c2.country ] )  YIELD node

        MERGE (c2)-[r:CALLED{setupTime: Setup_Time,
                    duration: Duration,
                    OP_Price: OP_Price}]->(c)

    } IN TRANSACTIONS

```

How can I speed up the load operation?
Comment: Try creating an index on `phone` property of `Customer`. Like this: `CREATE INDEX phone IF NOT EXISTS
FOR (n:Customer)
ON (n.phone)`
Comment: Great. I will post that as an answer so that other users can also take advantage of it.
Answer: MERGE acts as an upsert in Neo4j. So the statement:
MERGE (c:Customer{phone: toInteger(Called_Phone)})

checks if there is a Customer node with the given phone number is there or not. If it is, it performs the update otherwise creates the node. When there is a large number of nodes, this lookup can be very slow, and CSV import will be slow overall. Creating an index on the phone property of Customer should do the trick. You can create the index like this:
CREATE INDEX phone IF NOT EXISTS FOR (n:Customer) ON (n.phone)

Loading CSV in Neo4j is time consuming


jQuery Scroll function : Scroll Top and Window Height 1px discrepancy in value

Question: This a function for infinate scroll. Sometimes it works, sometime the log output calucates a difference of 1 between the $(window).scrollTop(), and $(document).height() - $(window).height() and I can't for the life of me figure out why.
What am I missing? Thanks
   $window.scroll(function() {
     var position     = $(window).scrollTop(),
     docHeight    = $(document).height(),
     windowHeight = $(window).height(),
     bottom =  docHeight - windowHeight;

     console.log(position);
     console.log(bottom);

     if(position == bottom ) {
       console.log('ajax');
       load_posts();
     }
   }

Answer: It is because the browser sometimes adds its own stylesheet as well. That may be the cause of your issue. Try using reset.css. It resets all the browser default css.
And its always a good practice to trigger infinite scroll from around 50px of the bottom. You dont wanna have the user to scroll to "the very end" to show next content.
Comment: Thanks for 50px tip, that gets my feature working. However I'm still confused as to what is causing the problem- for instance, I imagined the javascript to be measuring the what the browser has `rendered` regardless of what style's are are applied. Your suggestion for a css reset doesn't sound wrong per say, I'd just like to understand better exactly what the javascript is taking it's measurements from.
Comment: every browser has its own default stylesheet called the user agent stylesheet which has default margin, padding etc. for the browser. This might be causing inconsistencies for the js while calculating. There is a nice list of css2 defaults given here http://css-class.com/test/css/defaults/UA-style-sheet-defaults.htm
Comment: cool, I guess I just have to read the methods I'm using to really understand what's going on, thanks for pointing me in the right direction.


AOSP build on custom device -emulator

Question: I'm learning AOSP build system, especially how to add new devices.
I build android-6.0.1_r46  Marshmallo ,on default full-eng configuration and run it on emulator. It was working properly.
But when I tried to add my custom device in source tree like     /device/my_company/my_product/   than build successfully and run it on emulator - emulator just hangs up with black screen. Not loading at all.
how can i make emulator work ?
my makefiles are as given below..
Android.mk
ifneq ($(filter my_product, $(TARGET_DEVICE)),)

LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)

include $(call all-makefiles-under,$(LOCAL_PATH))

endif

AndroidProducts.mk
PRODUCT_MAKEFILES := \
 $(LOCAL_DIR)/aosp_my_product.mk

vendorsetup.sh
add_lunch_combo aosp_my_product-eng

aosp_my_product.mk
#$(call inherit-product, device/generic/mini-emulator-armv7-a-neon/mini_emulator_common.mk) //copied to device.mk

$(call inherit-product, device/my_company/my_product/device.mk)

#Overrides

PRODUCT_NAME := aosp_my_product
PRODUCT_DEVICE :=my_product
PRODUCT_MODEL := Customized Android
PRODUCT_MANUFACTURER :=my_company
PRODUCT_BRAND :=Android

PRODUCT_LOCALES := en_US
PRODUCT_PACKAGE_OVERLAYS := device/my_company/my_product/overlay
PRODUCT_CHARACTERISTICS := nosdcard

device.mk
 PRODUCT_NAME :=aosp_my_product
    PRODUCT_DEVICE :=my_product
    PRODUCT_MODEL := Customized Android
    PRODUCT_MANUFACTURER := my_company
    PRODUCT_BRAND := Android

    LOCAL_KERNEL := prebuilts/qemu-kernel/arm/kernel-qemu-armv7
    PRODUCT_COPY_FILES += \
    $(LOCAL_KERNEL):kernel

# common stuffs across mini_emulators

PRODUCT_PACKAGES += \
    audio.primary.goldfish \
    camera.goldfish \
    gps.goldfish \
    gralloc.goldfish \
    lights.goldfish \
    power.goldfish \
    sensors.goldfish \
    vibrator.goldfish \
    qemu-props \
    qemud \
    libGLES_android \
    libGLESv1_CM_emulation \
    lib_renderControl_enc \
    libEGL_emulation \
    libGLESv2_enc \
    libOpenglSystemCommon \
    libGLESv2_emulation \
    libGLESv1_enc \
    rild

PRODUCT_COPY_FILES += \
    device/generic/mini-emulator-armv7-a-neon/init.mini-emulator.rc:root/init.goldfish.rc \
    device/generic/goldfish/init.goldfish.sh:system/etc/init.goldfish.sh \
    device/generic/goldfish/ueventd.goldfish.rc:root/ueventd.goldfish.rc \
    device/generic/goldfish/data/etc/apns-conf.xml:system/etc/apns-conf.xml \
    frameworks/native/data/etc/android.hardware.touchscreen.multitouch.jazzhand.xml:system/etc/permissions/android.hardware.touchscreen.multitouch.jazzhand.xml \
    frameworks/native/data/etc/android.hardware.camera.autofocus.xml:system/etc/permissions/android.hardware.camera.autofocus.xml \
    frameworks/av/media/libeffects/data/audio_effects.conf:system/etc/audio_effects.conf \
    hardware/libhardware_legacy/audio/audio_policy.conf:system/etc/audio_policy.conf \
    device/generic/goldfish/camera/media_profiles.xml:system/etc/media_profiles.xml \
    frameworks/av/media/libstagefright/data/media_codecs_google_audio.xml:system/etc/media_codecs_google_audio.xml \
    frameworks/av/media/libstagefright/data/media_codecs_google_telephony.xml:system/etc/media_codecs_google_telephony.xml \
    frameworks/av/media/libstagefright/data/media_codecs_google_video.xml:system/etc/media_codecs_google_video.xml \
    device/generic/goldfish/camera/media_codecs.xml:system/etc/media_codecs.xml \
    device/generic/goldfish/fstab.goldfish:root/fstab.goldfish

BoardConfig.mk
# config.mk
#
# Product-specific compile-time definitions.
#
# The generic product target doesn't have any hardware-specific pieces.

TARGET_NO_BOOTLOADER := true
TARGET_NO_KERNEL := true
TARGET_ARCH := arm

TARGET_ARCH_VARIANT := armv7-a
TARGET_CPU_VARIANT := generic
TARGET_CPU_ABI := armeabi-v7a
TARGET_CPU_ABI2 := armeabi

SMALLER_FONT_FOOTPRINT := true
MINIMAL_FONT_FOOTPRINT := true
# Some framework code requires this to enable BT
BOARD_HAVE_BLUETOOTH := true
BOARD_BLUETOOTH_BDROID_BUILDCFG_INCLUDE_DIR := device/generic/common/bluetooth

BOARD_USES_GENERIC_AUDIO := true

USE_CAMERA_STUB := true

BUILD_EMULATOR_OPENGL := true
USE_OPENGL_RENDERER := true

BOARD_USE_LEGACY_UI := true
VSYNC_EVENT_PHASE_OFFSET_NS := 0

TARGET_USERIMAGES_USE_EXT4 := true

BOARD_BOOTIMAGE_PARTITION_SIZE := 576716800
BOARD_SYSTEMIMAGE_PARTITION_SIZE := 576716800
BOARD_USERDATAIMAGE_PARTITION_SIZE := 576716800

BOARD_CACHEIMAGE_PARTITION_SIZE := 69206016
BOARD_CACHEIMAGE_FILE_SYSTEM_TYPE := ext4
BOARD_FLASH_BLOCK_SIZE := 512
TARGET_USERIMAGES_SPARSE_EXT_DISABLED := true

BOARD_SEPOLICY_DIRS += build/target/board/generic/

#ifndef PDK_FUSION_PLATFORM_ZIP
#ifeq ($(HOST_OS),linux)
# WITH_DEXPREOPT := true
#endif
#endif # PDK_FUSION_PLATFORM_ZIP

out/target/product/my_product$ ls
android-info.txt  hardware-qemu.ini         symbols
cache             installed-files.txt       system
cache.img         kernel                    system.img
clean_steps.mk    obj                       userdata.img
data              previous_build_config.mk  userdata-qemu.img
dex_bootjars      ramdisk.img
gen               root

adb devices  shows
emulator-5554   offline
[cmd]~/aosp$ emulator &
[1] 17183
[cmd]~/aosp$ emulator -verbose
    emulator:Found ANDROID_PRODUCT_OUT: /home/azahar/aosp/out/target/product/my_product
    emulator:Found build target architecture: arm
    emulator:Looking for ranchu emulator backed for arm CPU
    emulator:Probing program: ./emulator64-ranchu-arm
    emulator:Probing program: ./emulator-ranchu-arm
    emulator:Probing path for: emulator64-ranchu-arm
    emulator:Probing path for: emulator-ranchu-arm
    emulator:Looking for emulator-arm to emulate 'arm' CPU
    emulator:Probing program: ./emulator64-arm
    emulator:Probing program: ./emulator-arm
    emulator:Probing path for: emulator64-arm
    emulator:Found target-specific emulator binary: /home/azahar/aosp/prebuilts/android-emulator/linux-x86_64/emulator64-arm
    emulator:GPU emulation is disabled
    emulator: found Android build root: /home/azahar/aosp
    emulator: found Android build out:  /home/azahar/aosp/out/target/product/my_product
    emulator: Read property file at /home/azahar/aosp/out/target/product/my_product/system/build.prop
    emulator: Cannot find boot properties file: /home/azahar/aosp/out/target/product/my_product/boot.prop

    emulator: Found target API sdkVersion: 23

    emulator: virtual device has no config file - no problem
    emulator: using core hw config path: /home/azahar/aosp/out/target/product/my_product/hardware-qemu.ini
    emulator: found skin-specific hardware.ini: /home/azahar/aosp/development/tools/emulator/skins/HVGA/hardware.ini
    emulator: autoconfig: -skin HVGA
    emulator: autoconfig: -skindir /home/azahar/aosp/development/tools/emulator/skins
    emulator: found skin-specific hardware.ini: /home/azahar/aosp/development/tools/emulator/skins/HVGA/hardware.ini
    emulator: keyset loaded from: /home/azahar/.android/default.keyset
    emulator: trying to load skin file '/home/azahar/aosp/development/tools/emulator/skins/HVGA/layout'
    emulator: skin network speed: 'full'
    emulator: skin network delay: 'none'
    emulator: autoconfig: -kernel /home/azahar/aosp/out/target/product/my_product/kernel
    emulator: Auto-detect: Kernel image requires legacy device naming scheme.
    emulator: Auto-detect: Kernel does not support YAFFS2 partitions.
    emulator: autoconfig: -ramdisk /home/azahar/aosp/out/target/product/my_product/ramdisk.img
    emulator: autoconfig: -sysdir /home/azahar/aosp/out/target/product/my_product
    emulator: Using initial system image: /home/azahar/aosp/out/target/product/my_product/system.img
    emulator: WARNING: system partition size adjusted to match image file (550 MB > 200 MB)

    emulator: autoconfig: -data /home/azahar/aosp/out/target/product/my_product/userdata-qemu.img
    emulator: autoconfig: -initdata /home/azahar/aosp/out/target/product/my_product/userdata.img
    emulator: WARNING: data partition size adjusted to match image file (550 MB > 200 MB)

    emulator: autoconfig: -cache /home/azahar/aosp/out/target/product/my_product/cache.img
    emulator: Physical RAM size: 512MB

    emulator: GPU emulation is disabled
    emulator: WARNING: CPU acceleration only works with x86/x86_64 system images.
    emulator: Auto-config: -qemu -cpu cortex-a8
    Content of hardware configuration file:
      hw.cpu.arch = arm
      hw.cpu.model = cortex-a8
      hw.ramSize = 512
      hw.screen = touch
      hw.mainKeys = yes
      hw.trackBall = yes
      hw.keyboard = no
      hw.keyboard.lid = no
      hw.keyboard.charmap = qwerty2
      hw.dPad = yes
      hw.gsmModem = yes
      hw.gps = yes
      hw.battery = yes
      hw.accelerometer = yes
      hw.audioInput = yes
      hw.audioOutput = yes
      hw.sdCard = yes
      disk.cachePartition = yes
      disk.cachePartition.path = /home/azahar/aosp/out/target/product/my_product/cache.img
      disk.cachePartition.size = 66m
      hw.lcd.width = 320
      hw.lcd.height = 480
      hw.lcd.depth = 16
      hw.lcd.density = 160
      hw.lcd.backlight = yes
      hw.gpu.enabled = no
      hw.initialOrientation = portrait
      hw.camera.back = emulated
      hw.camera.front = none
      vm.heapSize = 48
      hw.sensors.proximity = yes
      hw.sensors.magnetic_field = yes
      hw.sensors.orientation = yes
      hw.sensors.temperature = yes
      hw.useext4 = yes
      kernel.path = /home/azahar/aosp/out/target/product/my_product/kernel
      kernel.parameters =  androidboot.hardware=goldfish android.checkjni=1
      kernel.newDeviceNaming = no
      kernel.supportsYaffs2 = no
      disk.ramdisk.path = /home/azahar/aosp/out/target/product/my_product/ramdisk.img
      disk.systemPartition.initPath = /home/azahar/aosp/out/target/product/my_product/system.img
      disk.systemPartition.size = 550m
      disk.dataPartition.path = /home/azahar/aosp/out/target/product/my_product/userdata-qemu.img
      disk.dataPartition.size = 550m
      avd.name = <build>
    .
    QEMU options list:
    emulator: argv[00] = "/home/azahar/aosp/prebuilts/android-emulator/linux-x86_64/emulator64-arm"
    emulator: argv[01] = "-android-hw"
    emulator: argv[02] = "/tmp/android-azahar/emulator-lsvyCj"
    Concatenated QEMU options:
     /home/azahar/aosp/prebuilts/android-emulator/linux-x86_64/emulator64-arm -android-hw /tmp/android-azahar/emulator-lsvyCj
    emulator: registered 'boot-properties' qemud service
    emulator: Using kernel serial device prefix: ttyS
    emulator: Ramdisk image contains fstab.goldfish file
    emulator: Found format of system partition: 'ext4'
    emulator: Found format of userdata partition: 'ext4'
    emulator: Found format of cache partition: 'ext4'
    emulator: system partition format: ext4
    emulator: Mapping 'system' partition image to /tmp/android-azahar/emulator-AvYGsQ
    emulator: nand_add_dev: system,size=0x22600000,file=/tmp/android-azahar/emulator-AvYGsQ,initfile=/home/azahar/aosp/out/target/product/my_product/system.img,pagesize=512,extrasize=0
    emulator: userdata partition format: ext4
    WARNING: userdata image already in use, changes will not persist!
    emulator: Mapping 'userdata' partition image to /tmp/android-azahar/emulator-YcBfzc
    emulator: Creating empty userdata partition image at: /tmp/android-azahar/emulator-YcBfzc
    Creating filesystem with parameters:
        Size: 576716800
        Block size: 4096
        Blocks per group: 32768
        Inodes per group: 7040
        Inode size: 256
        Journal blocks: 2200
        Label:
        Blocks: 140800
        Block groups: 5
        Reserved block group size: 39
    Created filesystem with 11/35200 inodes and 4536/140800 blocks
    emulator: nand_add_dev: userdata,size=0x22600000,file=/tmp/android-azahar/emulator-YcBfzc,pagesize=512,extrasize=0
    emulator: cache partition format: ext4
    WARNING: cache image already in use, changes will not persist!
    emulator: Mapping 'cache' partition image to /tmp/android-azahar/emulator-wM4p7H
    emulator: Creating empty cache partition image at: /tmp/android-azahar/emulator-wM4p7H
    Creating filesystem with parameters:
        Size: 69206016
        Block size: 4096
        Blocks per group: 32768
        Inodes per group: 4224
        Inode size: 256
        Journal blocks: 1024
        Label:
        Blocks: 16896
        Block groups: 1
        Reserved block group size: 7
    Created filesystem with 11/4224 inodes and 1302/16896 blocks
    emulator: nand_add_dev: cache,size=0x4200000,file=/tmp/android-azahar/emulator-wM4p7H,pagesize=512,extrasize=0
    emulator: registered 'boot-properties' qemud service
    emulator: Adding boot property: 'dalvik.vm.heapsize' = '48m'
    emulator: Adding boot property: 'ro.config.low_ram' = 'true'
    emulator: Adding boot property: 'qemu.sf.lcd_density' = '160'
    emulator: Adding boot property: 'qemu.hw.mainkeys' = '1'
    emulator: Adding boot property: 'qemu.sf.fake_camera' = 'back'
    emulator: Kernel parameters: qemu.gles=0 qemu=1 console=ttyS0 android.qemud=ttyS1 androidboot.hardware=goldfish android.checkjni=1 ndns=1
    emulator: autoconfig: -scale 1
    emulator: Forcing ro.adb.qemud to "0".
    emulator: control console listening on port 5556, ADB on port 5557
    emulator: sent '0012host:emulator:5557' to ADB server
    emulator: android_hw_fingerprint_init: fingerprint qemud listen service initialized

    emulator: ping program: /home/azahar/aosp/prebuilts/android-emulator/linux-x86_64/ddms
    goldfish_fb_get_pixel_format:170: display surface,pixel format:
      bits/pixel:  16
      bytes/pixel: 2
      depth:       16
      red:         bits=5 mask=0xf800 shift=11 max=0x1f
      green:       bits=6 mask=0x7e0 shift=5 max=0x3f
      blue:        bits=5 mask=0x1f shift=0 max=0x1f
      alpha:       bits=0 mask=0x0 shift=0 max=0x0

Comment: I am facing the same issue, Did you find any solution ?
Answer: You are building for an arm device which cannot be emulated on qemu.
You can try to build for any pre existing device like coral or merlin and check it it boot for them. But probably it will not.

AOSP build on custom device -emulator


Can I claim Makrov Chain or Hidden Markov Model are simple Recurrent Neural Networks?

Question: If we focus on sequence modeling (discrete time and discrete observations), Can I claim Makrov Chain or Hidden Markov Model are simple Recurrent Neural Networks (Because both of them have "time dependency components")?
Answer: No. A hidden markov model is a graphical model - or a bivariate stochastic process - and a markov chain is a stochastic process. They lack many of the properties that a typical RNN would have -- ability to train via backpropagation and ability to model non-markovian processes. A "node" in a hidden markov model is a random variable, while a node in an RNN has no such meaning. Just about the only way they are related is their ability to model sequential data.
Answer: No.
An important feature for Markov or Hidden Markov model is the Markovian property. Where given the current, past and future are independent. In the case of the first order Markov model, it can be described as
$$
P(X_i|X_1,\cdots, X_{i-1})= P(X_i|X_{i-1})
$$
On the other hand, for recurrent neural network, we can view the neural network is a very complicated function that is trying to estimate
$$
P(X_i|X_1,\cdots, X_{i-1})
$$
using large amount of the data.

In The Unreasonable Effectiveness of Recurrent Neural Networks, Fun with RNN part, we can see the model can generate a valid (but random) xml.
<page>
  <title>Antichrist</title>
  <id>865</id>
  <revision>
    <id>15900676</id>
    <timestamp>2002-08-03T18:14:12Z</timestamp>
    <contributor>
      <username>Paris</username>
      <id>23</id>
    </contributor>
    <minor />
    <comment>Automated conversion</comment>
    <text xml:space="preserve">#REDIRECT [[Christianity]]</text>
  </revision>
</page>

This would be extremely hard to use Markov or Hidden Markov model on character level. Since we need to remember things happens in far past, e.g.,  <page> and '' tag are 300 + characters apart. If we are building a 300th order Markov model, the transition matrix will be $26^{300}$, even if we only assume there are 26 letters.


Alphabetical sorting of terms (not using a view)

Question: I'm using the templates to display my terms rather than views but I'd like to change the order that the items are sorted. Currently it appears to be sorted by date. I would like to sort them alphabetically. Is this something I can do in the temeplate.php or within anywhere else?
Comment: How do you call your terms?
Comment: I use a conditional statements within the page template so if term then...
Comment: Do you get back an array that you're rendering or is it already rendered?
Comment: I'm choosing the fields to output yeah from an array
Comment: Can't you just sort the array before rendering it?
Comment: if they come from  would I be able to do that though?
Comment: hmmm but you need to implement the terms in your content type at some point, how do you do that? give all the code+details you can.
Answer: The easiest way indeed is using views.
If you really don't like to do so, you could create a custom module, implement hook_menu_alter() to alter the page callback of the taxonomy page:
<code>/**
 * Implements hook_menu_alter()
 */
function MYMODULE_menu_alter(&$items) {
  if (isset($items['taxonomy/term/%taxonomy_term'])) {
    $items['taxonomy/term/%taxonomy_term']['page callback'] => 'MYMODULE_my_taxonomy_page';
  }
}
</code>
Then write your own version of the taxonomy module's function taxonomy_term_page($term) (using the above example, you would call it MYMODULE_my_taxonomy_page).
Within this function you can alter the call of taxonomy_select_nodes and add a fourth parameter, specifying the desired sort order:
<code>$order = array('t.title' => 'ASC')
</code>
Note that this is working only, if you did not use a field replacement for the title property (e.g. using the title module). Then you would have to write an own version of the taxonomy_select_nodes function as well.
Comment: ok cool giving it a go...
Comment: Let me know, if it worked for you or any information is missing in my answer. Also feel free to upvote/accept the answer once your term page is sorted alphabetically.
Comment: Assuming I have done it correctly it just seems to output nothing. I am getting the fields from the node array
Comment: Just checked your comments on your question. I was assuming you were talking of the term page. Seems you asked about the term references on a node page?
Comment: yeah the terms, so on the page template i have a if term then, and then on the node I have a if term then


How can I embed a video in a drupal page that is remotely hosted in Amazon s3 cloudfront?

Question: When I try to embed a video in a drupal page that is hosted remotely on an Amazon s3 server, I get the following error message:
"Could not find a video provider to handle the given URL"
I have the Video Embed Field, Video Embed Media, Video Embed WYSIWIG modules enabled, but still cannot get this to work.
The URL of my video has this form, where the x's represent the directory path to the videos.
https://s3-us-west-2.amazonaws.com/xxxxx/xxxxx/xxxx.mp4
Can anyone help me get this working?
Answer: Those modules only know how to embed videos from particular providers (Youtube, Vimeo, Facebook, etc). They actually parse the URL and check that it contains "youtube" or "vimeo" or whatever. The modules won't work with arbitrary URLs, S3 or not.
A couple of potential solutions:

Use a more generic module, for example VideoJS, which should theoretically let you embed a video from anywhere.
Write your own handler for Video Embed Field which knows how to embed videos from S3. You'll presumably have to find a JS library which can play the video from Amazon, and integrate that as part of it. Writing the handler itself is pretty easy, it's just a matter of a hook or two and a few functions. The code for the existing handlers makes it pretty obvious what needs to be done.
Comment: Thanks for the suggestions. I'll start with VideoJS to see if I can make that work.


Kubeadmin: Why do we need to upgrade the kubelet and kubectl seperately?

Question: Kubeadmin is a tool to manage and maintain the Kubernetes cluster. Based on the Kubernetes Doc, there are rough four steps to upgrade the controlplane node.

upgrade the version of kubeadmin itself

cordon the node

upgrade the controlplane components with this command kubeadm upgrade apply v1.26.x

upgrade the kubelet and kubectl with this command.
apt-mark unhold kubeadm && \
apt-get update && apt-get install -y kubeadm=1.26.x-00 && \
apt-mark hold kubeadm

Kubernetes components
Kubernetes is composed of many components, for example:

scheduler
etcd, a key-value storage
API server
kubelet
kubectl

When executing the command sudo kubeadm upgrade apply v1.26.x or kubeadm upgrade node, the ETCD, kube-apiserver, kube-controller-manager and kube-scheduler will be upgraded and restarted. Here are logs:
controlplane ~ ➜  kubeadm upgrade apply v1.25.0
[upgrade/config] Making sure the configuration is correct:
[upgrade/config] Reading configuration from the cluster...
[upgrade/config] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -o yaml'
[preflight] Running pre-flight checks.
[upgrade] Running cluster health checks
[upgrade/version] You have chosen to change the cluster version to "v1.25.0"
[upgrade/versions] Cluster version: v1.24.0
[upgrade/versions] kubeadm version: v1.25.0
[upgrade] Are you sure you want to proceed? [y/N]: y
[upgrade/prepull] Pulling images required for setting up a Kubernetes cluster
[upgrade/prepull] This might take a minute or two, depending on the speed of your internet connection
[upgrade/prepull] You can also perform this action in beforehand using 'kubeadm config images pull'
[upgrade/apply] Upgrading your Static Pod-hosted control plane to version "v1.25.0" (timeout: 5m0s)...
[upgrade/etcd] Upgrading to TLS for etcd
[upgrade/staticpods] Preparing for "etcd" upgrade
[upgrade/staticpods] Renewing etcd-server certificate
[upgrade/staticpods] Renewing etcd-peer certificate
[upgrade/staticpods] Renewing etcd-healthcheck-client certificate
[upgrade/staticpods] Moved new manifest to "/etc/kubernetes/manifests/etcd.yaml" and backed up old manifest to "/etc/kubernetes/tmp/kubeadm-backup-manifests-2022-12-16-08-40-41/etcd.yaml"
[upgrade/staticpods] Waiting for the kubelet to restart the component
[upgrade/staticpods] This might take a minute or longer depending on the component/version gap (timeout 5m0s)
[apiclient] Found 1 Pods for label selector component=etcd
[upgrade/staticpods] Component "etcd" upgraded successfully!
[upgrade/etcd] Waiting for etcd to become available
[upgrade/staticpods] Writing new Static Pod manifests to "/etc/kubernetes/tmp/kubeadm-upgraded-manifests2720616931"
[upgrade/staticpods] Preparing for "kube-apiserver" upgrade
[upgrade/staticpods] Renewing apiserver certificate
[upgrade/staticpods] Renewing apiserver-kubelet-client certificate
[upgrade/staticpods] Renewing front-proxy-client certificate
[upgrade/staticpods] Renewing apiserver-etcd-client certificate
[upgrade/staticpods] Moved new manifest to "/etc/kubernetes/manifests/kube-apiserver.yaml" and backed up old manifest to "/etc/kubernetes/tmp/kubeadm-backup-manifests-2022-12-16-08-40-41/kube-apiserver.yaml"
[upgrade/staticpods] Waiting for the kubelet to restart the component
[upgrade/staticpods] This might take a minute or longer depending on the component/version gap (timeout 5m0s)
[apiclient] Found 1 Pods for label selector component=kube-apiserver
[upgrade/staticpods] Component "kube-apiserver" upgraded successfully!
[upgrade/staticpods] Preparing for "kube-controller-manager" upgrade
[upgrade/staticpods] Renewing controller-manager.conf certificate
[upgrade/staticpods] Moved new manifest to "/etc/kubernetes/manifests/kube-controller-manager.yaml" and backed up old manifest to "/etc/kubernetes/tmp/kubeadm-backup-manifests-2022-12-16-08-40-41/kube-controller-manager.yaml"
[upgrade/staticpods] Waiting for the kubelet to restart the component
[upgrade/staticpods] This might take a minute or longer depending on the component/version gap (timeout 5m0s)
[apiclient] Found 1 Pods for label selector component=kube-controller-manager
[upgrade/staticpods] Component "kube-controller-manager" upgraded successfully!
[upgrade/staticpods] Preparing for "kube-scheduler" upgrade
[upgrade/staticpods] Renewing scheduler.conf certificate
[upgrade/staticpods] Moved new manifest to "/etc/kubernetes/manifests/kube-scheduler.yaml" and backed up old manifest to "/etc/kubernetes/tmp/kubeadm-backup-manifests-2022-12-16-08-40-41/kube-scheduler.yaml"
[upgrade/staticpods] Waiting for the kubelet to restart the component
[upgrade/staticpods] This might take a minute or longer depending on the component/version gap (timeout 5m0s)
[apiclient] Found 1 Pods for label selector component=kube-scheduler
[upgrade/staticpods] Component "kube-scheduler" upgraded successfully!
[upgrade/postupgrade] Removing the old taint &Taint{Key:node-role.kubernetes.io/master,Value:,Effect:NoSchedule,TimeAdded:<nil>,} from all control plane Nodes. After this step only the &Taint{Key:node-role.kubernetes.io/control-plane,Value:,Effect:NoSchedule,TimeAdded:<nil>,} taint will be present on control plane Nodes.
[upload-config] Storing the configuration used in ConfigMap "kubeadm-config" in the "kube-system" Namespace
[kubelet] Creating a ConfigMap "kubelet-config" in namespace kube-system with the configuration for the kubelets in the cluster
[kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[bootstrap-token] Configured RBAC rules to allow Node Bootstrap tokens to get nodes
[bootstrap-token] Configured RBAC rules to allow Node Bootstrap tokens to post CSRs in order for nodes to get long term certificate credentials
[bootstrap-token] Configured RBAC rules to allow the csrapprover controller automatically approve CSRs from a Node Bootstrap Token
[bootstrap-token] Configured RBAC rules to allow certificate rotation for all node client certificates in the cluster
[addons] Applied essential addon: CoreDNS
[addons] Applied essential addon: kube-proxy

[upgrade/successful] SUCCESS! Your cluster was upgraded to "v1.25.0". Enjoy!

[upgrade/kubelet] Now that your control plane is upgraded, please proceed with upgrading your kubelets if you haven't already done so.

Question

Why doesn't the command sudo kubeadm upgrade apply v1.26.x in step 3 upgrade the kubectl and kubelet as well?

why do we upgrade kubelet and kubectl in a separate step? (step 4)

Reference

Stack Overflow: why does kubeadm do exactly?

Kubernetes Doc: kubeadm will not install or manage kubelet or kubectl for you
Answer: The command sudo kubeadm upgrade does not upgrade kubectl and kubelet. Kubeadm only manages the control plane components, such as the API server, scheduler, and controller-manager. Kubectl and kubelet are the components that manage the nodes and workloads running on them. Therefore, they must be upgraded separately. @Ryan Lyu


how to create a "my comments" view

Question: I just want to create a view that show each user their own set of comments only. would I add something in contextual filters?
Thanks
Tony
Answer: Yes, add the contextual filter "Comment Author uid". Then, under the section "When the filter value is NOT available", select,
"provide a default value".
You can then select:
"User ID from logged in user"
or
"User ID from URL".
To use the latter, you will have to display the view as a block on a page that has the user->uid in the system path, such as the user account page (user/%uid). If you use the former, the view can be displayed anywhere, and will always show the current user's comments.

how to create a "my comments" view


Is there a name for chord shape 322450 on guitar?

Question:
This shape is playing an Em (322450), but I'm not used to see it and it doesn't match the common E and A movable shapes I see all the time.
Is this common with some specific styles?

Edit:
I should have added this at the beginning:
- This is the original song (tuned down for live):

- This is the guitar cover with the 'odd' chord shape:

you can see that shape around 1:07
Comment: It's uncommon to me too. Movable, but the top string would need muting. Something of a G6.
Comment: @Tim -- it took me a minute to catch up to you about the muting: muting to make it movable. It kind of looks like the top string is being muted by the side of the index finger in the image. If OP saw this labelled as an **Em** somewhere, it is an **Em** in first inversion, but it seems more likely to me that it would be used as a **G6**, as you say.
Comment: Why a G6? Other than the fact it's got a G bass, it's just root & 5th all the way up GBEBEE
Comment: @Tetsujin -- B is the 3rd of **G**, so 1-3-6: an acceptable **G6** ;)
Comment: The other guitar is playing an E5 at that time; the progression being A5-G5-E5, this is most likely an Em
Comment: 'The other guitar'? Where did that come into the question
Comment: It feels like it should form part of a Pink Floyd style pedal, like their Em structures that sit with a pedal D G at the top; think Wish you were Here etc
Comment: Emin first inversion, similar to G6 (no 5th).  The hand form is most like a G6 but the open string would make it difficult to translate up the neck (not a movable chord form).  On the other hand, your 5 on the B string is just doubling the open E.  Any reason for that?
Answer: It's an Em/G or maybe G6, but not a particularly nice sounding one, IMO. It's less muddy, if you leave out at least the second-lowest string, for example 3x24xx, but then you'll have to mute the non-sounding strings, maybe finger-pick. I use those kinds of chords when I want to have particular inversions and voice-leading for the bass, and/or a specific highest note. But then it's only for a specific moment in that specific bass/harmony/melody motion.
Which styles use that... "fingerstyle" maybe? I think fingerstyle guitarists seem to be more careful about inversions than players of some other styles. :)
Comment: It's in a 70s rock song ("This is the one", from Thin Lizzy); one guitar does power chords and the other one plays the same chords, but in a higher register. I saw a video with that shape and I have been intrigued by it


Menu Management

Question: I am trying to make menu management easy for my clients in Drupal 7.

How can I make it so that clients can move links on the menu but cannot delete the top level menu? For example, if the top level menu item is "Products", how can I make it so that the clients cannot delete the menu item "Products" (and even the node itself) but they can reorder the children?
Let's say I have a main menu item called "Products" and under it I have "Phones". How can I make it so that if a node "Phones" has children under it on the menu, that it can not be deleted. Because right now, if the client deletes "Phones", all of its menu children are automatically moved up to the same level that the other product categories were on i.e. "Televisions", "Computers", etc.
Comment: You can create a menu without to create a node. Drupal gives you the possibility of creating a menu item while creating a node, but those "entities" are not related to each other.
Comment: Hello JM01, and welcome on _Drupal Answers_. You tagged this question with _nodes_, but I don't understand which is the relationship between the menu you are describing, and nodes. May you explain that in your question?
Comment: When I add a basic page, it creates a node. I have the option to "Provide a menu link" under "Menu Settings" when I edit the node. I can also delete the node, and that is where the trouble begins with the menu.
Answer: If using Drupal 6 is a possibility, these 2 modules would help:
Menu Parent
Menu Admin per Menu
Comment: Menu Admin per Menu is a step in the right direction because it restricts access to only certain menus. However, the client can still move top level menu items around which can cause major problems with the CSS, main navigation, and breadcrumbs.
Answer: From what little I know, I think this is tricky to do in Drupal 7. It does look like there is some work going on with the workbench access module to allow better integration for menus: http://drupal.org/node/1101638.
Some other things to explore might be the book module (comes with drupal core), or even fudging with different content types (maybe make one for "landing pages" which the editor cannot delete, and one for "sub-page" which they can delete... I have never tried this though). Also potentially organic groups with organic groups menu (this, as a lot of modules is in dev, and I'm not sure how well it works).
Let us know if you come to a solution, I would be interested in knowing as well.

Menu Management