text:
Q: Override require() behavior in node I'm looking to create a permission-based plugin system for a project in Node. For ease of writing, and for other reasons, I'd like to allow myself to call a plugin with:
var plugin = require('plugin');
Here's the trick, I want to force plugin to use my permissions api system, but I want the plugin writer to be able to do something like:
var library = require('library');
What this would require, is the ability to create my own require() method, and pass it to the plugin/module so they are using my method without any more work. My method would (primitively) work like this:

    function myRequire (module) {
      if(meetsPermissions) return require(module);
      throw 'You don't have the necessary permissions;
    }

Is this possible in Node?

A: You can override the default loader in require.extensions. However, this is deprecated so it might be removed from Node.js at any time.
For example:
var jsloader = require.extensions['.js'];

require.extensions['.js'] = function(module, filename) {
  if (meetsPermissions(module)) return jsloader.apply(this, arguments);
  throw new Error("You don't have the necessary permissions");
};

Some caveats (besides from the deprecation):

*

*this function will be called for all modules (including dependencies-of-dependencies), so meetsPermissions() should be relatively fast

*it doesn't seem to get called for built-in modules (util, http, etc)

Another possible solution could be running all the code in a sandbox using the vm module. There are various higher-level modules that offer this, like node-sandboxed-module.


text:
Q: 'Named' slave the same as having forwarders? I have a slave DNS server that dumped a bunch of...
" error (unexpected RCODE REFUSED) resolving 'xxx.xxx.xxx.xxx.in-addr.arpa/PTR/IN'"

messages all the sudden, and DNS lookups to the slave server did not respond.
From what I can tell this is generally due to having forwarders in the configuration file that refused to respond.
However I do not have any forwarders in my configuration file, but it is configured as a slave DNS server for my zone.
The odd thing is, a restart of the slave DNS server fixed the issue and I no longer got those errors, no action was taken on the upstream master.
Any thoughts on what may have caused this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Establecer valor de movimiento arduino RAMPS Estoy haciendo un proyecto con arduino mega, ramps y Marlin____ y quiero que cuando por consola serie le mando una A0 se mueva a un lugar concreto. Pero no quiero mandarle los datos mediante la consola serie, sino que quiero que se almacenen en el código. Es decir, en lugar de ponerle G0 X200 quiero poner A0 y que el programa sepa que es G0 X200. Y que al poner A1 el programa sepa que es G0 X220.
He intentando modificar el buffer en el que se guarda el comando recibido, de forma que si empieza por A, sea G28 Z, pero me da error de compilación.
El siguiente fragmento de código se corresponde con la función process_commads(). No copio todo el código porque son cientos de líneas, pero con esto creo que es suficiente:
if(code_seen('A')){
SERIAL_ECHO(cmdbuffer[bufindr]);
switch((int)code_value())
{
  case 0:

  case 1: // G1
  if(Stopped == false) {
    get_coordinates(); // For X Y Z E F
    prepare_move();
    //ClearToSend();
    return;
  }
  //break;
 }

}
Este fragmento de código funciona correctamente. Lo que hace es que si el comando es A0 o A1, emula el funcionamiento de G0 y G1. Ahora bien, si yo coloco la siguiente línea al inicio de la función process_comands()
cmdbuffer[bufindr]="G28 Z";

No compila, dando el siguiente error:
Marlin_main.cpp: In function 'void process_commands()':
Marlin_main.cpp:1065:21: error: incompatible types in assignment of 'const char [6]' to 'char [96]'

A: Lo conseguí por mi cuenta.
Si alguno tiene curiosidad, lo que hay que hacer es cambiar
cmdbuffer[bufindr]="G28 Z"

por
strncpy(cmdbuffer[bufindr], "G28 Z", sizeof(cmdbuffer[bufindr]));


text:
Q: How to count selected rows in SQL I want to count how many rows are selected from query along with selected data.
SELECT `student`.`student id` AS ID,
    `student unit enrolment`.`session`,
    `student unit enrolment`.`unit code`,
    `units`.`unit name`,
    `workshops`.`campus`,
    `workshops`.`location`,
    CONCAT (
        `teachers`.`first name`,
        " ",
        `teachers`.`last name`
        ) AS Tutor
FROM `student`,
    `student unit enrolment`,
    `units`,
    `workshops`,
    `teachers`
WHERE `student`.`student id` = `student unit enrolment`.`student id`
    AND `student unit enrolment`.`unit code` = `units`.`unit id`
    AND `student unit enrolment`.`unit code` = `workshops`.`unit code`
    AND `workshops`.`teacher id` = `teachers`.`staff id`;

A: Try this:
$result = mysql_query(YOUR_QUERY_HERE);
mysql_num_rows($result);

A: select `student`.`student id` as 'Student ID' , `student unit enrolment`.`session` , `student unit enrolment`.`unit code`
 , `units`.`unit name` , `workshops`.`campus` , `workshops`.`location` , CONCAT(`teachers`.`first name`, " " , `teachers`.`last name`) as Tutor ,

(select count(`student`.`student id`)
from `student` ,  `student unit enrolment` , `units` , `workshops` , `teachers`
where `student`.`student id` = `student unit enrolment`.`student id` and `student unit enrolment`.`unit code` =  `units`.`unit id`
and `student unit enrolment`.`unit code` =  `workshops`.`unit code`
and `workshops`.`teacher id` = `teachers`.`staff id`
and `student unit enrolment`.`Year` = '2014') as 'Total count of students'

from `student` ,  `student unit enrolment` , `units` , `workshops` , `teachers`
where `student`.`student id` = `student unit enrolment`.`student id`
and `student unit enrolment`.`unit code` =  `units`.`unit id`
and `student unit enrolment`.`unit code` =  `workshops`.`unit code`
and `workshops`.`teacher id` = `teachers`.`staff id`
and  `student unit enrolment`.`Year` = '2014'

Order by `student unit enrolment`.`session` , `student unit enrolment`.`unit code` , `workshops`.`location` , `workshops`.`class times`


text:
Q: Start Autocad and run VBA automatically with .bat files I have the following problem. I have an app that retrieves dwg files from a specific network location. Once retrieved i have written some vba commands that retrieve those files and do some operations on them.
I want to be able to automate this whole procedure with a .bat file.
Start .net -> finish .net -> start Autocad.
And again for the second program.
For one app this works great. I have used this VBA run on startup.
But this limits me to one since the programs will start at different times and start the same instance of vba.
These two programs will run on the same computer and will run as services.
The simpler way that i found to start autocad with .net is through a bat file.
Is there some way to automate some commands with the bat file or whatever.
For example the 2 script might look sth like this inside a bat file.
"C:\Program Files\Autodesk\AutoCAD 20XX\acad.exe" with firstListOfCommands.scr

"C:\Program Files\Autodesk\AutoCAD 20XX\acad.exe" with secondListOfCommands.scr

Do you have any suggestions on how can i achieve this?

A: The command line switch to specify a script for AutoCAD to run on opening is /b.
"C:\Program Files\Autodesk\AutoCAD 20XX\acad.exe /b firstListOfCommands.scr"
Reference:
http://help.autodesk.com/view/ACD/2016/ENU/?guid=GUID-8E54B6EC-5B52-4F62-B7FC-0D4E1EDF093A


text:
Q: Alexa Skills - Maintain session in the simulator I'm trying to maintain a session in the simulator so that I can chain intents and not have to start each sentences with "tell my skill {something}".
Each time i trigger an Intent, I can see in the output JSON that the session.new is always true.
What do I do wrong ?
Thanks a lot.

A: Make sure that when you send responses, you use a "ask" response instead of a "tell" response.  A tell response will close the session.
With the Java SDK, you can create an ask response with:
SpeechletResponse.newAskResponse(speech, reprompt, card);

Whereas the tell response is created with:
SpeechletResponse.newTellResponse(speech, card);

A: In node.js I realized that you do need the "repompt" part to keep the session attributes :
handlerInput.responseBuilder
                .speak(speechText)
                .reprompt(speechText)
                .withSimpleCard('Hello World', speechText)
                .getResponse();


text:
Q: Dynamic Table with HTML, Javascript, and PHP? Based on this project , I want to modify this js function with my own table. Focus at this code
$("#employee_table tr:last").after("
<input type='text' name='name[]' placeholder='Enter Name'>	<input type='text' name='age[]' placeholder='Enter Age'>	<input type='text' name='job[]' placeholder='Enter Job'>	<input type='button' value='DELETE' onclick=delete_row('row"+$rowno+"')>
");

When I try to modify that code to this :
 $("#employee_table tr:last").after("

    input type='text' name='name[]' placeholder='Enter Name'>
    <input type='text' name='age[]' placeholder='Enter Age'>	   <input type='text' name='job[]' placeholder='Enter Job'>
    <input type='button' value='DELETE' onclick=delete_row('row"+$rowno+"')>
");

It's not work. If I can modify and work, then I can try for my own table code.
If I can seperate each of , I can modify my table code :

HISTORY OF OWNERSHIP

                      No
                      Owner
                      Remarks
                      Action

            <?php
            $no = 0;
            $no++;
            ?>
            <input style="width: 150px;max-height: 30px;text-align: center"  class="form-control" type="text" name="no_history[]" value = "<?php echo $no ?>" readonly/>

            <select type="text" name="owner2[]" class="form-control" style="text-align: center;font-size: 10px;max-height: 35px">
            <option value="-">-</option>
            <?php
            $sqlowner = "SELECT * FROM owner ORDER BY owner ASC";
            $hasilowner = mysqli_query($connect2,$sqlowner);
            while ($rowowner = mysqli_fetch_array($hasilowner,MYSQLI_ASSOC))
            {
                $owner = $rowowner['owner'];
            ?>
            <option value="<?php echo $owner?>"><?php echo $owner?></option>
             <?php
                            }
                            ?>
                            </select>

            <input style="width: 150px;max-height: 30px;text-align: center"  class="form-control" type="text" name="remarks[]" onkeyup="this.value = this.value.toUpperCase()" style="text-transform:uppercase"/>

            <input type="button" onclick="add_row();" value="ADD ROW" class="btn btn-primary">

A: Firstly, there is missing syntax's in your code where you are trying to insert. Secondly, you can use back-ticks when your string goes more tha

var $rowno = 0;

function add_row() {
  $("#add_history tr:last").after(`

    <input type='text' name='name[]' placeholder='Enter Name'>
    <input type='text' name='age[]' placeholder='Enter Age'>
    <input type='text' name='job[]' placeholder='Enter Job'>
    <input type='button' value='DELETE' onclick=delete_row('row${$rowno}')>

 `);
  $rowno++;
}

      No
      Owner
      Remarks
      Action

    <input style="width: 150px;max-height: 30px;text-align: center" class="form-control" type="text" name="no_history[]" value="" readonly/>

    <input style="width: 150px;max-height: 30px;text-align: center" class="form-control" type="text" name="remarks[]" onkeyup="this.value = this.value.toUpperCase()" style="text-transform:uppercase" />

      <input type="button" onclick="add_row();" value="ADD ROW" class="btn btn-primary">


text:
Q: Ubuntu 15.04. fills up root partition automatically quite quickly! I have got a funny but bad problem. The root partition is filling up quickly and automatically. I can see that there is a continous read and write process on this partion. But I cannot stop it.
It is that worse, so I have to move large amount of data from the root partition to another partition. Is this a virus? I have barley any network traffic, which makes me think that this is no virus/trojan horse or something else.
I get the message regularly that there are 0 bytes free on the root partition.
I did sudo apt-get clean and autoclean commands often and delete temporary files I do not need. Swap partition is 247 MB and it is steadly growing.
I used df -h command several times and can that root partition is getting full of data, wich data is copying there from where?
I had to do some partitioning work with gparted, did I do anything wrong?
I have never faced such a problem before.

A: I have the same problem too.
And I also identified where all the disk space is going:
du -hs /var/lib/apt/lists/partial
152G    /var/lib/apt/lists/partial
It seems that there is a bug in apt: https://bugs.launchpad.net/ubuntu/+source/apt/+bug/1445239
And, the fix for it is manually installing apt 1.0.9.10 from here: https://launchpad.net/ubuntu/+source/apt/1.0.9.10ubuntu1/+build/7460103
Just install apt and libapt-pkg4.12

A: Install Baobab a.k.a. Disk Space Analyzer and drill down to find where the files are created. Most likely it's some process creating tons of files or continuously writing to a temp file


text:
Q: How to handle routing request "john.myexample.com" in ASP.NET Core Suppose my application URL is myexample.com, myexample.com has user john he has a public profile link john.myexample.com how to handle such types of request in ASP.NET Core application and map to the UserController which has action Profile takes username as an argument and returns Johns profile.
routes.MapRoute(
                name: "user_profile",
                template: "{controller=User}/{action=Profile}/{username}");

A: Built-in ASP.NET Core Routing does not provide any template for request subdomain. That's why you need to implement custom router to cover such scenario.
The implementation will be pretty straightforward. You should parse hostname of incoming request to check whether it's a profile subdomain. If so, you fill controller, action and username in route data.
Here is a working sample:
Router implementation:
public class SubdomainRouter : IRouter
{
    private readonly Regex hostRegex = new Regex(@"^(.+?)\.(.+)$", RegexOptions.Compiled);

    private readonly IRouter defaultRouter;
    private readonly string domain;
    private readonly string controllerName;
    private readonly string actionName;

    public SubdomainRouter(IRouter defaultRouter, string domain, string controllerName, string actionName)
    {
        this.defaultRouter = defaultRouter;
        this.domain = domain;
        this.controllerName = controllerName;
        this.actionName = actionName;
    }

    public async Task RouteAsync(RouteContext context)
    {
        var request = context.HttpContext.Request;
        var hostname = request.Host.Host;

        var match = hostRegex.Match(hostname);
        if (match.Success && String.Equals(match.Groups[2].Value, domain, StringComparison.OrdinalIgnoreCase))
        {
            var routeData = new RouteData();
            routeData.Values["controller"] = controllerName;
            routeData.Values["action"] = actionName;
            routeData.Values["username"] = match.Groups[1].Value;

            context.RouteData = routeData;
            await defaultRouter.RouteAsync(context);
        }
    }

    public VirtualPathData GetVirtualPath(VirtualPathContext context)
    {
        return defaultRouter.GetVirtualPath(context);
    }
}

Registration in Startup.Configure():
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMvc(routes =>
    {
        routes.Routes.Add(new SubdomainRouter(routes.DefaultHandler, "myexample.com", "User", "Profile"));

        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

Sample Controller:
public class UserController : Controller
{
    [HttpGet]
    public IActionResult Profile(string username)
    {
        return Ok();
    }
}

Sample Project on GitHub
UPDATE (using a route for localhost in development environment)
You have two options for using such route for localhost in development environment:

*

*The first one fully emulates subdomain URLs like in production environment. To make it work you should configure your hosts file so that john.myexample.com point to 127.0.0.1 and make your ASP.NET Core Application to accept requests for such host. In this case you don't need any additional adjustments in the routing since the requests will have the same URLs as in production (just the port is added): http://john.myexample.com:12345/.

*If you want to keep things simple and use usual development URLs pointing to localhost, you should bypass described SubdomainRouter (because it parses for subdomain which will not work for localhost) and use usual ASP.NET Core routing. Here is adjusted routing configuration for this case:
app.UseMvc(routes =>
{
    if (env.IsDevelopment())
    {
        routes.MapRoute(
            name: "user-profile",
            template: "profiles/{username}",
            defaults: new { controller = "User", action = "Profile" });
    }
    else
    {
        routes.Routes.Add(new SubdomainRouter(routes.DefaultHandler, "myexample.com", "User", "Profile"));
    }

    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

Now if you send request to URL like http://localhost:12345/profiles/john, UserController.Profile action will be called with the correct user name.


text:
Q: How to get the same MenuItem Behaviour in a customView I want to have an Icon on a custom view (not on the toolbar) that when clicked have the same dropdown list as the menuItem click.
Any thoughts how to do this ?

A: Create One xml File Inside res->menu say popup.xml or any name what you want
Like below
<?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/menu1"
        android:icon="@android:drawable/ic_menu_search"
        android:title="menuItem1"
       />
    <item
        android:id="@+id/menu2"
        android:icon="@android:drawable/ic_menu_search"
        android:title="menuItem2"/>

</menu>

then in your activty, on Click of you action bar object call this code below
PopupMenu popup = new PopupMenu(this, view);
        popup.getMenuInflater().inflate(R.menu.popup, popup.getMenu());

        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getTitle().equals("menuItem1")) {
                    // handle MenuItem1
                } else if (item.getTitle().equals("menuItem2")) {
                    // handle MenuItem2
                }
                //......
                return true;
            }
        });

        popup.show();

A: you can try using dropdown spinners. you can use that in any where.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:padding="10dip"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content">

   <TextView
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_marginTop="10dip"
      android:text="Category:"
      android:layout_marginBottom="5dp"/>

   <Spinner
      android:id="@+id/spinner"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:prompt="@string/spinner_title"/>

</LinearLayout>

MainActivity.class
package com.example.spinner;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

class MainActivity extends Activity implements OnItemSelectedListener{
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      // Spinner element
      Spinner spinner = (Spinner) findViewById(R.id.spinner);

      // Spinner click listener
      spinner.setOnItemSelectedListener(this);

      // Spinner Drop down elements
      List<String> categories = new ArrayList<String>();
      categories.add("Automobile");
      categories.add("Business Services");
      categories.add("Computers");
      categories.add("Education");
      categories.add("Personal");
      categories.add("Travel");

      // Creating adapter for spinner
      ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);

      // Drop down layout style - list view with radio button
      dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

      // attaching data adapter to spinner
      spinner.setAdapter(dataAdapter);
   }

   @Override
   public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
      // On selecting a spinner item
      String item = parent.getItemAtPosition(position).toString();

      // Showing selected spinner item
      Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
   }
   public void onNothingSelected(AdapterView<?> arg0) {
      // TODO Auto-generated method stub
   }
}

If this answer helped you please do not forget to accept :)
Thanks


text:
Q: Unable to display error message for cakephp3 bootstrap-ui
*

*[x] bug

*BootstrapUI Version: v0.5.0

*Bootstrap Framework Version: v3.3.6

*jQuery: 3.0.0-rc1

*Platform and Target: Google Chrome, Apache

What you did
App\View
    namespace App\View;
use Cake\View\View;
use BootstrapUI\View\UIViewTrait;

class AppView extends View
{
    use UIViewTrait;

    /**
     * Initialization hook method.
     */
    public function initialize()
    {
        //render the initializeUI method from the UIViewTrait
        $this->initializeUI();
        $this->layout('default');
    }
}

controller/create function
$student = $this->Students->newEntity($data['Students']);
if (!$this->Students->save($student)) {
    $isOkay = false;
    debug($student);
}

create.ctp
<?php echo $this->Form->create(null, ['align' => [
   'sm' => [
       'left' => 4,
       'middle' => 8,
       'right' => 12
   ],
   'md' => [
       'left' => 2,
       'middle' => 6,
       'right' => 4
   ]

], 'id' => 'myform']); ?>

<fieldset id="page-1">
   <legend>Student Profile</legend>

   <?php
       echo $this->Form->input('Students.name', [
           'label' => 'Full name'
       ]);
   ?>
</fieldset>

<button class="btn btn-primary" type="submit">Save</button>
<?php echo $this->Form->end(); ?>

StudentsTable.php
public function validationDefault(Validator $validator) {
  $validator
    - > integer('id') - > allowEmpty('id', 'create');

  $validator
    - > notEmpty('name', 'Username must input.');
}

Expected Behavior
I expect I will getting error block beside the field.
Actual Behavior
The error message is missing from page, but I can found it in controller.

A: You need to pass the $student variable from controller to view create.ctp. Also you need to pass $student variable into the form you want to display errors. In you case it will be:
$this->Form->create($student, ['align' => [...
Note: in both case $student variable should be an entity of StudentsTable.php.


text:
Q: how to make the bxslider goToSlide function not animate - just jump/appear on slide? I am using the bxslider which in my option is a pretty awesome jquery slider plugin as far as sliders go.
http://bxslider.com/
I using the goToSlide(); function.
bxslider.goToSlide(slide);

I am trying to get goToSlide to jump to the slide - instead of animating.
Can someone help? I made a fiddle...
http://jsfiddle.net/dHxAJ/1/

Thanks in advance!

A: just override css transitions to resolve this
full answer here
How to move to the next slide without animation for BxSlider?

A: There is a much easier way to jump to a slide without animating:
$('.slidejump-2').on('click', function(e) {
  slider.reloadSlider({
    startSlide:1,
  });
});

Or for your example:
JumpToSlide = function (slideNumber) {

        var slide = slideNumber - 1;

        bxslider.reloadSlider({
          startSlide:slide,
          pager: false,
            auto: false
        });

    };

This reloads the slider and sets the start frame to whatever you choose.
Forked fiddle is here


text:
Q: Confusion with flux and Lenz's law in an LC tank circuit Below is an LC tank circuit and its V I plots:

I marked the points in red on the plots.
As far as I understand, at point a the capacitor is fully charged and the current is zero. At point b the current reaches to maximum and the voltage goes to zero(point y).
1-) Can we say that at point b, the net magnetic flux through the inductor is maximum?
2-) Here is my real confusion: According to Lenz's law the inductor should create a magnetic field which opposes the magnetic field rate through it. But in this case the magnetic field already is created by the coil it is not external. So does the Lenz law apply here? What can we say about the flux created by the current and the opposing magnetic flux?
Between the point a and b the current increases. Does that mean the net flux increases? What about the opposing flux? Is that in opposite direction?

A:
Can we say that at point b, the net magnetic flux through the inductor is maximum?

Yes

But in this case the magnetic field already is created by the coil it is not external. So does the Lenz law apply here?

Lenz Law does not state that the magnetic field should be external. In fact any change in the magnetic field will give rise to EMF which will try to oppose the change in magnetic field. This is actually how an inductor works, if the current through the inductor changes it will create a potential difference across its ends which would try to oppose the increase in current and hence increase in the magnetic flux (due to its own current) through the inductor coils or vice versa.
In fact this is what is called self inductance, that is, opposing the change in current due to its own magnetic flux. There is another type of inductance called mutual inductance which comes into play when there are two or more coils which couple their magnetic fields. In this case (in addition voltage due to self inductance) there will be additional potential difference to oppose the changing magnetic fields of the nearby coils.


text:
Q: sql full text search on specific rows I am building a web site. I am using sql to store my data. Can I use full text search on specific rows (dynamically determined by user preferences)?
Meaning I want to use the 'where' clause right before I free text search.

A: No, you cannot select a subset of your rows before running a full-text query on it. If you take a look at the query plan generated you will see that the full-text execution is at the bottom of the tree with results being filtered up to the WHERE clause.
Since the row selection is 'dynamically determined' creating a ft-index on a view of the table doesn't seem to be an option either.


text:
Q: Checking File Checksum In Alpine I got this curious problem with Alpine. I want to check the checksum of a file inside a bash console. It works under CentOS but not under Alpine. Where is the error?
Under CentOS
$ sha1sum /bin/tini
fa23d1e20732501c3bb8eeeca423c89ac80ed452  /bin/tini
$ echo "fa23d1e20732501c3bb8eeeca423c89ac80ed452 /bin/tini" | sha1sum -c -
/bin/tini: OK

Under Alpine
$ sha1sum /bin/tini
fa23d1e20732501c3bb8eeeca423c89ac80ed452  /bin/tini
$ echo "fa23d1e20732501c3bb8eeeca423c89ac80ed452 /bin/tini" | sha1sum -c -
sha1sum: WARNING: 1 of 1 computed checksums did NOT match

A: Could you try adding 1 space (total 2) between the checksum and the path:
$ echo "fa23d1e20732501c3bb8eeeca423c89ac80ed452  /bin/tini" | sha1sum -c -

I've tried with /bin/busybox:
# sha1sum /bin/busybox
71bdaf6e52759f7f277c89b694c494f472ca2dfb  /bin/busybox
# echo '71bdaf6e52759f7f277c89b694c494f472ca2dfb /bin/busybox' | sha1sum -c -
sha1sum: WARNING: 1 of 1 computed checksums did NOT match
# echo '71bdaf6e52759f7f277c89b694c494f472ca2dfb  /bin/busybox' | sha1sum -c -
/bin/busybox: OK

The error is because sha1sum expects its own output as input when called with -c and its output uses 2 spaces.

A: I had this issue while installing kubectl on Alpine Linux v3.13:
echo "$(<kubectl.sha256) kubectl" | sha256sum -c
sha256sum: WARNING: 1 of 1 computed checksums did NOT match

My two-part fix:

*

*the default shell (ash) responds to echo "$(<file.txt)" with an empty new line whereas bash responds with the contents of the file (expected behavior).

*Alpine's version of sha256sum wants two spaces between the hash and the file name (Ubuntu accepts one space).

bash
echo "$(<kubectl.sha256)  kubectl" | sha256sum -c
kubectl: OK


text:
Q: If $d_{n} = \frac{{\beta}_{n}}{10^n}$ where ${\beta}_{n}$ takes integer values between 0 and 9, does $\sum_{n=1}^{\infty}d_{n}$ converge? The series looks like a converging geometric series: $$\sum_{n=1}^{\infty}\frac{1}{10^n} = \sum_{n=0}^{\infty}\frac{1}{10^n} - 1 = \frac{1}{9}$$ Where the terms are being arbitrarily multiplied by constants between $0$ and $9$. I'm not sure about how this affects the convergence of a series. I suspect that it converges because the constants eventually become small in comparison to the value of the geometric terms, but I'm not sure how I could prove it.
The "worst case" would be one where $\beta_{n} = 9$ for all $n$. In that case:
$$\sum_{n=1}^{\infty}d_{n} = 9\sum_{n=1}^{\infty}\frac{1}{10^n} = 1$$
So again I'm inclined to think it converges in any case.
Thanks.

A: The argument you give is fine. You can also use the root test. Whatever the $\beta_i$ are, the $n$-th root just kills the root in the denominator and you have $$\limsup \frac{\sqrt[n]{\beta_n}}{10} \leq \lim_{n\to \infty} \frac{\sqrt[n]{9}}{10} \leq \frac{9}{10}< 1$$ clearly, which implies absolute convergence.


text:
Q: Combine Flot with Zepto Is one able to use Zepto with Flot and how?
I know Flot works fine with jQuery (tested), but Zepto just feels faster and smoother, than jQuery on mobile devices

A: I tried it and ran into two problems.  First, flot looks for jQuery to be defined and second, flot uses outerWidth which zepto doesn't replicate.
So, let's give it a little love and work around these problems:

<!DOCTYPE html>


text:
Q: Why Restsharp request object won't be renewed in every call This is my RestClientService :
public class RestClientService : IRestClientService
{
    protected readonly RestClient _restClient;
    protected readonly RestRequest _restRequest;

    public RestClientService()
    {
        _restClient = new RestClient();
        _restRequest = new RestRequest();
    }

    public async Task<MessageDTO> SendComment(Websites website, Comment comment, int postId)
    {
        if (await IsPostExist(postId,website))
        {
            _restClient.Options.BaseUrl = new Uri($"{website.Url}/wp-json/wp/v2/comments/");
            _restRequest.Method = Method.Post;
            _restRequest.RequestFormat = DataFormat.Json;
            _restRequest.AddJsonBody(new
            {
                post = postId,
                author_name = comment.Author,
                content = comment.Body
            });
            var result = await _restClient.ExecuteAsync(_restRequest);
            return new MessageDTO
            {
                Message = result.Content,
                Status = result.StatusCode.ToString()
            };
        }

        return new MessageDTO
        {
            Message = "Post Not Found",
            Status = "404"

        };
    }
}

I have a list of comments and list of products that I iterate over them and call SendComment method from RestClientService class. The problem is in first time SendComment method called _restRequest object will be get JsonBody and everything is okay but next time this method calls in loop _restRequest object has old data and won't be renewed.
In DI Container I added (Transient) RestClientService
builder.Services.AddTransient<IRestClientService,RestClientService>();

Here is where I used SendComment method in another service.
public async Task<MessageDTO> CreateSendCommentJob(SendCommentConfiguration config)
    {
        var updatedConfig = await _sendCommentConfigurationRepository.Get(config.Id);
        var ConfigDetails = JsonConvert.DeserializeObject<SendCommentConfigurationDetailsDTO>(updatedConfig.Configuration);
        var mappedWebsite = _mapper.Map<Websites>(ConfigDetails.WebsiteInfo);

        if (ConfigDetails.CommentType == "blog")
        {
            var comments = await _uCommentService.GetCommentsByGroupId(ConfigDetails.CommentGroupId);
            var commentCount = 0;

            for (int postCount = 0; postCount < ConfigDetails.ProductPerSendCount; postCount++)
            {
                var postId = ConfigDetails.Ids[postCount];

                    while (commentCount < ConfigDetails.CommentsPerProductCount)
                    {
                        var random = new Random();
                        var index = random.Next(comments.Count);

                        var result = await _restClientService.SendComment(mappedWebsite, comments[index], postId);

                        if (result.Status == "Created")
                        {
                            Console.WriteLine($"Comment Index ({index}) at Id ({postId}) submited successfuly...");
                            commentCount++;
                        }
                        else
                        {
                            Console.WriteLine($"{postId} - {result.Status} - {result.Message}");

                        }
                    }
                ConfigDetails.Ids.Remove(postId);
                commentCount = 0;
            }

        }

        var newConfig = new SendCommentConfiguration
        {
            Id = config.Id,
            Configuration = JsonConvert.SerializeObject(ConfigDetails)
        };

        await _sendCommentConfigurationRepository.Edit(newConfig);

        return new MessageDTO
        {
            Status = "200",
            Message = "Comments Successfuly Sent "
        };
    }

A: _restClientService.SendComment is called in a loop on the same service instance. As the request instance is a field of the service instance, the same request instance is reused for each call.
As each apple performs a distinct request, each request must use a distinct instance of RestRequest, like :
public class RestClientService : IRestClientService
{
    public async Task<MessageDTO> SendComment(Websites website, Comment comment, int postId)
    {
        if (await IsPostExist(postId,website))
        {
            //Each call, new instances
            var restClient = new RestClient();
            var restRequest = new RestRequest();

            restClient.Options.BaseUrl = new Uri($"{website.Url}/wp-json/wp/v2/comments/");
            restRequest.Method = Method.Post;
            restRequest.RequestFormat = DataFormat.Json;
            restRequest.AddJsonBody(new
            {
                post = postId,
                author_name = comment.Author,
                content = comment.Body
            });
            var result = await restClient.ExecuteAsync(_restRequest);
            return new MessageDTO
            {
                Message = result.Content,
                Status = result.StatusCode.ToString()
            };
        }

        return new MessageDTO
        {
            Message = "Post Not Found",
            Status = "404"
        };
    }
}


text:
Q: HTML button only uses width and height of text in the button I have a small problem. I am trying to change the width and height of a button but for some reason, it will not let me. The button automatically stays the same width and height as the contained text.
CSS
.flexcontainer {
display: flex;
align-items: center;
overflow: hidden;
}

img[width="500"] {
border: 3px solid #5F5F5F;
border-radius:3px;
float: left;
}

#leftRetail {
display: block;
height:354px;
width: 1308px;
float:right;
text-align: center;
vertical-align: middle;
line-height: 354px;
}

.button {
width: 250px;
height: 200px;
background: #ed2626;
border-radius: 2px;
color: white;
font-weight: bold;
text-decoration:none;
}

HTML

                Retail Menu

A: You need to change your .button to use display: block or inline-block:
.button {
display: block;
width: 250px;
height: 200px;
background: #ed2626;
border-radius: 2px;
color: white;
font-weight: bold;
text-decoration:none;
}

A: CHANGED ANSWER after copying the original code into a snippet:
I just realized that the whole thing is inside a flex container, which makes all child elements flex items automatically. (BTW: The float parameters have no effect in this case)
So, one method to add width and height to your .button is to give it some padding, as shown below:

.flexcontainer {
  display: flex;
  align-items: center;
  overflow: hidden;
}

img[width="500"] {
  border: 3px solid #5F5F5F;
  border-radius: 3px;
}

#leftRetail {
  height: 354px;
  width: 1308px;
  text-align: center;
  vertical-align: middle;
  line-height: 354px;
}

.button {
  background: #ed2626;
  border-radius: 2px;
  color: white;
  font-weight: bold;
  text-decoration: none;
  padding: 8px 12px;
}

    Retail Menu

A: You cannot modify the width and height of inline elements, manually.
Add display: block; (or inline-block) to your .button block, and you can observe that the height and width changes are you define it.
Only block elements may have their width and height set specifically.
Your button should now look like:
.button {
width: 250px;
height: 200px;
background: #ed2626;
border-radius: 2px;
color: white;
font-weight: bold;
text-decoration:none;
display: block;
}

A: Just make it block-level element by adding display:bock to its style. Then you can apply whatever style you want!


text:
Q: How do I ping the right bob?
We have two bobs at the moment. Bob (with the fox avatar) is a long time user, and bob, with the green avatar.
I'd like to ping Bob, without bothering bob with my pings. I see two ways to do this - It's trivial for me to get the username - so could we have a way to ping a user by user id number, the same way I'd do a superping as a mod? Alternatively, is there some way (case sensitivity? Letting me click on a user?) where I can pick one of the bobs?
For the moment I'm replying to the appropriate (B|b)ob but this might get messy if I wanted to actually initiate a conversation.


text:
Q: How to get the prev/next array string in Angular What I have:Now in my program, there is a previous and next button, whenever I click the button the {{departmentID}} in array will +1 or -1.
For example, the current {{departmentName}} ,{{departmentID}} is Node,2, after I click Next button the result will become Node,3.(Only the ID itself is change)
What I want : When I click the Next button the result will change from Node,2 >> Ruby,3 which is from 2nd array to 3rd array.
What I tried:Directly +1 in let previousName = this.departmentName+1;but surely it wont work because string cant +1 like that and I get null value.
Department Array
departments = [
    {"id":1,"name":"Angular"},
    {"id":2,"name":"Node"},
    {"id":3,"name":"Ruby"},
  ]

HTML:

     you selected department with id = {{departmentName}},{{departmentID}}

 <button (click)="goPrevious()">Previous</button>
   <button (click)="goNext()">Next</button>

export class DepartmentDetailComponent implements OnInit {
  public departmentID;
  public departmentName;

  constructor(private route : ActivatedRoute,private router: Router) { }

  ngOnInit() {
      this.route.paramMap.subscribe((params:ParamMap) => {
        let id = parseInt(params.get('id'));
        let name = params.get('name');

        this.departmentID = id;
        this.departmentName = name;

      });
    }

goPrevious(){
  let previousId = this.departmentID-1;
  let previousName = this.departmentName; // here is the code to change the departmentName when I click previous button.
 this.router.navigate(['/departments-list',previousId]);

}

A:
Convert the string into number in this way

ngOnInit() {
  //let id = parseInt(this.route.snapshot.paramMap.get('id'));
  //this.departmentID = id;
  this.route.paramMap.subscribe((params:ParamMap) => {
  this.id = +params['id'];  // (+) converts string 'id' to a number
    let name = params.get('name');

    this.departmentID = id;
    this.departmentName = name;

  });
}


text:
Q: Error while compiling on a 64-bit machine When I compile my SharePoint 2007 solution on a 64-bit machine in Release mode and the platform set to AnyCPU or x86 I get the following error:
An attempt was made to load an assembly with an incorrect format: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI\Microsoft.Office.Server.Search.dll.
When I use .Net Reflector on Microsoft.Office.Server.Search.dll it says the platform is set to x64. So I change my settings to Release mode and the platform to x64 and get the same error.
The strange thing is when I change Release to debug, It complies. Can anyone explain this?
I would prefer compiling with the settings Release/AnyCPU if its possible. Can anyone give me a push in the right direction?
Thanks
p.s. I also asked the question here: http://social.msdn.microsoft.com/Forums/en-US/netfx64bit/thread/21d14405-ca6f-4503-b416-f56bfb27168b/

A: I too have experienced this same issue, for me it seemed that my changes to the build configuration weren't actually taking. After several attempts at saving, reopening project, choosing build/rebuild, I was able to get it functioning after choosing "Clean" from the build options.


text:
Q: Guava: transform an List> to List keeping just present values Is there an elegant way of using Guava to transform from a list of optionals to a list of present values?
For example, going from
ImmutableList.of(
    Optional.of("Tom"), Optional.<String>absent(), Optional.of("Dick"),
    Optional.of("Harry"), Optional.<String>absent()
)

to a list containing just
["Tom", "Dick", "Harry"]

One approach would be:
List<T> filterPresent(List<Optional<T>> inputs) {
    return FluentIterable.from(inputs)
            .filter(new Predicate<Optional<T>>() {
                @Override
                public boolean apply(Optional<T> optional) {
                    return optional.isPresent();
                }
            }).transform(new Function<Optional<T>, T>() {
                @Override
                public T apply(Optional<T> optional) {
                    return optional.get();
                }
            }).toList();
}

But this is verbose.
Java 8 is not an option, unfortunately.

A: Why not do it in the old-fashioned Java way:
List<T> result = new ArrayList<T>();
for (Optional<T> optional : inputs) {
    if (optional.isPresent()) {
        result.add(optional.get());
    }
}
return result;

A: There's actualy built-in method for this in Guava: presentInstances in Optional:

Returns the value of each present instance from the supplied optionals, in order, skipping over occurrences of absent(). Iterators are unmodifiable and are evaluated lazily.

Example:
List<Optional<String>> optionalNames = ImmutableList.of(
    Optional.of("Tom"), Optional.<String>absent(), Optional.of("Dick"),
    Optional.of("Harry"), Optional.<String>absent());

Iterable<String> presentNames = Optional.presentInstances(optionalNames); // lazy

// copy to List if needed
List<String> presentNamesList = ImmutableList.copyOf(presentNames);
System.out.println(presentNamesList); // ["Tom", "Dick", "Harry"]

A: You could hide the predicate instances behind method calls to make the code more readable:
List<T> filterPresent(List<Optional<T>> inputs) {
    return FluentIterable.from(inputs).filter(present()).transform(value()).toList();
}

static <T> Predicate<Optional<T>> present() {
    return new Predicate<Optional<T>>() {
        @Override
        public boolean apply(Optional<T> optional) {
            return optional.isPresent();
        }
    };
}

static <T> Function<Optional<T>, T> value() {
    return new Function<Optional<T>, T>() {
        @Override
        public T apply(Optional<T> optional) {
            return optional.get();
        }
    };
}

Unfortunately, there is no easier way in the pre-Java-8-life.

A: If you are calling a method in a loop which returns an Optional and you want to create a List of the returned values which are present, then you can use the toSet method on the Optional in conjunction with the addAll method on the List, like so:
List<String> strings = newArrayList();
for (Long id : ids) {
   strings.addAll(getString(id).toSet());
}

This is useful if you want to return a List, rather than an Iterable, which you get from Optional.presentInstances.


text:
Q: Updating a column using choices from other lists I have a list A with a choice column (Choice 1,2,3). And a list B with the same choices column B.
I have also a third list, List C with column A and B which are updated through workflow from the lists A and B respectively.
My problem is: If I go to List A and Choose the choices 1 and 2 which update the column A in list C. And from List B I choose choice 1 which updates the column B in list C.
How could a column in List C be updated containing only choice 2 (choices from column A minus column B)?.
The choices I have are not numbers are text choices.
Using SharePoint 2013 Site and SharePoint Designer workflow 2010.
Thank you!

A: As you are using SharePoint designer workflow 2010, things will become a bit troublesome for 2010 workflow does not have the replace substring in string action. With this action, simply replace the choices from B column with white space in A column and the job is done.
You can get the choice text value in Designer with a lookup,remember to return filed as choices, comma delimited.

Then you will need two dummy columns to hold the text value of A and B column, use a workflow to update Dummy A and Dummy B to get the text value. Make the C column to be a calculated column and use the Replace, Find and len function to find the index of choice in B and replace it with white space. A similar sample:replace text with formula in calculate


text:
Q: Make geolocation call synchronously in javascript Im developing an app based on geolocation, so its mandatory to get the position in the first place, even before the execution of the rest of the app. So, how can I convert this module in a SYNCHRONOUS way????
 var geolocation = (function() {
 'use strict';

   var geoposition;

   var options = {
    maximumAge: 1000,
           timeout: 15000,
          enableHighAccuracy: false
};

function _onSuccess (position) {
    console.log('DEVICE POSITION');
    console.log('LAT: ' + position.coords.latitude + ' - LON: ' +  position.coords.longitude);
    geoposition = position
};

function _onError (error) {
    console.log(error)
};

function _getLocation () {
    navigator.geolocation.getCurrentPosition(
        _onSuccess,
        _onError,
        options
    );
}

return {
    location: _getLocation
}

}());

Thank you very much!

A: Geolocation has to remain asynchronous, but you can achieve what you want by passing in a callback to your module's main function and calling it each in the success and error functions, after they have completed their processing:
var geolocation = (function() {
 'use strict';

   var geoposition;
   var options = {
     maximumAge: 1000,
     timeout: 15000,
     enableHighAccuracy: false
   };

   function _onSuccess (callback, position) {
     console.log('DEVICE POSITION');
     console.log('LAT: ' + position.coords.latitude + ' - LON: ' +  position.coords.longitude);
     geoposition = position
     callback();
   };

   function _onError (callback, error) {
     console.log(error)
     callback();
   };

   function _getLocation (callback) {
     navigator.geolocation.getCurrentPosition(
       _onSuccess.bind(this, callback),
       _onError.bind(this, callback),
       options
     );
   }

  return {
    location: _getLocation
  }

}());

geolocation.location(function () {
  console.log('finished, loading app.');
});

Fiddle

A: I think you should not try to make it synchronously. Just implement some kind of event system for geolocation getter. This way it work asynchronously but geolocation initializes your app or components which requires geolocation.
Here's a dead simple example of how this could work:
var callbacks = [];

var onGeolocationReady = function (callback) {
     callbacks.push(callback);
}

function _onSuccess (position) {
     // iterare through each callback and invoce them
}

// and making component
onGeolocationReady(function () {
    // some code here which requires geolocation
});

I hope this helps.


text:
Q: python, regex to find anchor link html I need a regex in python to find a links html in a larger set of html.
so if I have:

URL Text

I would get back:
URL Text

I'd like to do it with a regex and not beautifulsoup or something similar to that.  Does anyone have a snippet laying around I could use for this?
Thanks

A: Soup is good for you:
>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup('''

...

... URL Text
...

...
''')

There are many arguments you can pass to the findAll method; more here.  The one line below will get you started by returning a list of all links matching some conditions.
>>> soup.findAll(href='#', title='myurl')
[URL Text]

Edit: based on OP's comment, added info included:
So let's say you're interested in only tags within list elements of a certain class
.  You could do something like this:
>>> soup = BeautifulSoup('''

    URL Text
    URL Text2

    URL Text3
''') # just some sample html

>>> for elem in soup.findAll("li", "li_class"):
...   pprint(elem.findAll('a')) # requires `from pprint import pprint`
...
[URL Text,
 URL Text2]

Soup recipe:

*

*Download the one file required.

*Place dl'd file in site-packages dir or similar.

*Enjoy your soup.

A: you really shouldn't use regexes to parse html.. ever.
try beautifulsoup or lxml.
but... you asked.
so a quick and naive version might look like this:
import re

html = """

URL Text

"""

m = re.search('()', html)
if m:
    print m.group(1)

I can think of a lot of ways this would break.

A: you can try this since your requirement is simple. No need BeautifulSoup or regex
>>> s="""
...

...

... URL Text
...

...

... """
>>> for item in s.split(""):
...    if "<a href=" in item :
...        print item [ item.find("<a href=") : ] + ""
...
URL Text

You can include a check of '
' in the if statement as desired.


text:
Q: Problem with installing champions of regnum on ubuntu 17.10 I was trying to install Champions of Regnum, I downloaded the linux installer 64bit, changed the permissions and executed it. But after it was done installing, I got it in the softwares and on the desktop, but neither of which would open when double clicked.
So I tried reusing the installer through the terminal and after it was finished I got the following error message.
/usr/local/regnum/rolauncher: error while loading shared libraries: libpng12.so.0: cannot open shared object file: No such file or directory

A: Manually downloading libpng12-0 from this site and installing it worked for me.
I also had a problem with libjpeg, which was solved installing sudo apt install libjpeg62. And then I had to run the launcher using sudo /usr/local/... to avoid a warning.


text:
Q: Replacing a substring with values from an array in PHP I am trying to write a JSON file using arrays. Originally, the file was used to create a colorbook.js file on the server and then a manual find and replace to handjam all the values into it. This is the code:
<?php
$colorsperpage = 48; // format is 6 columns by 8 rows
$letters = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K');
$hexValues = array('ECECEC', 'D9D9D9', 'C7C7C7', 'B4B4B4', 'A2A2A2');

$txt = "var color = {\r\n";

for ($i = 0 ; $i < count($letters) ; $i++){
    $pagenum = $i + 1;
    for ( $j = 1; $j <= $colorsperpage; $j++ ){
        if ($j < 10){
            if ($j == $colorsperpage){
                $txt .= "\t\"" . $letters[$i] . $pagenum . "-" . "0" . $j . "\"  :  \"rgba(255,255,255,1)\"\r\n";
            } else {
                $txt .= "\t\"" . $letters[$i] . $pagenum . "-" . "0" . $j . "\"  :  \"rgba(255,255,255,1)\",\r\n";
            }
        } else {
            if ($j == $colorsperpage){
                $txt .= "\t\"" . $letters[$i] . $pagenum . "-" . $j . "\"  :  \"rgba(255,255,255,1)\"\r\n";
            } else {
                $txt .= "\t\"" . $letters[$i] . $pagenum . "-" . $j . "\"  :  \"rgba(255,255,255,1)\",\r\n";
            }

        }
    }
};

$txt .= "};";

foreach ($hexValues as $hex){
    $txt = preg_replace('/rgba(255,255,255,1)/', $hex, $txt, 1);
}
$jsonFile = fopen('colorbook.js', 'w') or die('Unable to open file!');
fwrite($jsonFile, $txt);
fclose($jsonFile);
?>

The original script did write the file correctly(if you remove the foreach loop). I assumed that running preg_replace would go through that string and one at a time replace the hex values. Note that the original array is 528 items; I shortened it for the sake of posting here. One for each of the RGBA entries. Could someone let me know what I'm doing wrong? Thanks.

A: Don't create JSON by hand. Build the array in a loop, and use json_encode() on the final result. You can get the hex codes from the array during the loop, rather than doing hundreds of string replacements afterward.
And to format the array keys, you can use sprintf() to concatenate all the pieces and give a leading zero to $j.
<?php
$result = [];
$color_index = 0;
foreach ($letters as $i => $letter) {
    $pagenum = $i + 1;
    for ($j = 1; $j <= $colorsperpage; $j++) {
        $key = sprintf("%s%d-%02d", $letter, $pagenum, $j);
        $colorcode = $hexValues[$color_index++];
        $result[$key] = $colorcode;
    }
}
file_put_contents("colorbook.js", "var color = " . json_encode($result));


text:
Q: Replacing UseMvc in .Net Core 3.0 I'm trying to figure out how to properly replace app.UseMvc() code that use to be part .net core 2.2. The examples go so far as to tell me what are all the codes I can call but I'm not yet understanding which should I call. For example for my MVC Web Application I have the following:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseStatusCodePagesWithReExecute("/Error/Index");
    app.UseMiddleware<ExceptionHandler>();
    app.UseStaticFiles(new StaticFileOptions()
    {
        OnPrepareResponse = (context) =>
        {
            context.Context.Response.GetTypedHeaders()
                .CacheControl = new CacheControlHeaderValue
            {
                MaxAge = TimeSpan.FromDays(30)
            };
        }
    });

    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
        endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
    });
}

Before I would provide my routing inside the UseMvc() options. However now it seems I have to provide it inside MapControllerRoute But the examples always seem to also call MapRazorPages(). Do I need to call both or am I suppose to call just one? What is the actual difference between the two and how do I setup a default controller and a default action?

A: This is documented in the Migrate from ASP.NET Core 2.2 to 3.0 article. Assuming you want an MVC application.

The following example adds support for controllers, API-related
  features, and views, but not pages.

services
    // more specific than AddMvc()
    .AddControllersWithViews()
    .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)

And in Configure:
    public void Configure(IApplicationBuilder app)
    {
        app.UseStaticFiles();

        app.UseRouting();

        // The equivalent of 'app.UseMvcWithDefaultRoute()'
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();
            // Which is the same as the template
            endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
        });
    }

For the order of use statemtents check the documentation.

A: The easiest way to fix it...
Build a new project targeting the .NET Core that you need and just copy the new Configure method and paste into your project that you are migrating to...
In this example...
Here are the old code lines:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseMvc();
}

And here are the new code lines:
// This method gets called by the runtime. Use this method to configure
the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}


text:
Q: Code won't compile and i don't understand what these errors are for so as the title says my code won't compile i get multiple issues now and before when it was formatted differently it worked to some extent. but now the code completly refuses to run and with my current level of understanding i am unable to figure out the issue but i believe the issue is just the way i've formatted the program so it follows the flowchart.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            // SETUP SESSION
            // Declare variables
            Int32 currentGuess, upperLimit, randomNumber;
            double maxGuesses;
            char playAgain;
            Random random = new Random();

            // WELCOME THE USER
            Console.WriteLine("Welcome to the high/low guessing game.");

            //INITILIZE WIN COUNT AND GAME COUNT

            Int32 gameCount = 0, winCount = 0;

            //DO LOOP #1
            do
            //SETUP GAME
            {
            //REQUEST USER FOR UPPER LIMIT
                Console.WriteLine("Enter Upper range (e.g. 100):");
                upperLimit = Int32.Parse(Console.ReadLine());

                //INITILIZE GUESS COUNT
                Int32 guessCount = 0;
                bool gameOver = false;

                //DETERMINE RANDOM NUMBER
                randomNumber = random.Next(1, upperLimit);
                //DETERMINE MAX GUESSES
                maxGuesses = Math.Ceiling(Math.Log(upperLimit, 2) - 1);

                // INFORM USER RANDOM NUMBER IS CHOSEN AND INDICATE NUMBER OF GUESSES ALLOWED
                Console.WriteLine("I picked a number between 1 and {0} you get {1} chances to guess it", upperLimit, maxGuesses);

            //DO LOOP #2
            do
                            {
                                //PLAY GAME
                               //READ GUESSES
                            Console.WriteLine(string.Format(" Enter Guess {0}: ", guessCount));
                            currentGuess = Int32.Parse(Console.ReadLine());
                            if (currentGuess == randomNumber)
                            {
                                //INCRIMENT WIN COUNT
                                winCount++;
                            }
                            if (currentGuess == randomNumber)
                            {
                                Console.WriteLine("You got it!");
                                gameOver = true;
                                gameCount++;
                            }
                            else if (currentGuess > randomNumber)
                            {
                                Console.WriteLine("Too High");
                            }
                            else if (currentGuess < randomNumber)
                            {
                                Console.WriteLine("Too Low");
                            }

                            } while (guessCount < maxGuesses &&  gameOver == false);

                //POST PROCESSING GAME

                             if (guessCount++ == maxGuesses)
                                        {
                                            //INCRIMENT GAME COUNT
                                            gameCount++;
                                            Console.WriteLine("You lost");
                                            //DISPLAY CORRECT NUMBER IF TOO MANY INCORRECT GUESSES
                                            Console.WriteLine("\nThe number was {0},better luck next time!", randomNumber);
                                            guessCount = 1;

                                 //PROMPT TO PLAY AGAIN

                                           Console.WriteLine("Would you like to play again? (Y/N)");
                                           playAgain = char.Parse (Console.ReadLine());

                                       }
                                           while (playAgain == 'y' ||playAgain == 'Y');

                          // display win count
                         Console.WriteLine("Thanks for playing, you won {0} out of {1} games", winCount, gameCount);
                         Console.ReadLine();
       }
    }
}

A: Two problems:

*

*You are missing a squirly bracket before your last while in your outer do while loop.

*You need to initialize the "playAgain" char when you declare it.

;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
    class Program
    {
         static void Main(string[] args)
         {
            // SETUP SESSION
            // Declare variables
            Int32 currentGuess, upperLimit, randomNumber;
            double maxGuesses;
            char playAgain = 'n';
            Random random = new Random();

            // WELCOME THE USER
            Console.WriteLine("Welcome to the high/low guessing game.");

            //INITILIZE WIN COUNT AND GAME COUNT

            Int32 gameCount = 0, winCount = 0;

            //DO LOOP #1
            do
            //SETUP GAME
            {
                //REQUEST USER FOR UPPER LIMIT
                Console.WriteLine("Enter Upper range (e.g. 100):");
                upperLimit = Int32.Parse(Console.ReadLine());

                //INITILIZE GUESS COUNT
                Int32 guessCount = 0;
                bool gameOver = false;

                //DETERMINE RANDOM NUMBER
                randomNumber = random.Next(1, upperLimit);
                //DETERMINE MAX GUESSES
                maxGuesses = Math.Ceiling(Math.Log(upperLimit, 2) - 1);

                // INFORM USER RANDOM NUMBER IS CHOSEN AND INDICATE NUMBER OF GUESSES ALLOWED
                Console.WriteLine("I picked a number between 1 and {0} you get {1} chances to guess it", upperLimit, maxGuesses);

                //DO LOOP #2
                do
                {
                    //PLAY GAME
                    //READ GUESSES
                    Console.WriteLine(string.Format(" Enter Guess {0}: ", guessCount));
                    currentGuess = Int32.Parse(Console.ReadLine());
                    if (currentGuess == randomNumber)
                    {
                        //INCRIMENT WIN COUNT
                        winCount++;
                    }
                    if (currentGuess == randomNumber)
                    {
                        Console.WriteLine("You got it!");
                        gameOver = true;
                        gameCount++;
                    }
                    else if (currentGuess > randomNumber)
                    {
                        Console.WriteLine("Too High");
                    }
                    else if (currentGuess < randomNumber)
                    {
                        Console.WriteLine("Too Low");
                    }

                } while (guessCount < maxGuesses && gameOver == false);

                //POST PROCESSING GAME

                if (guessCount++ == maxGuesses)
                {
                    //INCRIMENT GAME COUNT
                    gameCount++;
                    Console.WriteLine("You lost");
                    //DISPLAY CORRECT NUMBER IF TOO MANY INCORRECT GUESSES
                    Console.WriteLine("\nThe number was {0},better luck next time!", randomNumber);
                    guessCount = 1;

                    //PROMPT TO PLAY AGAIN

                    Console.WriteLine("Would you like to play again? (Y/N)");
                    playAgain = char.Parse(Console.ReadLine());

                }
            } while (playAgain == 'y' || playAgain == 'Y');

            // display win count
            Console.WriteLine("Thanks for playing, you won {0} out of {1} games", winCount, gameCount);
            Console.ReadLine();
       }
    }
}

A: There were two errors in your program. First, before using a variable it must always be initialized. If you look at the different paths your playAgain variable can take, the value is only set in your if (guessCount++ == maxGuesses) path. If the condition is false, you'll get to the while part without any value. You can change the declaration to
char playAgain = 'n';

The second error was a missing bracket. If you carefully do the indentation, you will see this :
do
{
    //Bunch of code
    if (guessCount++ == maxGuesses)
    {
        //INCRIMENT GAME COUNT
        gameCount++;
        Console.WriteLine("You lost");
        //DISPLAY CORRECT NUMBER IF TOO MANY INCORRECT GUESSES
        Console.WriteLine("\nThe number was {0},better luck next time!", randomNumber);
        guessCount = 1;

        //PROMPT TO PLAY AGAIN

        Console.WriteLine("Would you like to play again? (Y/N)");
        playAgain = char.Parse(Console.ReadLine());

} while (playAgain == 'y' || playAgain == 'Y');

as you can see, you're missing the if bracket, it should be
   playAgain = char.Parse(Console.ReadLine());
   }

} while (playAgain == 'y' || playAgain == 'Y');

Also, there are a LOT of things you could improve. For example, you should place your variable declarations where they are used not at the top of the class. Each comment should be a separate method; it would be way easier for you to follow your flowchart if your Main, instead of being a huge blob of code was something like:
private static void Main(string[] args)
{
    WelcomeTheUser();
    InitializeWinCountAndGameCount();
    Play();
    DisplayWinCount();
}

You could also avoid a ton of misplaced brackets if you keep your functions small.


text:
Q: What is the most efficient way to get a negative lookbehind to work alongisde an optional value? I'm aware negative look-behinds have to be  zero width but I've noticed an issue where they don't work if the preceding token is optional. Why does this happen?
(?<!test):?(\\d{3})

Fails on test123.
But passes test:123
Is there a solution to this other than (?<!test|test:)? I'd rather avoid the above solution as the regex I'd like to apply this to already has a lot of negative look-behind phrases which I'd be doubling.
Edit: I initially posted this using a PCRE editor but I'm coding with ICU

A: With the ICU regex engine, you have an access to a constrained-width lookbehind that allows using limiting quantifiers of known length inside the lookbehinds.
So, use
(?<!test:{0,1})\d{3}
        ^^^^^^

The :{0,1} will match one or zero :.
Note that ICU regex does not work the same as PCRE, you should be aware of the differences when testing in an incompatible environment, such as regex101.com.
Some cool PCRE features that are missing in ICU:

*

*(*SKIP)(*FAIL) verbs

*\K operator

Some cool ICU features missing in PCRE:

*

*Constrained width-lookbehind ((?<!test:{0,1})\d{3})

*Character class intersection ([\p{Letter}&&\p{script=cyrillic}]) or subtraction ([\p{Letter}--\p{script=latin}])


text:
Q: Having trouble with java regex I'm new to regex in Java and am having trouble getting it to work properly. The following code is saying there were no matches found.
pattern = Pattern.compile("EN\\( [ -][0-5]\\)= \\d+.?\\d*E[+-]\\d{2}");
match = pattern.matcher("EN(  0)= 0.000000E+00");
String result = match.group();

As far as I can tell, this should be working. I've been using the Oracle java tutorial on regular expressions to guide me. Any and all help is appreciated.

A: Almost there, you just need:
Matcher match = pattern.matcher("EN(  0)= 0.000000E+00");
match.find(); // <-- missing
String result = match.group();

A: - in [ -] is special character so you must use [ \\-]
Pattern pattern = Pattern.compile("EN\\( [ \\-][0-5]\\)= \\d+.?\\d*E[+\\-]\\d{2}");
Matcher match = pattern.matcher("EN(  0)= 0.000000E+00");
if (match.find())
    System.out.println(match.group());


text:
Q: Handle Future with transform I have a telegram bot on Scala and I want to send the image to the user if it exists and the message "Sorry, the image doesn't exist" if it's not. And I have a function getImage(tag), which returns Future.successful(link) or Future.failed(NoImageException(msg)).
onCommand("/img") { implicit msg =>
  val tag = msg.text.get.drop("/img ".length)
  try {
    if (tag.isEmpty) throw new IndexOutOfBoundsException()
    service.getImage(tag).transform {
      case Success(link) => Success(
        try {
          replyWithPhoto(InputFile(link))
        } catch {
          case _ => reply(link) // maybe it isn't a photo...
        })
      case Failure(e) => Success(reply(e.getMessage))
    }.void
  } catch {
    case _: IndexOutOfBoundsException => reply("Empty argument list. Usage: /img tag").void
  }}

And this code sends an image if it's a success, but it doesn't send a message if it's a failure (but it definitely chooses case Failure(e) in this case)

A: reply family of functions return a Future[Message]. Currently you wrap the result of reply in Success, so the result of your transform is Future[Future[Message]], which doesn't work. Instead you can use transformWith, which expects a Future result from its argument:
onCommand("/img") { implicit msg =>
  val tag = msg.text.get.drop("/img ".length)
  val message: Future[Message] =
    if (tag.isEmpty) reply("Empty argument list. Usage: /img tag")
    else {
      service.getImage(tag).transformWith {
        case Success(link) => replyWithPhoto(InputFile(link)).recoverWith {
          case _ => reply(link) // maybe it isn't a photo...
        }
        case Failure(e) => reply(e.getMessage)
      }
    }
  message.void
}

Note, that I have also removed both try operators. The external is just unnecessary, because you can just use if/else. The internal won't work at all, because replyWithPhoto returns a Future. So it doesn't throw errors, and you need to recover or transform when it fails.


text:
Q: Create Amazon Cloudfront distribution in a script (Windows) Is there anywhere a decent full example of creating a distribution (ideally with more than one origin - S3 and an AMS) from the command line?  I was a bit dismayed to find that it isn't a case of "aws cloudfront blah blah..."
In Windows, assuming no special tools - though any solution that needs a standalone exe is fine. I have been hinted to use cURL... but can't figure out all the stuff I need to pass in, or indeed how to use cURL to do so - have found it has a -h param for headers...but never used cURL so a bit lost.
Looked http://docs.aws.amazon.com/AmazonCloudFront/latest/APIReference/CreateDistribution.html but am bemused by the sketchiness of the 'example'  e.g.
     POST /2013-09-27/distribution HTTP/1.1
     Host: cloudfront.amazonaws.com
     Authorization: AWS authentication string
     Date: Thu, 17 May 2012 19:37:58 GMT
     Other required headers
     ...

Where do I find my AWS authentication string?
What are the "Other required headers"
Distribution ID I can find on the Cloudfront admin page on the web
I am totally lost - need the real beginners guide here, step by step, ideally cross referenced to the Cloudfront admin page on the web. I'm a C#/SQL desktop apps dev normally, so this is way out of comfort zone.

A: Have ended up using the Amazon SDK for .NET

A: Actually, it probably is a matter of aws cloudfront blah blah
When typing aws cloudfront in a recent version of the AWS CLI one gets:
This service is only available as a preview service.

However, if you'd like to use a basic set of cloudfront commands with the
AWS CLI, you can enable this service by adding the following to your CLI
config file:

  [preview]
  cloudfront=true

Following this advice, you get the command aws cloudfront create-distribution.
I am personally still struggling to find the correct input for required params like --distribution-config

A: Running aws configure set preview.cloudfront true did not work for me. In my case (Linux), the following worked:
Edit the file ~/.aws/config and add the content
 [preview]
 cloudfront=true

To its end. This topic helped, but not mentioned the [brackets].


text:
Q: is not of type 'NodeMixin'. -Python Anytree I am getting the following error when i try to use a json a value of the Parent node using the anytree module, How can I get the json value as a parent?
Here is my code
def Get_Full_Name():
    name = names.get_full_name()
    return name

def Type_Name():
    ListType = ['Room', 'Building', 'Bed']
    number = random.sample([int(x) for x in range(1, 3)], 1)
    RandomList = ListType[number[0]]
    return RandomList

headers = {
    'accept': 'text/plain',
    'Content-Type': 'application/json-patch+json',
}

name = Get_Full_Name()
ListValue = Type_Name()
params = (
    ('name', name),
    ('type', 'BuildingGroup'),
)

data = '["{}"]'.format(name)

response = requests.post('http://SampleApiURL/', headers=headers,
                         params=params, data=data)

response_body = response.json()
print("Parent: " + response_body)
headers = {
    'accept': 'text/plain',
}

response2 = requests.get('http://SAmpleApiUrl/' + response_body, headers=headers)

response_body1 = response2.json()
RootNode = AnyNode(response_body1)
#ChildL2 = AnyNode(response_content="someValue", parent=RootNode)

exporter = JsonExporter(indent=4, sort_keys=True)
print  (exporter.export(RootNode))

The error I am getting is
Parent node {'locationId': 'LocationId', 'name': 'Andrew Rice', 'type': 'BuildingGroup', 'patientId': None, 'children': None} is not of type 'NodeMixin'.

How can I use a Json as a parent Node?


text:
Q: Office JavaScript API: Hiding the title of a bound ContentControl Using the Office JavaScript API in MS Word, I am binding a ContentControl by using its title property. This works fine, but Word displays this title, causing confusion for end users. I am wondering if there is a way to prevent the title from being shown.

Current result: a ContentControl which displays its custom title cc_typo5.

Desired result: a ContentControl which doesn't display its custom title cc_typo5.

A: That's just how content controls work in Word, but you have an alternative:
Have you tried making the content control invisible?
Check out this code:

Word.run(function (context) {
        context.document.contentControls.getByTitle("cc_typo5").getFirst().appearance = "hidden";
        return context.sync();
    })
        .catch(OfficeHelpers.Utilities.log);


text:
Q: Angular 2 - Forms - Set NgForm .submitted to true via NgForm Object In Angular 1 (1.5) the form controller had a $setSubmitted() method that allowed you to programmatically set the .$submitted flag to true.
How can I do this in 2 via the NgForm object? I do not want to use the template, aka (ngSubmit)="".
I've tried <formname>.ngSubmit.emit(), but it does not set .submitted to true.

A: ngSubmit is actually an event emitter (an @Output() binding) that will notify you after form has been submitted - it does this by listening to the DOM event for submit on the host form element.
So even if you don't use ngSubmit the form will still be 'submitted` if the user clicks a submit button within the form.
You can set the form submitted flag to to true manually using the onSubmit method e.g. via a button
<button type="button" (click)="theForm.onSubmit($event)">Submit</button>

.. but in my experience with Angular forms this would be quite unusual to need to set this manually (the ngForm directive and ngSubmit event emitter should be all you need to manage the form). Is there a reason why you would need this?

A: To submit form on click of button which is outside of form this same method can be used.
While creating the form assign a Reference variable to the form
<form name = "myform" (ngSubmit)= "SubmitForm()" #formVar = "ngForm">.....</form>

Now we can use this "formVar" throughout the html to directly access the form.
For submitting on click of button outside of form (using ngSubmit directive of angular form)  use this.
<button (click)= "formVar.onSubmit($event)"> Submit </button>

A: I'm doing a workaround:
 <form #form="ngForm" [formGroup]='toiletForm' [class.submitted]='submitted'></form>

Component prop:
submitted: boolean;

.less:
form.submitted input.ng-invalid {
    border: solid 2px #fa787e !important;
}


text:
Q: How to properly draw and label overlapping polygons? I would like to show overlapping polygons on a single layer.
The polygons are coloured based on a property and labelled according to another property. The problem is then twofold:

*

*The polygons are rendered in random order in tiles where they overlap, resulting in some small ones to "disappear" under the larger ones (e.g. cities "under" regions), while I would like them to be rendered according to a given property (I was thinking about using Priority but it is available only for TextSymbolizer in geoserver).

*The labels of larger polygons are shown "on top" of smaller polygons, while I would like to have them drawn ( repeated ) only at areas where the two (or more) polygons do not overlap. E.g. State names only to be shown where no other regional surface is being drawn (even if this might result in State names not being shown at all).

Is there a proper way of doing it?

A: As @iant pointed out, what appeared to be random order is the order in which the back end delivers the polygons to geoserver. Sorting them according to a property reflecting the desired display order is the correct way to solve it.
Unfortunately the labelling issue cannot be solved trivially on server side and on client side the most promising solution is to compute labelling points using WFS to retrieve involved geometries (but indeed slow).


text:
Q: nesting elesif syntax I'm modifying a breadcrumb script to append a '...' if the title is over 40 characters long. I got that part worked out fine, but what I can't get right is how to nest it in this massive script to leave it along if it's under 40 characters long.
Do I even need an else here? I have never encountered a script where there were multiple ifs without an else or elseif
    } elseif ( is_single() && !is_attachment() ) {
      if ( get_post_type() != 'post' ) {
        $post_type = get_post_type_object(get_post_type());
        $slug = $post_type->rewrite;
        echo '' . $post_type->labels->singular_name . '';
        if ($showCurrent == 1) echo ' ' . $delimiter . ' ' . $before . substr(the_title('', '', FALSE), 0, 40) . $after;
      } else {
        $cat = get_the_category(); $cat = $cat[0];
        $cats = get_category_parents($cat, TRUE, ' ' . $delimiter . ' ');
        if ($showCurrent == 0) $cats = preg_replace("#^(.+)\s$delimiter\s$#", "$1", $cats);
        echo $cats;
        if (($showCurrent == 1) && (strlen($post->post_title) > 40)) echo $before . substr(the_title('', '', FALSE), 0, 40) . '...' . $after;
      } elseif {
        if (($showCurrent == 1) && (strlen($post->post_title) < 40)) echo $before . get_the_title() . $after;

      }

A: The last elseif is invalid, as it is already preceded by an else.
I would also say that you should get in the habit of using a standardized way of writing if / if-else statements.  It appears to me that your code is probably messed up because you have some if statements without curly braces and some with.  If you were to, for example, use curly braces in all cases, and use proper indentation for them, your problem of having and elseif following an else conditional would have been very clear to discover.
As an example:
if ( get_post_type() != 'post' ) {
    $post_type = get_post_type_object(get_post_type());
    $slug = $post_type->rewrite;
    echo '' . $post_type->labels->singular_name . '';
    if ($showCurrent == 1) {
         echo ' ' . $delimiter . ' ' . $before . substr(the_title('', '', FALSE), 0, 40) . $after;
    }
} else {
    $cat = get_the_category(); $cat = $cat[0];
    $cats = get_category_parents($cat, TRUE, ' ' . $delimiter . ' ');
    if ($showCurrent == 0) {
        $cats = preg_replace("#^(.+)\s$delimiter\s$#", "$1", $cats);
    }
    echo $cats;
    if (($showCurrent == 1) && (strlen($post->post_title) > 40)) {
        echo $before . substr(the_title('', '', FALSE), 0, 40) . '...' . $after;
    }
} else if {
    if (($showCurrent == 1) && (strlen($post->post_title) < 40)) {
        echo $before . get_the_title() . $after;
    }
}

To me, this is much clearer to read even though it is slightly more verbose. It is also readily clear that the last else-if makes no sense.
By the way, as you fix your logic, make sure you consider what happens if the string is exactly 40 characters long.

A: Looks like you may be missing some curly brackets
} elseif ( is_single() && !is_attachment() ) {
      if ( get_post_type() != 'post' ) {
        $post_type = get_post_type_object(get_post_type());
        $slug = $post_type->rewrite;
        echo '' . $post_type->labels->singular_name . '';

        if ($showCurrent == 1) { echo ' ' . $delimiter . ' ' . $before . substr(the_title('', '', FALSE), 0, 40) . $after; }

      } else {
        $cat = get_the_category(); $cat = $cat[0];
        $cats = get_category_parents($cat, TRUE, ' ' . $delimiter . ' ');

        if ($showCurrent == 0) { $cats = preg_replace("#^(.+)\s$delimiter\s$#", "$1", $cats);
        echo $cats; }

        if (($showCurrent == 1) && (strlen($post->post_title) > 40)) { echo $before . substr(the_title('', '', FALSE), 0, 40) . '...' . $after; }

      } elseif {

        if (($showCurrent == 1) && (strlen($post->post_title) < 40)) { echo $before . get_the_title() . $after; }

      }

A: The logic is not clear.  You have not handled the case where the length is exactly 40 characters.
Try to structure your code so you only need to evaluate the same expression once.  Perhaps this is what you meant?
} elseif ( is_single() && !is_attachment() ) {
  if ( get_post_type() != 'post' ) {
   ...
  } else {
    ...
    echo $cats;

    if (($showCurrent == 1) && (strlen($post->post_title) > 40))
      echo $before . substr(the_title('', '', FALSE), 0, 40) . '...' . $after;
    }
    else {
      echo $before . get_the_title() . $after;
    }
  }
}  // Close the elseif


text:
Q: Insufficient Oauth scope when trying to deploy Jenkins click to deploy on an existing Google Kubernetes Engine cluster I have an existing Google Kubernetes Engine cluster where I want to deploy a Jenkins server.
GKE offers a marketplace with a click to deploy Jenkins image that I wanted to use but when I try to select my cluster it is marked as ineligible cluster with the message insufficient Oauth scope.
How can I work around this?

A: You get this error because of the node pool if your cluster doesn't have the right scopes to deploy the Jenkins server, Unfortunately you cannot stop the nodes to change their scopes, the IG will recreate these nodes with the old scopes.
To get around this problem you need to create another pool with the right scopes:
--scopes=https://www.googleapis.com/auth/cloud-platform

First create a new node pool:
gcloud container node-pools create adjust-node-scope \
   --cluster <YOUR_CLUSTER_NAME> --zone <YOUR_ZONE> \
   --num-nodes 3 \
   --scopes=https://www.googleapis.com/auth/cloud-platform

Second drain the old node pool:
kubectl cordon <NODE_NAME> #This will prevent new pods from being scheduled onto them
kubectl drain <NODE_NAME> --force #This will delete all the pods on that node.

Third delete the old node pool:
gcloud container node-pools delete default-pool \
   --cluster <YOUR_CLUSTER_NAME> --zone <YOUR_ZONE>

Then deploy your Jenkins server after.
Another workaround but not safe is to create a new instance template almost the same that your cluster is using with the new scopes you can as well setup full API access.
then in IG roll a new update and select the new instances template.


text:
Q: group data from array I have a DB like this:
id | start               | stop                | reason
1  | 2017-10-09 08:00:00 | 2017-10-09 08:15:00 | fault 1
2  | 2017-10-09 08:15:00 | 2017-10-09 08:30:00 | fault 2
3  | 2017-10-09 08:30:00 | 2017-10-09 09:00:00 | fault 3
4  | 2017-10-09 10:00:00 | 2017-10-09 11:15:00 | fault 1
5  | 2017-10-09 14:00:00 | 2017-10-09 15:00:00 | fault 2

I would like to make a pie chart of this data using flot charts but I need to group the data first and only display the total duration as a percentage, resulting in an array like:
0
label:  "Fault 1"
data:   46.15385
1
label:  "Fault 2"
data:   38.46154
2
label:  "Fault 3"
data:   15.38462

I am having trouble grouping them, I thought I could use in_array but I am having trouble with this, here is my code so far:-
header('Content-Type: application/json');
$sql = "SELECT * FROM " . STATE_TABLE . " INNER JOIN " . DOWNTIME_TABLE .
    " ON " . STATE_TABLE . ".reason = " . DOWNTIME_TABLE . ".faultId
    WHERE ('$shiftEnd' > start AND stop > '$shiftStart')
    OR ('$shiftEnd' > start AND stop is null) ORDER BY start DESC";
if ( !($result = $db->sql_query($sql)) )
{
    die('Could not query STATUS_TABLE database');
}
$totalDowntime = 0;
while( $row = $db->sql_fetchrow($result) ) {
    $start = $row['start'];
    $stop = $row['stop'] == null ? $currentTime : $row['stop'];
    $faultStart = $shiftStart > $start ? $shiftStart : $start;
    $faultStop = $stop > $shiftEnd ? $shiftEnd : $stop;

    $duration = get_time_difference($faultStart, $faultStop, 'seconds');

    $totalDowntime += $duration;
    $faults[] = $row;
}
$db->sql_freeresult($result);

$output = array();
$i = 0;
foreach($faults as $fault) {

    $start = $fault['start'];
    $stop = $fault['stop'] == null ? $currentTime : $fault['stop'];
    $description = $fault['description'];
    $faultStart = $shiftStart > $start ? $shiftStart : $start;
    $faultStop = $stop > $shiftEnd ? $shiftEnd : $stop;

    $duration = get_time_difference($faultStart, $faultStop, 'seconds');

    $percent = ($duration / $totalDowntime) * 100;

    if (in_array($description, $output)) {
        $output[]['data'] += $percent;
    } else {
        $output[$i]['label'] = $description;
        $output[$i]['data'] = $percent;
    }
    $i++;
}

die(json_encode($output));

A: Can't you group your data using your SQL query, so that you get the array ready for plotting right from MySQL?
SQL Fiddle: http://sqlfiddle.com/#!9/152bcc/4/0
For a table like this:
create table faults (id int not null, start timestamp not null, stop timestamp, reason text not null);
insert into faults (id, start, stop, reason) values
(1, '2017-10-09 08:00:00', '2017-10-09 08:15:00', 'fault 1'),
(2, '2017-10-09 08:15:00', '2017-10-09 08:30:00', 'fault 2'),
(3, '2017-10-09 08:30:00', '2017-10-09 09:00:00', 'fault 3'),
(4, '2017-10-09 10:00:00', '2017-10-09 11:15:00', 'fault 1'),
(5, '2017-10-09 14:00:00', '2017-10-09 15:00:00', 'fault 2'),
(6, '2017-10-09 14:00:00',  NULL                , 'fault 2');

You can use the TIMEDIFF() function and group by the "reason" column. The COALESCE() function returns the first NOT NULL value from a list, so it can be used to replace the current timestamp when stop is null:
select
  reason as label,
  SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(COALESCE(stop, CURRENT_TIMESTAMP), start)))) as data,
  SUM(TIME_TO_SEC(TIMEDIFF(COALESCE(stop, CURRENT_TIMESTAMP), start))) as data_seconds
from faults
group by reason
order by reason;

|   label |     data | data_seconds |
|---------|----------|--------------|
| fault 1 | 01:30:00 |         5400 |
| fault 2 | 13:23:02 |        48182 |
| fault 3 | 00:30:00 |         1800 |


text:
Q: What does a fitted value mean in dshw forecasting package? I have a double seasonal data. I wrote the following code to find the best fit model and find fitted values:

orders <- read.csv("DataForR.csv", header = TRUE),
  NumOrders <- orders$Orders,
> period <- orders$Period,
  OrderTimeSeries <- msts(NumOrders,seasonal.periods=c(24,7*24)),
  fit2 <- dshw(OrderTimeSeries,24,168,336,alpha=NULL,beta=NULL,gamma=NULL,omega=NULL,phi=NULL,lambda=NULL,armethod=TRUE,model=NULL),

my original time series plot is as follows:

but the fitted values are as follows:

I wonder what does a fitted value mean? does it mean using the fitted model, the forecast values for the training dataset are fitted data? how can I have both series in one plot so I can better compare their trends? Thanks

A: The fitted values correspond to an optimal 1-step ahead forecast.
See: http://cran.ms.unimelb.edu.au/web/packages/forecast/forecast.pdf


text:
Q: "Help us grow this site"? I've never liked the use of "to grow [x]" to mean "to make [x] bigger", rather than in the agricultural sense.
Am I justified in this at all?
(If so, can we make the SE team reword our social media banner?)

A: As a young editor (long ago), I was taught to use "grow" only in reference to plants, and that companies "build" a business. Somewhere in the past 30 years, businesses started to use the word "grow" to refer to their company. It really does grate on my ears. I know it's common usage now, but I still consider it marketing jargon and I always change it when editing.
Just my .02 on this.

A: I think it's fair to say that most people outside the business community rarely use grow as a transitive verb, unless they're talking about plants. I'm not generally impressed by business jargon. I think it tends to be purposefully vague, and to replace perfectly effective existing phrases without cause. The use of grow is a perfect example, since you could almost always just say expand or increase instead.

A: I don't think this is a matter of agriculture so much as organics. That is, the traditionally preferred use of "grow" is intransitive, unless what's growing does so from its own (natural) power. So, hair can grow, and crystals can grow, and tomatoes can grow, but economies can't grow, since human agency is needed to make them larger or stronger or whatever.
Fie upon you, Bill Clinton! This is not a Southern thing, since nobody I know in the South would ever "grow" a business. It's a matter of style, grace, and taste, which is of course how all grammar is ultimately determined. As my dear college professor said to me, "I don't think it's incorrect, it's just vulgar."
Raymond Chandler to new editor of his novel when they "corrected" his prose:  "If I want to goddam well split an infinitive, I intend to." (or something like that)

A: I don't see any problem with using grow as transitive verb for things not related to agriculture.
Here is the definition from the Merriam-Webster dictionary for grow as transitive verb:
1
a : to cause to grow
b :to let grow on the body
2
: to promote the development of start a business and grow it successfully — J. L. Deckter
The second definition is the one being used on the banner.


text:
Q: sails-auth not generating models, policies etc., I installed a fresh sails application, I planned to integrate passport for authentication. Sails-auth seems to be the easiest way but it just doesn't create any files as said in the doc..
sails : 0.12.14
I got this deprecated warning while installing sails-auth though,
newmacs-iMac:dn dev$ npm install sails-auth --save
npm WARN deprecated gulp-util@3.0.8: gulp-util is deprecated - replace it, following the guidelines at https://medium.com/gulpjs/gulp-util-ca3b1f9f9ac5
npm WARN deprecated graceful-fs@3.0.11: please upgrade to graceful-fs 4 for compatibility with current and future versions of Node.js
npm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated minimatch@0.2.14: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated graceful-fs@1.2.3: please upgrade to graceful-fs 4 for compatibility with current and future versions of Node.js

A: You have to follow the steps explained on https://github.com/trailsjs/sails-auth
First, do npm install sails-auth --save followed by installing a password strategy you want to use, e.g. npm install passport-google-oauth
Then create the file config/passport.js with the following content according to the passport strategy you want to use, for example:
module.exports.passport = {
  local: {
    strategy: require('passport-local').Strategy
  },

  basic: {
    strategy: require('passport-http').BasicStrategy,
    protocol: 'basic'
  }
};

More examples can be found here https://github.com/trailsjs/sails-auth/blob/master/config/passport.js
Then create config/auth.js
bcrypt: {
    /**
     * Specifiy number of salt rounds to perform on password. Values >10 are
     * slow.
     */
    rounds: 8
  }

Then you are ready to authenticate to /auth/local or /auth/google depending on the passport strategy you are using.
Important: with sails v1.0 sails-auth does no longer seem to work but since you are using sails 0.12 it should work.


text:
Q: MySQL second auto increment field based on foreign key I've come across this problem numerous times but haven't found a "MySQL way" to solve the issue as such - I have a database that contains users and reports. Each report has an id which I display as a report number to my users.
The main complaint is that users are confused as to why reports have gone missing from their system. This is not actually the case. It is actually that they are recognizing a gap between their IDs and assume that these are missing reports, when in actual fact, it is simply becasue another user has filled in this auto-incrementing gap.
I need to know if there is a way to do this in MySQL:
Is it possible that I can have a second auto-increment field called report_number which is based on a user_id field which has a different set of auto-increments per user?
e.g.
|------|---------|---------------|
|  id  | user_id | report_number |
|------|---------|---------------|
|  1   |    1    |       1       |
|  2   |    1    |       2       |
|  3   |    1    |       3       |
|  4   |    2    |       1       |
|  5   |    1    |       4       |
|  6   |    1    |       5       |
|  7   |    2    |       2       |
|  8   |    3    |       1       |
|  9   |    3    |       2       |
|------|---------|---------------|

I am using InnoDB for this as it is quite heavily weighted with foreign-keys. It appears to complain when I add a second auto increment field, but I wasn't sure if there was a different way to do this?

A: Right one with IFNULL:
DELIMITER $$
CREATE TRIGGER salons_trigger
BEFORE INSERT ON salon
FOR EACH ROW BEGIN
    SET NEW.salon_id = IFNULL((SELECT MAX(salon_id) + 1 FROM salon WHERE owner = NEW.owner), 1);
END $$
DELIMITER ;

A: MyISAM supports the second column with auto increment, but InnoDB doesn't.
For InnoDB you might create a trigger BEFORE INSERT to get the max value of the reportid and add one to the value.
DELIMITER $$
CREATE TRIGGER report_trigger
BEFORE INSERT ON reports
FOR EACH ROW BEGIN
    SET NEW.`report_id` = (SELECT MAX(report_id) + 1 FROM reports WHERE user_id = NEW.user_id);
END $$
DELIMITER ;

If you can use MyISAM instead, in the documentation of MySQL page there is an example:
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
CREATE TABLE animals (
    grp ENUM('fish','mammal','bird') NOT NULL,
    id MEDIUMINT NOT NULL AUTO_INCREMENT,
    name CHAR(30) NOT NULL,
    PRIMARY KEY (grp,id)
) ENGINE=MyISAM;

INSERT INTO animals (grp,name) VALUES
    ('mammal','dog'),('mammal','cat'),
    ('bird','penguin'),('fish','lax'),('mammal','whale'),
    ('bird','ostrich');

SELECT * FROM animals ORDER BY grp,id;

Which returns:
+--------+----+---------+
| grp    | id | name    |
+--------+----+---------+
| fish   |  1 | lax     |
| mammal |  1 | dog     |
| mammal |  2 | cat     |
| mammal |  3 | whale   |
| bird   |  1 | penguin |
| bird   |  2 | ostrich |
+--------+----+---------+

A: I think mysql doesnt support two auto_increment columns. you can  create report number using information schema.
select NULL from information_schema.columns

A: MySQl does not support two auto incremented fields, if you need then create another table, set the other field which you want to be as auto incremented and you must set up a relationship with these two tables.


text:
Q: Run time parallel loop in R I have access to a quite powerful remote desktop where I ran some parallel code in R. However, I am surprised about the results when I compare the running time between the parallel loop and the simple for loop. Below is my code.
library(rbenchmark)
library(foreach)
library(doParallel)

max.eig <- function(N, sigma) {
  d <- matrix(rnorm(N**2, sd = sigma), nrow = N)
  E <- eigen(d)$values
  abs(E)[[1]]
}

no_cores <- 20
registerDoParallel(cores=no_cores)
cl <- makeCluster(no_cores)

benchmark(
  foreach(n = 1:50) %do% max.eig(n, 1),
  foreach(n = 1:50) %dopar% max.eig(n, 1)
)

The speed comparison gives
                                     test replications elapsed relative user.self sys.self user.child sys.child
   foreach(n = 1:50) %do% max.eig(n, 1)          100   3.097    1.000     3.081    0.003      0.000     0.000
foreach(n = 1:50) %dopar% max.eig(n, 1)          100   8.327    2.689     0.943    6.643      3.648    27.523

Notice that the running time of the parallel loop is much longer. This is true regardless of the number of cores I register. In contrast, when I run the comparison on my own computer, the parallel for loop is much faster (with 4 cores). The results give
                                    test replications elapsed relative user.self sys.self user.child sys.child
    foreach(n = 1:70) %do% max.eig(n, 1)          100   11.36    1.939     11.27     0.03         NA        NA
 foreach(n = 1:70) %dopar% max.eig(n, 1)          100    5.86    1.000      2.97     0.35         NA        NA

How is it possible that the parallel loop is slower on the remote desktop? And is there a way to set up the parallel cluster differently so that it is much faster and I can exploit the many cores on the remote computer?