text:
Q: Android: Shake Detector too Sensitive I'm trying to detect a shake - and i'm using the following code,
it works very good, but in some devices (Galaxy note 2 for example) it detects the shake too soon (in some cases - when i just hold the phone still)
main.java:
ShakeListener mShaker = new ShakeListener(this);
     mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
         public void onShake()
         {
        // Some code...
         }
     });
}

ShakeListener.java :
package com.my.app;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.widget.Toast;
import android.content.Context;
import java.lang.UnsupportedOperationException;

public class ShakeListener implements SensorEventListener
{
      private static final int FORCE_THRESHOLD = 700;
      private static final int TIME_THRESHOLD = 100;
      private static final int SHAKE_TIMEOUT = 500;
      private static final int SHAKE_DURATION = 1000;
      private static final int SHAKE_COUNT = 5;

      private SensorManager mSensorMgr;
      private float mLastX=-1.0f, mLastY=-1.0f, mLastZ=-1.0f;
      private long mLastTime;
      private OnShakeListener mShakeListener;
      private Context mContext;
      private int mShakeCount = 0;
      private long mLastShake;
      private long mLastForce;

      public interface OnShakeListener
      {
        public void onShake();
      }

      public ShakeListener(Context context)
      {
        mContext = context;
        resume();
      }

      public void setOnShakeListener(OnShakeListener listener)
      {
        mShakeListener = listener;
      }

      public void resume() {
        mSensorMgr = (SensorManager)mContext.getSystemService(Context.SENSOR_SERVICE);
        if (mSensorMgr == null) {
          throw new UnsupportedOperationException("Sensors not supported");
        }
        boolean supported = false;
        try {
        supported = mSensorMgr.registerListener(this, mSensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
        } catch (Exception e) {Toast.makeText(mContext, "Shaking not supported", Toast.LENGTH_LONG).show();}

        if ((!supported)&&(mSensorMgr != null)) mSensorMgr.unregisterListener(this);
      }

      public void pause() {
        if (mSensorMgr != null) {
          mSensorMgr.unregisterListener(this);
          mSensorMgr = null;
        }
      }

      public void onAccuracyChanged(Sensor sensor, int accuracy) { }

      public void onSensorChanged(SensorEvent event)
      {
        if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
              return;
        long now = System.currentTimeMillis();

        if ((now - mLastForce) > SHAKE_TIMEOUT) {
          mShakeCount = 0;
        }

        if ((now - mLastTime) > TIME_THRESHOLD) {
          long diff = now - mLastTime;
          float speed = Math.abs(event.values[0] + event.values[1] + event.values[2] - mLastX - mLastY - mLastZ) / diff * 10000;
          if (speed > FORCE_THRESHOLD) {
            if ((++mShakeCount >= SHAKE_COUNT) && (now - mLastShake > SHAKE_DURATION)) {
              mLastShake = now;
              mShakeCount = 0;
              if (mShakeListener != null) {
                mShakeListener.onShake();
              }
            }
            mLastForce = now;
          }
          mLastTime = now;
          mLastX = event.values[0];
          mLastY = event.values[1];
          mLastZ = event.values[2];
        }
      }
}

A: Check Acceleration with higher number of shake. Take a Look on this code it works for me.
private final SensorEventListener mSensorListener = new SensorEventListener() {

        public void onSensorChanged(SensorEvent se) {
            float x = se.values[0];
            float y = se.values[1];
            float z = se.values[2];
            mAccelLast = mAccelCurrent;
            mAccelCurrent = (float) Math.sqrt((double) (x * x + y * y + z * z));
            float delta = mAccelCurrent - mAccelLast;
            mAccel = mAccel * 0.9f + delta; // perform low-cut filter

            if (mAccel > 8) {
                 Toast.makeText(getApplicationContext(),
             "You have shaken your phone", Toast.LENGTH_SHORT).show();
            }

        }

        public void onAccuracyChanged(Sensor sensor, int accuracy) {
            Log.i("Sensor", "mAccel" + mAccel);
        }
    };

A: Start from lower sensitivity but gradually increase it if shaking above some initial threshold continues for a longer time. This is similar to human perception.

A: Try this...and let me know..
public class ShakeListener implements SensorEventListener {
    private String TAG = ShakeListener.class.getSimpleName();
    private static final int FORCE_THRESHOLD = 800;
    private static final int TIME_THRESHOLD = 100;
    private static final int SHAKE_TIMEOUT = 500;
    private static final int SHAKE_DURATION = 1000;
    private static final int SHAKE_COUNT = 5;

    private SensorManager mSensorMgr;
    private float mLastX = -1.0f, mLastY = -1.0f, mLastZ = -1.0f;
    private long mLastTime;
    private OnShakeListener mShakeListener;
    private Context mContext;
    private int mShakeCount = 0;
    private long mLastShake;
    private long mLastForce;

    public interface OnShakeListener {
        public void onShake();
    }

    public ShakeListener(Context context) {

        Log.d(TAG,"ShakeListener invoked---->");
        mContext = context;
        resume();
    }

    public void setOnShakeListener(OnShakeListener listener) {
        Log.d(TAG,"ShakeListener setOnShakeListener invoked---->");
        mShakeListener = listener;
    }

    public void resume() {
        mSensorMgr = (SensorManager) mContext
                .getSystemService(Context.SENSOR_SERVICE);
        if (mSensorMgr == null) {
            throw new UnsupportedOperationException("Sensors not supported");
        }
        boolean supported = false;
        try {
            supported = mSensorMgr.registerListener(this,
                    mSensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                    SensorManager.SENSOR_DELAY_GAME);
        } catch (Exception e) {
            Toast.makeText(mContext, "Shaking not supported", Toast.LENGTH_LONG)
                    .show();
        }

        if ((!supported) && (mSensorMgr != null))
            mSensorMgr.unregisterListener(this);
    }

    public void pause() {
        if (mSensorMgr != null) {

            mSensorMgr.unregisterListener(this);
            mSensorMgr = null;
        }
    }

    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
            return;
        long now = System.currentTimeMillis();

        if ((now - mLastForce) > SHAKE_TIMEOUT) {
            mShakeCount = 0;
        }

        if ((now - mLastTime) > TIME_THRESHOLD) {
            long diff = now - mLastTime;
            float speed = Math.abs(event.values[SensorManager.DATA_X]
                    + event.values[SensorManager.DATA_Y]
                    + event.values[SensorManager.DATA_Z] - mLastX - mLastY
                    - mLastZ)
                    / diff * 10000;
            if (speed > FORCE_THRESHOLD) {
                if ((++mShakeCount >= SHAKE_COUNT)
                        && (now - mLastShake > SHAKE_DURATION)) {
                    mLastShake = now;
                    mShakeCount = 0;
                     Log.d(TAG,"ShakeListener mShakeListener---->"+mShakeListener);
                    if (mShakeListener != null) {
                        mShakeListener.onShake();
                    }
                }
                mLastForce = now;
            }
            mLastTime = now;
            mLastX = event.values[SensorManager.DATA_X];
            mLastY = event.values[SensorManager.DATA_Y];
            mLastZ = event.values[SensorManager.DATA_Z];
        }
    }
}

A: This works fine with me:
public class ShakeEventListener implements SensorEventListener {
public final static int SHAKE_LIMIT = 15;
public final static int LITTLE_SHAKE_LIMIT = 5;

private SensorManager mSensorManager;
private float mAccel = 0.00f;
private float mAccelCurrent = SensorManager.GRAVITY_EARTH;
private float mAccelLast = SensorManager.GRAVITY_EARTH;

private ShakeListener listener;

public interface ShakeListener {
    public void onShake();
    public void onLittleShake();
}

public ShakeEventListener(ShakeListener l) {
    Activity a = (Activity) l;
    mSensorManager = (SensorManager) a.getSystemService(Context.SENSOR_SERVICE);
    listener = l;
    registerListener();
}

public ShakeEventListener(Activity a, ShakeListener l) {
    mSensorManager = (SensorManager) a.getSystemService(Context.SENSOR_SERVICE);
    listener = l;
    registerListener();
}

public void registerListener() {
    mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}

public void unregisterListener() {
    mSensorManager.unregisterListener(this);
}

public void onSensorChanged(SensorEvent se) {
    float x = se.values[0];
    float y = se.values[1];
    float z = se.values[2];
    mAccelLast = mAccelCurrent;
    mAccelCurrent = (float) FloatMath.sqrt(x*x + y*y + z*z);
    float delta = mAccelCurrent - mAccelLast;
    mAccel = mAccel * 0.9f + delta;
    if(mAccel > SHAKE_LIMIT)
        listener.onShake();
    else if(mAccel > LITTLE_SHAKE_LIMIT)
        listener.onLittleShake();
}

public void onAccuracyChanged(Sensor sensor, int accuracy) {}
}

Reference


text:
Q: Suppose that S is a nonempty set such that A= LUB S. Let T={2x+1:x element in S}. Prove that LUB T=2A+1 Can some one please help me get started on this.
I would really like to understand what I am doing.
Suppose that S is a nonempty set such that A= LUB S.
Let $T={2x+1:x \in S}$.
Prove that LUB $T=2A+1$

A: First, $2\sup S + 1$ is an upper bound of $T$. By the definition of $\sup T$, we must have $$\sup T \leq 2\sup S + 1.$$
Conversely, given $\epsilon >0$ and then there exists $t \in T$ such that  $$\sup T - \epsilon<t .$$
Here $t = 2s + 1$ for some $s \in S$, then $\sup T - \epsilon < 2\sup S + 1$ for any $\epsilon >0$. Therefore we have, $$ \sup T \leq 2\sup S + 1.$$

A: $2A+1$ is an upperbound of $T$: any $t\in T$ can be written as $t=2s+1$ where $s\in S$. Because $s\leq A$, we have $t=2s+1\leq 2A+1$.
Now suppose that $M$ is any upperbound of $T$, then $\frac{M-1}{2}$ is an upperbound of $S$ so that $\frac{M-1}{s}\geq A$. But this means $M\geq 2A+1$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error in Lists in Haskell - Intersection This is a tiny problem, I really don't know where I've be wrong. I need to create a function for show the intersection of two lists (without library and list comprehension). Ok, I made this, it's simple, but I have make a mistake, cause the function return me only the first element equal of the two lists. This is a stupid error, I know. someone can Help me?
this is the function:
inter :: [Int] -> [Int] -> [Int]
inter [] _ = []
inter _ [] = []
inter (x:xs) (y:ys) | (x == y) = x:[]
                    | otherwise = inter xs ys

example of error: (Two lists) [1,2,4] [1,3,4]
return only [1] when the correct is: [1,4]

A: You're iterating over both lists simultaneously and stopping at the first common element.  You need to be checking list membership and continuing after you find the first matching element.  I would recommend using the elem function:
inter (x:xs) ys | elem x ys = ...
                | otherwise = inter xs ys

You'll need to fill in the ... here, I intentionally left it blank for you to figure out what you need to do.
In your function what's going to happen is it will see
inter (1:2:4:[]) (1:3:4:[])

And it will assign x = 1, y = 1, xs = 2:4:[], ys = 3:4:[], then compute x == y, which evaluates as True, so that branch is chosen, returning x : []. or [1].  At that point the function returns.  It'll never check 2 == 3 or 4 == 4.

A: Assumption: a set is a sorted list here.
Your code works as follows:
inter :: [Int] -> [Int] -> [Int]
inter [] _ = []
inter _ [] = []
inter (x:xs) (y:ys) | (x == y) = x:[]         -- if x == y, we stop?
                    | otherwise = inter xs ys -- can we drop both elements?

The first two lines state that "from the moment one of the lists is [], we return []". So far so good.
Then next line works with two guards. Given we find that the two heads are equal (x == y), we simply return *a list with one item [x]. That is not correct: it is possible that in the two tails xs and ys, there are still items that are in both sets. The second guard is incorrect as well: if x is not equal to y, that does not mean we can throw away both elements: it is possible that x is still in the tail ys, or that y is still in xs somewhere.
We can however obtain a rather efficient solution by the fact that both lists are sorted. In that case, we can simply drop the smallest of the two. Since if ys is sorted and x < y, we know that all elements in ys will also be greater than x.
So a solution I propose is:
inter :: [Int] -> [Int] -> [Int]
inter [] _ = []  -- left list is empty, stop
inter _ [] = []  -- right list is empty, stop
inter xa@(x:xs) ya@(y:ys) | x == y = x : inter xs ys -- both head same, continue
                          | x < y = inter xs ya      -- left less, step left
                          | otherwise = inter xa ys  -- right less, step right
The @ is an alias here. xa@(x:xs) means that we have a reference to the entire list xa and to the head x and the tail xs.
Usually one aims to be as generic as possible in Haskell: right now we have to implement an inter for lists with Ints, Strings, etc. That is not very elegantly. We can generalize it to the following:
inter :: Ord a => [a] -> [a] -> [a]
inter [] _ = []
inter _ [] = []
inter xa@(x:xs) ya@(y:ys) | x == y = x : inter xs ys
                          | x < y = inter xs ya
                          | otherwise = inter xa ys


text:
Q: If Statement to check if a screen exists before sending form. c# Visual Studio So I've written a countdown timer for my church using Visual Studio c# (first program I've written) I've created a controller (Form1) and the countdown timer (Form2) and I have already set it all up to automatically start the countdown timer on Form2, scale Form2 to maximum screen size along with the text in the form and I can send it between monitor 1, 2 or 3. no worries. the issue I've got is that i need an if statement that checks if screen 1,2,3 (0,1,2) exists before sending. At the moment my program crashes because it can't find screen.allscreens[2] (this is because i don't have a 3rd monitor attach, deliberately to test this code).
Please let me know if you require more information. Thanks!

A: You answer to your own question. You can simply use:
if(Screen.AllScreens.Length>0)
{
//some of your code
}

Or using Linq:
if(Screen.AllScreens.Any())
{
//some of your code
}


text:
Q: Vue.js devtools not detecting Vue.js in standalone installation, already allowed access to file URLs I have a vue.js + laravel installation project on my local server where the Vue.js devtools detects Vue.js and I'm able to use it. However, when I do a standalone Vue.js installation using 'vue create', Vue.js is not detected by devtools. I already allowed access to file URLs under chrome extension but it is still not working. The devtools was detecting Vue.js in the laravel version just fine without allowing access to file URLS.
Is there something else basic that I'm missing to get Vue.js devtools to work? There must be a simple step I missed because there should be loads of people creating fresh Vue.js projects on local server and getting devtools to work.
I'm using 'npm run serve' to run Vue.js in localhost, is this supposed to be detected by Vue.js devtools by default?

A: solved by reinstalling Vue.js 2 instead of the Vue.js 3 preview version as of 2020-08-26.


text:
Q: GitLab CI: reuse the same image in two independent parallel jobs I am currently building two Latex documents in parallel using the aergus/latex container as follows (a Makefile is available in the repository):
stages:
  - compile

.compile_pdf_template:
  stage: compile
  image: aergus/latex

presentation:
  extends:
    - .compile_pdf_template
  script:
    - make presentation
  artifacts:
    paths:
      - presentation.pdf

report:
  extends:
    - .compile_pdf_template
  script:
    - make report
  artifacts:
    paths:
      - report.pdf

This works as expected, but it pulls the image twice (it is the slowest step in this simple pipeline, since the documents have few pages/slides). Is there any way to share the image across the two jobs, effectively pulling it only once, while keeping the jobs running in parallel?

A: All the jobs are independent, to speed up your process you can use the Shell Executor https://docs.gitlab.com/runner/executors/ to make it faster
With this executor you will be able to use local docker images.
The first job will download the image from the docker hub and the next ones will get from the local docker service.
But if you are using other executors or Gitlab Shared Runner, this is the normal behaviour


text:
Q: Does Origin have groups and events à la Steam Community? (Unnecessary preamble.) Given yesterday's failure of the L4D2 Game On, we decided to change to Battlefield 3 to put this fancy server of ours to the test. I made the relevant Steam event but... that doesn't really help, does it?
Does Origin have groups and events like Steam does?

A: No it does not.
Origin doesn't really support any of the features that Steam does in terms of profile and networking.


text:
Q: Prevent capacitor discharge after it was charged using a microcontroller I want to use a micro-controller (like an Arduino) to:

*

*Charge an external capacitor

*Measure voltage across the capacitor

*Capacitor discharge rate as low as possible.

*Capacitor discharge rate while using ADC to measure voltage as low as possible.

The microcontroller has

*

*DAC (to charge capacitor)

*ADC (to measure capacitance)

*Multiplexer to attach DAC/ADC to whatever pin you want

*I use a multimeter to measure resitance between pin 0 and pin 1 = 1Mohm (Q1 is pin0-1 resistance called chip resitance? What is the name?)

I can attach a capacitor between pins 0 and 1 however it will discharge as 1Mohm resitance isn't very high.

simulate this circuit – Schematic created using CircuitLab
Question:

*

*Is the pin 0 to 1 resistance called chip resistance? What is the name?

*How can I reduce the capacitor discharge after I charge it with the DAC?

*How can I reduce the discharge while measuring voltage with ADC?

My actual chip is the NHS3152. I am looking for any solution, even one with other components to be added.
EDIT EXTRA CONTEXT INFORMATION
I was thinking of using the capacitor as an X-ray detector:

*

*X-rays would interact with the dielectric to create e-h pairs

*The electric field present on the charged capacitor would separate the charges

*This would affect voltage across capacitance.

*Measure the voltage with NHS3152 and have a working device.

If the capacitor discharges over time, then the field within the dielectric would change, separating the e-h pairs less, so low-discharge is important.


text:
Q: is there a way to check if the scanf is empty? The scanf is appending to a double array double array[40]; int var = 0; while (scanf("%lf", &array[var])== 1){     var++;
sometimes the double array is left empty by the users that are inputing data. how can i check if the array isnt empty. if it is empty i will add a print statement. I cant add 0 to the whole list or else it can mess up some results. that the user enters and null values only work in char.
$echo -n ' ' | ./test
your statement is empty


text:
Q: Not able to get selected item in wx.DataViewCtrl I am using wx.DataViewCtrl of wxpython 2.7.8 to list my data. I can get selected item from list using wx.DataViewCtrl:GetSelections() at first time by clicking menu. after closing the box by clicking close button, again am trying to open this box by clicking menu. But i coudn't get selected item to delete/modify using wx.DataViewCtrl:GetSelections(). wx.DataViewCtrl:GetSelections() returns empty list. But still the wx.DataViewCtrl box displaying the list of data.
Please help me. I am struck with this issue for last two days.Thanks in advance.
    class MainFrame(wx.Dialog):

def __init__(self, parent, title, data):

    self.data = data
    wx.Dialog.__init__(self, parent, title=title, size=(800, 400))
    self.panel = wx.Panel(self)
    self.model = UpdateModel(self.data)

def createEntityTable(self, editor_ctrl):
    self.__editor_ctrl = editor_ctrl.getEditor()
    self.dvc = dv.DataViewCtrl(self.panel,
                               style=wx.BORDER_THEME
                               | dv.DV_ROW_LINES # nice alternating bg colors
                               #| dv.DV_HORIZ_RULES
                               | dv.DV_VERT_RULES
                               | dv.DV_MULTIPLE, size = (600, 400)
                               )
    self.dvc.AssociateModel(self.model)

    self.dvc.AppendTextColumn("Name",  0, width=170, mode=dv.DATAVIEW_CELL_EDITABLE)
    self.dvc.AppendTextColumn("DTD",   1, width=80, mode=dv.DATAVIEW_CELL_EDITABLE)
    self.dvc.AppendTextColumn("File name",   2, width=80,  mode=dv.DATAVIEW_CELL_EDITABLE)
    self.dvc.AppendTextColumn("Public Id",   3, width=80,  mode=dv.DATAVIEW_CELL_EDITABLE)
    self.dvc.AppendTextColumn("Notation",   4, width=80,  mode=dv.DATAVIEW_CELL_EDITABLE)

    for c in self.dvc.Columns:
        c.Sortable = True
        c.Reorderable = True

    self.new = wx.Button(self.panel, -1, "New")
    self.Bind(wx.EVT_BUTTON, self.OnAddRow, self.new)

    self.modify = wx.Button(self.panel, -1, "Modify")
    self.Bind(wx.EVT_BUTTON, self.onModifyRow, self.modify)

    self.delete = wx.Button(self.panel, -1, "Delete")
    self.Bind(wx.EVT_BUTTON, self.OnDeleteRows, self.delete)

    self.close = wx.Button(self.panel, -1, "Close")
    self.Bind(wx.EVT_BUTTON, self.OnClosePanel, self.close)

    dvcSizer = wx.BoxSizer(wx.HORIZONTAL)
    dvcSizer.Add(self.dvc, 1, wx.EXPAND)

    btnbox = wx.BoxSizer(wx.VERTICAL)

    btnbox.Add(self.new, 0, wx.LEFT|wx.RIGHT, 5)
    btnbox.Add(self.modify, 0, wx.LEFT|wx.RIGHT, 5)
    btnbox.Add(self.delete, 0, wx.LEFT|wx.RIGHT, 5)
    btnbox.Add(self.close, 0, wx.LEFT|wx.RIGHT, 5)
    dvcSizer.Add(btnbox, 0, wx.TOP|wx.BOTTOM, 5)

    self.panel.SetSizer(dvcSizer)
    self.ShowModal()

def OnDeleteRows(self, evt):
    items = self.dvc.GetSelections()
    rows = [self.model.GetRow(item) for item in items]
    self.model.DeleteRows(rows)

A: It seems that you used the DVC_IndexListModel from the wxPython Demo. Did you implement the method DeleteRows(self, rows) as shown in the TestModel derived from PyDataViewIndexListModel? This would be your UpdateModel.
BTW, 2.7.8 should be your (C)Python version. I suppose you have a wxPython version > 2.9.


text:
Q: PHP url routing and pretty urls I have this url that is generated from a form that is supposed to search inside a database for an event: http://localhost:8080/search?event=ecddf4
I want that the url is rewrited in this way: http://localhost:8080/search/event/ecddf4
I'm using FastRoute as my php routing system but I want to try something more documented like Simple Router . I have this rules inside my .htaccess file:
RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-l
RewriteRule ^(.*)$ index.php/$1

I use this set of rules for both routing systems but I'm unable to obtain a pretty url when the form is submitted. Can anyone explain me how to achieve this?It's few time that I'm using FastRoute and I will start tomorrow with php-simple-router. Someone suggested me to map an url with regexp but how?I've readed the documentations but it's not clear form me if i need to set a placeholder like this /search/{event} to rewrite the url?
this is the form I have to submit the search:
<form method="GET" action="search" name="">
 <input type="search" name="event" />
 <button type="submit">Search</button>
</form>


text:
Q: PowerPoint Interop - How to access Chart out of a shape? I am working in an office automation tool to process PowerPoint documents, where I am facing an issue in formatting Chart.
I am using the following assemblies for formatting the Presentation
    Microsoft.Office.Interop.PowerPoint  Version: 12.0.0.0
    Microsoft.Office.Interop.Graph Version: 12.0.0.0
Requirement is to apply some styles like Legend location, color, font etc to the Chart exists in the presentation.
I am able to verify the Shape like
    shape.HasChart == MsoTriState.msoTrue
But not able to get the Chart object out of the shape
Tried the following code, but received OLEFormat exception
    Graph.Chart chart = (Graph.Chart)shape.OLEFormat.Object
Thanks in advance for your help.

A: Resolved the issue by selecting correct reference from the COM tab.
Answer from thread - http://social.msdn.microsoft.com/Forums/en-US/officegeneral/thread/06cea2b7-f169-4f8a-b53e-4319b12b5450

A: I know you are asking from (rather) .NET point of view but I'll show you some code from VBA PowerPoint. My goal is to show you object hierarchy. I believe it would be helpful enough for you to solve your problem.
Sub Chart_Elements()

Dim CHRT As Chart
'first shape in the 1st slide is chart
Set CHRT = ActivePresentation.Slides(1).Shapes(1).Chart

With CHRT
    'to set legend position
    .Legend.Position = xlLegendPositionBottom
    'to set size of 1st entry in legend
    .Legend.LegendEntries(1).Font.Size = 10
    'and so on
End With
End Sub

If that answer doesn't help you at all please consider re-tagging your question.


text:
Q: Getting livestreams from YouTube channel I am trying to keep track of the livestream viewers of a specific channel.
This is no problem when I have got the stream ID and use it manually.
However I want my program to be able to track upcoming livestream automatically. So I want to get the livestream ID from the channel for the next upcoming livestream. I have been looking through the documentation from the API, but I couldn't find anything.
What API call do I need to make?

A: You cannot get the liveBroadcast or liveStream object that does not belong to the user or channel you are authenticated as.  The list endpoint for each object requires you to authenticate as your own channel/user to retrieve your own live events only.
If you want to retrieve information on another channel's current live broadcasts, you have to use the standard Search/list endpoint:
part -> snippet
channelId -> [channelId of the channel/user with the live event]
eventType -> live
type -> video (required when setting eventType to live)
HTTP GET https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={channelId}&eventType=live&type=video&key={YOUR_API_KEY}


text:
Q: The possibility of a symmetric difference in a torsion-free group Is there a torsion-free group  containing two elements $x$ and $y$ and a finite non-empty subset $B$ such that $B=xB \triangle yB$, where $\triangle$ denotes the symmetric difference of two sets and $xB$ denotes the set $\{xb \;:\; b\in B\}$?
Edited May 29, 2015:
The question is equivalent to the following:
Is there a torsion-free group $G$ and elements $x,y\in G$ such that $1+x+y$ is a zero divisor in the group ring $\mathbb{F}_2[G]$, where $\mathbb{F}_2$ is the field with $2$ elements?


text:
Q: Error when trying to check if email already exists in db I am receiving this error when I try to check if an email already exists in the database and not sure why:
Fatal error: Call to a member function bind_param() on a non-object in ""
Here is my code:
$email = $_POST['email'];
//prepare and set the query and then execute it
$stmt = $conn2->prepare("SELECT COUNT (*) FROM users WHERE email = ?");
$stmt->bind_param('s', $email);
$stmt->execute();

// grab the result
$stmt->store_result();

// get the count
$numRows = $stmt->num_rows();

if( $numRows )
{

echo "
Email is already registered with us
";
}
else

//if we have no errors, do the SQL

I have a seperate database connection file:
function DB2($host='', $user='', $password='', $db='') {

     /* Create a new mysqli object with database connection parameters */
     $mysqli = new mysqli($host, $user, $password, $db);

     if(mysqli_connect_errno()) {
        echo "Connection Failed: " . mysqli_connect_errno();
        exit();
     }

     return $mysqli;
  }

Which is linked to this file using:
$conn2 = DB2();

A: You didn't say what language this is in. I'm assuming it's perl and dbi.
$email = $_POST['email'];
//prepare and set the query and then execute it
$stmt = $conn2->prepare("SELECT COUNT (*) FROM users WHERE email = ?");
$stmt->bind_param($email);
$stmt->execute();

should be
$email = $_POST['email'];
//prepare and set the query and then execute it
$stmt = $conn2->prepare("SELECT 1 FROM users WHERE email = ? fetch first row only");
$stmt->execute($email);

I don't know what store_result() is. I don't think it's part of DBI. You possibly want to do:
@found = $stmt->selectrow_array();
if ($#found) { #email was found }


text:
Q: Importing a CSV file into Spyder from a mac I'm just getting started with learning how utilize Spyder. I'm utilizing a mac to do so, if that makes any difference. I'm having a horrible time opening up a csv file on my computer. I'm wondering if someone can tell me what I'm doing wrong?
Here's the code I'm using:
import pandas as pd
one = pd.read_csv("~/Documents/2017Data/2017DATA.csv")

I get the following error when I execute the statements:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb0 in position 592: invalid start byte

A: Try to use different encoding -
import pandas as pd
one = pd.read_csv("~/Documents/2017Data/2017DATA.csv", encoding = "ISO-8859-1")


text:
Q: Diff between sourceurl and linkurl and how to display image attachments for different features in 1 layer What is the difference between the sourceURL and linkURL?
Also, I have a layer that has multiple features.  Each feature has an attached image.  How would I set up the popup to find and show the attachment unique to the feature?
  //define a popup template
        var popupTemplate = new esri.dijit.PopupTemplate({
          title: "{BUILDING}",
          fieldInfos: [
          {fieldName: "FLOOR", visible: true, label:"Floor:"},
          {fieldName: "BUILDING", visible: true, label:"Building Name:"},
          {fieldName: "CAMERA", visible: false, label:"Camera:"},
          ],
          mediaInfos: [{
            "title": "Image:",
            "caption": "",
            "type": "image",
            "value": {
              "sourceURL": "http://gis.aoscloud.net/aosmaps/rest/services/Test/Test/FeatureServer/0/1025/attachments/1201",
              }
          }],
        });

        //create a feature layer based on the feature collection
        var featureLayer = new esri.layers.FeatureLayer("http://gis.aoscloud.net/aosmaps/rest/services/Test/Test/MapServer/0", {
          mode: esri.layers.FeatureLayer.MODE_SNAPSHOT,
          infoTemplate: popupTemplate,
          outFields: ["*"],
        });

A: The source url of the image and the url of a related link. Clicking on the image opens the linkUrl. It's optional.


text:
Q: Yii: Naming relations and fields I wrote some Yii code with the same name for a DB field and a relation:
public function relations()
{
    return array(
        'kin' => array(self::BELONGS_TO, 'Kin', 'kin'),
        'child' => array(self::BELONGS_TO, 'Child', 'child'),
    );
}

Now I understand that this is wrong, because relations "cover" over field attributes and queries like $this->child to get child ID do not work.
My question: Which naming scheme would you suggest for DB fields and for relations?

A: Firstly, I'd avoid naming your primary key after the table. It makes this kind of statement difficult to read. I always name my primary keys something like childId or kinId; that way it's clear what field you're talking about.
I think there is no hard and fast rules about naming, except to use what makes sense in your context. For something like this, assuming I've understood your table structure correctly, I'd be inclined to go for this:
Table 1: kin
Primary key: kinId
Table 2: child
Primary key: childId
Foreign key from table kin: fkKinId
Then, assuming that one kin can have many children, your relation in the Kin model becomes:
public function relations()
{
    return array(
        'children' => array(self::HAS_MANY, 'Child', 'fkKinId'),
    );
}

You can then call the child model for your kin using $this->children if you're inside the Kin model.


text:
Q: How to convert digit month to the full name of month in C# console I want to convert digit month that is inputed by User to the name of month. I find it easily to use if else condition, but is there any function I can use without using condition? It's take me to write alot of code.
Note : Just month!
int month = 0;
bool TempResult = false;
Console.Write("Month: ");
TempResult = int.TryParse(Console.ReadLine(), out Month);

A: There are two reasonably simple options:

*

*Construct a date using that number as the month, and then format it with a custom format, e.g.
DateTime date = new DateTime(2000, month, 1);
string monthName = date.ToString("MMMM");

*Use DateTimeFormatInfo.MonthNames
DateTimeFormatInfo info = CultureInfo.CurrentCulture.DateTimeFormat;
// The array is 0-based, e.g. MonthNames[0] is for January
string monthName = info.MonthNames[month - 1];

Both of these will take the name from the current culture; in either case you can specify a different CultureInfo if you want. (In the first case, use it as a second argument to ToString.)


text:
Q: Fire JavaScript event with custom parameter and catch it with jQuery I'm currently firing a custom JavaScript event like that from the page itself to the iframe document:
// Create iframe
var iframe = document.createElement('iframe');
iframe.setAttribute('src', 'URL to load');
document.body.appendChild(iframe);

// Event itself
var event = document.createEvent('HTMLEvents');
event.custom = 'example param';
event.initEvent('custom', false, true);
iframe.contentWindow.window.document.dispatchEvent(event);

Now on this iframe page I have jQuery available. How could I catch the event (which works) and also (important) get the custom (object) parameter?
Catching it like that:
$(document).on('custom', function(e, param) {
    alert(e); // [object Object] -> normal jQuery event data without any special data
    alert(e.custom); // undefined
    alert(param); // undefined
});

How could I get the custom parameter data without adding jQuery to the page itself which contains the iframe?

A: jQuery wraps the original DOM event. The original event should be available through the originalEvent property of the jQuery event.
e.originalEvent.custom

should evaluate to your custom value, in this case 'example param'.


text:
Q: Do Java CDI execute CDI all events: @Observes @Initialized(ApplicationScoped.class) ServletContext in the same thread? I have 2+ CDI beans that observes Java servlet context lifecycle.
@ApplicationScoped
public class ServletContextLifecycleListener1 {

    public void contextInitialized(@Observes @Initialized(ApplicationScoped.class) ServletContext sc) {
    }

    public void contextDestroyed(@Observes @Destroyed(ApplicationScoped.class) ServletContext sc) {
    }
}

@ApplicationScoped
public class ServletContextLifecycleListener2 {

    public void contextInitialized(@Observes @Initialized(ApplicationScoped.class) ServletContext sc) {
    }

    public void contextDestroyed(@Observes @Destroyed(ApplicationScoped.class) ServletContext sc) {
    }
}

My question is: This is not @ObservesAsync, This is @Observes.
Does the container make sure ServletContextLifecycleListener1.contextInitialized and ServletContextLifecycleListener2.contextInitialized get executed in the same thread? (main thread?)
The same question for contextDestroyed.
I googled, but I couldn't find my answer.
Any comments?
Thanks.

A: Yes, the execution happens in the same thread which is also why you can also order observers via @Priority.
The moment you (or container) fire a synchronous event, CDI container immediately identifies all relevant observer methods, sorts them by @Priority, and executes one at a time. Once done, the execution returns to the code which fired the event.
It behaves slightly differently for transactional observers and obviously completely differently for asynchronous observers which don't block code execution.
Related specification text can be found here (CDI 3.0 variant but this is the same for CDI 2 to CDI 4).


text:
Q: Clustered index on frequently changing reference table of one or more foreign keys My specific concern is related to the performance of a clustered index on a reference table that has many rapid inserts and deletes.
Table 1 "Collection" collection_pk int (among other fields)
Table 2 "Item" item_pk int (among other fields)
Reference Table "Collection_Items" collection_pk int, item_pk int (combined primary key)

Because the primary key is composed of both pks, a clustered index is created and the data physically ordered in the table according to the combined keys.
I have many users creating and deleting collections and adding and removing items to those collections very frequently affecting the "Collection_Items" table, and its clustered index.
QUESTION PART: Since the "Collection_Items" table is so dynamic, wouldn't there be a big performance hit on constantly resorting the table rows because of the clustered index ?
If yes, what should I do to minimize this ?

A: Assume you delete and re-insert a set of rows for a given (compound) primary key:

*

*If the table index is clustered, you drop the leaf-level data and any "upper-level" index page data, then add data back to the pages, and add the lookup data in the upper level pages. Call it at best four page writing operations.

*If the table index is non-clustered, you drop the heap data, the "upper-level" index data, and the leaf-level index data, and then write heap data, upper0level index data, and leaf-level index data. At best, that's six page writing operations.

*In either case you'll have to worry about index building/revising, and with non-clustered you have to manage modifications to the heap table as well as tracking all the index-to-data references.

Performance-wise, it certainly seems like the clustered index is the way to go... though certain operational considerations may trump that. (How many drops/inserts, frequency, table growing at then end [idenity values?] or middle [inserting new PK values], overall size, frequency of updates vs. concurrency/locking issues, etc. etc.)
The only way to avoid this is to not have any index on the heap, and the odds are good that you don't want to do that.
In all cases, you may get high table fragmentation, so (depending on overall table size) periodic index rebuilds might be good.
--  Update based on first comment  ------------------
My initial answer was based on the following assumptions:

*

*All rows being dropped within a given transaction (i.e. INSERT or DELETE statement) would be for a single Collection. That is, N Items would be added/dropped for a single collection.

*A single (and preferrably clustered) index would exist on columns (Collection_pk, Item_pk), with Collection_pk the firxt column.

Done this way, whenever you add or drop a set of rows, only that small part (unless it involves hundreds or more rows) of the index/table would need to be modified. My comments were geared towards that design.
Remember, with a clustered index, the "table itself", i.e. the data rows, is the leaf-level of the clustered index--so, again, only that part of the index would ever need to be modified. With a non-clustered index on top of a heap, you still have those extra pages to maintain, and I think frequent delete/inserts would cause some serious table fragmentation.
If a second index existed on (Item_pk, Collection_pk), which would be necessary if you had to perform lookups by item, then it gets tricky. In this case:

*

*For the same reasons, it would be more efficient to have a clustered index and a non-clustered index.

*Absoutely, you will take a performance hit maintaining that second index, as insertion/deletion actions will occur througout the item-first index all the time.

It sounds like you don't have and don't need that second index, so don't worry about it.


text:
Q: Get JSONObject by some attribute of object from JsonArray I have resevationTickets json array,i need to get specific reservation ticket object from above mentioned json array and using ticket id.how do that?
json array like this:
reservation_tickets[
{object 1},{object 2},{object 3}
]

**object has tx_id;
i need to find right ticket using tx_id

A: org.json.JSONObject
org.json.JSONArray

JSONArray jsonArray = new JSONArray(json_array);
int size = jsonArray.length();

for (int index = 0; index < size; index++) {
    JSONObject json = jsonArray.getJSONObject(index);
    if(json.getString("tx_id") == tx_id){
      //here we go...
    }
}


text:
Q: Compare each spark dataframe element with all the rest of same dataframe I'm looking for efficient way of applying some map function to each pair of elements in a dataframe. e.g.
records = spark.createDataFrame(
    [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')], \
    ['id', 'val'])
records.show()

+---+---+
| id|val|
+---+---+
|  1|  a|
|  2|  b|
|  3|  c|
|  4|  d|
+---+---+

I want to take values a, b, c, d and compare each of them with all the rest:
a -> b
a -> c
a -> d
b -> c
b -> d
c -> d

By comparison I mean custom function that takes those 2 values and calculates some similarity index between them.
Could you suggest efficient way to perform this calculation, assuming input dataframe could contain tenth millions elements?
Spark version 2.4.6 (AWS emr-5.31.0), using EMR notebook with pyspark

A: Collect val column values into lookup column. then compare each value from lookup array with val column.
Check below code.
>>> records\
.select(F.collect_list(F.struct(F.col("id"),F.col("val"))).alias("data"),F.collect_list(F.col("val")).alias("lookup"))\
.withColumn("data",F.explode(F.col("data"))) \
.select("data.*",F.expr("filter(lookup,v -> v != data.val)").alias("lookup")) \
#.withColumn("compare",expr("transform(lookup, v -> val [.....] )")) # May be you can add your logic in this -> [.....]
.show()

+---+---+---------+
| id|val|   lookup|
+---+---+---------+
|  1|  a|[b, c, d]|
|  2|  b|[a, c, d]|
|  3|  c|[a, b, d]|
|  4|  d|[a, b, c]|
+---+---+---------+

A: This is a cross join operation with a collect_list aggregation.  if you want a's matches list to contain only [b,c,d] you should apply that filter before doing the collect_list.
records.alias("lhs")
.crossJoin(episodes.alias("rhs"))
.filter("lhs.val!=rhs.val")
.groupBy("lhs")
.agg(functions.collect_list("rhs.val").alias("lookup"))
.selectExpr("lhs.*", "lookup");


text:
Q: Низкая скорость в туннеле IPsec между Freebsd в одну сторону Есть 2 территориально распределенных офиса соединенных туннелем.
Оба офиса имеют интернет канал 100мегабит статический IP. Шлюзы на FreeBSD. Схема такая:
192.168.1.0/24----FREEBSD_GW1--ipsec-tunnel--FREEBSD_GW0----192.168.0.0/24

Когда передаю данные, независимо от протокола, из GW0 в GW1 то скорость нормальная близка к 100мегабитам. В обратную же сторону скорость передачи колеблется около 200кбайт.сек.(тоесть около 2мегабит).
Причем, если обращаюсь на внешний IP GW и делаю передачу не через туннель в ту же сторону, используя например FTP то скорость нормальная.
Скорость upload/download в интернет нормальная в обоих офисах.
Ошибок в логах racoon и на шлюзах нет.
До какого-то момента все работало нормально. В один момент увеличился пинг до удаленного офиса с 2мс до 47мс после этого начались проблемы. Обращался к провайдеру - ни чем не могут помочь.
Подскажите как определить где затыкается трафик, почему только в одну сторону? Какие инструменты можно использовать на freebsd?  Rонфиг ракуна одинаков на оба сервера:
padding {
    maximum_length 20 ;
    randomize off ;
    strict_check off ;
    exclusive_tail off ;
}

listen {
    isakmp <внешний ip> [500] ;
}

timer {
    counter 5 ;
    interval 20 sec ;
    persend 1 ;
    phase1 30 sec ;
    phase2 15 sec ;
}

remote  anonymous {
    exchange_mode main,aggressive ;
    doi ipsec_doi ;
    situation identity_only ;
    nonce_size 16 ;
    initial_contact on ;
    proposal_check obey ;

    proposal {
        encryption_algorithm 3des ;
        hash_algorithm md5 ;
        authentication_method pre_shared_key ;
        dh_group 2 ;
    }
}

sainfo anonymous {
    pfs_group 2 ;
    lifetime time 5 min ;
    encryption_algorithm 3des ;
    authentication_algorithm hmac_md5 ;
    compression_algorithm deflate ;
}


text:
Q: How to format a block of variables in PHP? I just want to know which way of formatting I should prefer if I have to declare a block of variables.
I saw a alignment-style several times:
$foo    = 'foo';
$bar    = 'bar';
$foobar = 'foobar';
$baz    = 'baz';

and a assignment-style:
$foo = 'foo';
$bar = 'bar';
$foobar = 'foobar';
$baz = 'baz';

Is there a standardized way or a official guideline for this? I already searched for this in PSR-1 and PSR-2 but it seems that these standards do not handle this question.
And if there is no official answer how do other languages handle this and why do they prefer the way they do it?

A: It's up to you. Aligned assignments and comments tend to look quite beautiful, but they tend to be more "maintenance-heavy". For example, a tool-assisted refactoring change of a variable name can throw off your entire indentation.
Unless you maintain that carefully, you can end up with code ten years later like:
$foobiedoobie     = 'foo';
$barquax    = 'bar';
$foob = 'foobar';
$boob        = 'baz';

... as though someone did a drive-by shooting all over your careful formatting. My former workplace was like that -- it's hard to keep these styles looking good in a team setting with a really large codebase, and especially in a version control setting where you might come across these "drive-by shootings" and have to face the difficult decision of leaving it as it is (to avoid committing more code changes than necessary), or fix it (and risk annoying other people on your team).
So these can look really beautiful in the beginning, but unless you maintain their beauty, they can get really ugly over the years.
Meanwhile, take a style like this:
$foo = 'foo';
$bar = 'bar';
$foobar = 'foobar';
$baz = 'baz';

... and it's not quite as pretty -- or at least some may think so. But it'll tend to look pretty much the same no matter how the variables are renamed with refactoring/text find & replace tools.
It's arguably not as pretty, but it's pretty much guaranteed to age well, whereas the former one tends to age well only if you actively maintain it (or don't make any changes to the code).

A: Personally, i prefer the first style, it's more clear and readable, but it's a personal opinion
My advice is to give a suffix for your variables to know very quickly their type:
$vari = 5;              # i => integer
$vara = array("hello"); # a => array
$vars = "hello";        # s => string
// ...

It's simple, but can help a lot when you coding thousands of lines :)

A: It depends on context.
For example (from Zend Framework):
    $this->_mode             = $this->_detectMode();
    $this->_homeDirectory    = $this->_detectHomeDirectory();
    $this->_storageDirectory = $this->_detectStorageDirectory();
    $this->_configFile       = $this->_detectConfigFile();

But if you have comments:
/**
 * @var string
 */
protected $_storageDirectory = null;
/**
 * @var string
 */
protected $_configFile = null;

A: PSR doesn't say a word about it, so generally there's no unified convention. It's a matter of personal preferences or company coding standards.
"Alignment-style", as you called it, maybe looks better, but not every IDE can format code like this (using built-in refactoring features), therefore it may be irritating for some people, as IDE format feature would "broke" the convention when you format whole file with a shortcut.


text:
Q: Java YTApi LiveChatMessage (v 3) I'm trying to work with the YoutubeLiveChat-API in Java.
I'm having trouble to insert a LiveChatMessage because it is always returning the errorcode 400:

{
  "code" : 400,
  "errors" : [ {
    "domain" : "youtube.part",
    "location" : "part",
    "locationType" : "parameter",
    "message" : "liveChatMessage",
    "reason" : "unknownPart"
  } ],
  "message" : "liveChatMessage"
}

The error occurs at the following line:
youtube.liveChatMessages().insert("snippet,liveChatMessage",msg).execute();
I already know that the problem is insert(<String>,msg) but I don't know what to put int for String.

Thank you!


text:
Q: Human readable alternative for UUIDs I am working on a system that makes heavy use of pseudonyms to make privacy-critical data available to researchers. These pseudonyms should have the following properties:

*

*They should not contain any information (e.g. time of creation, relation to other pseudonyms, encoded data, …).

*It should be easy to create unique pseudonyms.

*They should be human readable. That means they should be easy for humans to compare, copy, and understand when read out aloud.

My first idea was to use UUID4. They are quite good on (1) and (2), but not so much on (3).
An variant is to encode UUIDs with a wider alphabet, resulting in shorter strings (see for example shortuuid). But I am not sure whether this actually improves readability.
Another approach I am currently looking into is a paper from 2005 titled "An optimal code for patient identifiers" which aims to tackle exactly my problem. The algorithm described there creates 8-character pseudonyms with 30 bits of entropy. I would prefer to use a more widely reviewed standard though.
Then there is also the git approach: only display the first few characters of the actual pseudonym. But this would mean that a pseudonym could lose its uniqueness after some time.
So my question is: Is there any widely-used standard for human-readable unique ids?

A: Here you go UUID Readable
Generate Easy to Remember, Readable UUIDs, that are Shakespearean and Grammatically Correct Sentences

A: This article suggests to use the first few characters from a SHA-256 hash, similarly to what git does. UUIDs are typically based on SHA-1, so this is not all that different. The tradeoff between property (2) and (3) is in the number of characters.
With d being the number of digits, you get 2 ** (4 * d) identifiers in total, but the first collision is expected to happen after 2 ** (2 * d).
The big question is really not about the kind of identifier you use, it is how you handle collisions.

A: Not aware of any widely-used standard for this. Here's a non-widely-used one:
Proquints
https://arxiv.org/html/0901.4016
https://github.com/dsw/proquint
A UUID4 (128 bit) would be converted into 8 proquints. If that's too much, you can take the last 64 bits of the UUID4 (= just take 64 random bits). This doesn't make it magically lose uniqueness; only increases the likelihood of collisions, which was non-zero to begin with, and which you can estimate mathematically to decide if it's still OK for your purposes.


text:
Q: How to return search results with Sunspot and Solr in rails app? I am having some trouble with Sunspot and Solr.  When I pass a parameter, I'm getting no results.  I've included in the comments at 2 points in the code.
I've confirmed that there is also data in the Review table in my db and that the string does occur in the records.
Any advice on how to return the search results?
    puts "search query is #{params[:search]}"   //returns search query
    if params[:search]
        @search = Review.search do
            fulltext params[:search]
        end
        puts "search results are #{@search.results}"   //returns []
        @reviews_search_results = @search.results
    end

A: Get the search result using
@result = @search.results

Take a look at this railscasts tutorial


text:
Q: Laravel Cant save image using Storage I cant save a image using the storage method.
If I do: $file->move(public_path().'/', $file->getClientOriginalName());
The image will get saved and I can open it in finder.
But if I save the image using:
$extension = $file->guessExtension();
      $filename = 'thumnail_'.$id.'.'.$extension;
      if ($file) {
          $s3 = Storage::disk('public')->put($filename, $file);
      }

It will also get saved to the folder but then I cant open it because the file is corrupted
And to be clear "file" is sent to my model from a controller: $file = $request->file('images');


text:
Q: Regex: how to match a particular syntax when it doesn't include that particular syntax, single line? I have a particular syntax I use in strings which helps me retrieve and insert substrings.
an example:
{{ variable |||
example text
}}

Now I find myself having something like:
{{ variable1 |||

some text

    {{ variable2 |||
some other text
}}
    {{ variable3 |||
even more text
}}

}}

and obvously the regex I use for the first case does not match correctly.
the regex I usually use is:
/\B\{\{(.*?)\|\|\|(.*?)\}\}/

which in the second example matches:
{{ variable1 |||

some text

    {{ variable2 |||
some other text
}}

which is not what I want.
I need a regex to match that particular syntax when it doesn't containt that particular syntax. I've tried many combinations similar to this:
\B\{\{(.*?)\|\|\|(.*(?!\{\{.*?\|\|\|.*?\}\}).*)\}\}

but can't work it out. It would be enough to get only
{{ variable2 |||
some other text
}}

Because after the match I can delete that syntax so that recursively checking I can match everything.
The difficulty I have is that the string I parse is only in one line, so I can't use anythng like
^(?!example).*$

Am I right? What am I missing?
I couldn't find a solution in other questions so I wrote this; sorry if this is a duplicate.
Thank you very much

A: The problem you have here is that you are starting to get past what you can usefully* achieve with a regex - the way things are going now, it looks like sooner or later you'll hit on something like:
{{ variable1 |||

some text

    {{ variable2 |||
some other text
}}
    {{ variable3 |||
even more text

text always here

                            {{ variable4 |||
optional text
}}

}}

}}

In this kind of situation you've gone past the point where you have convenient text substitution and you're creating your own mark-up language and templating system. Once you are aware that is what you are doing, it is not too hard, but it's definitely more of a heavyweight task - you will want to parse your text into a tree (Regexes can be very useful for this) and then use your variables to decide which nodes to show.
The thing to think about if you get to this point is whether you are better off using your own mark-up for this, or whether there is an existing tool that can handle what you need already with minimal changes to your existing documents. There are various templating engines available in JavaScript ( I think Moustache and Handlebars are best known, but tools like JSRender might be worth a look ) and it is very possible that something matches your need already.

* When I say usefully what I mean is that beyond a certain point if you can solve a problem with a Regex it tends to become cumbersome and hard to maintain. Regular Expressions are great tools for simple text operations, but if they get too big or complicated it can be very hard to troubleshoot them.


text:
Q: Creating a copy of a function with some vars fixed Assume I have a function
def multiply_by(x, multiplier):
    return x * multiplier

How can I create a copy of that function and fix the multiplier in that function?
multiply_by_5 = multiply_by?    <-- here I need python magic

such that multiply_by_5 would have only one argument x and the multiplier would be 5? So that
multiply_by_5(2)
10

Is there a way in Python 2.7 to do that?

A: You can use functools.partial with keyword argument:
>>> def multiply_by(x, multiplier):
...     return x * multiplier
...
>>> from functools import partial
>>> multiply_by_5 = partial(multiply_by, multiplier=5)
>>> multiply_by_5(2)
10

A: functools.partial is made exactly for this.
you can use it like
import functools
multiply_by_5=functools.partial(multiply_by,multiplier=5)

A: As suggested by @niemmi's answer, functools.partial is probably the way to go.
However, similar work can be done using curried functions:
def multiply_by(multiplier):
    def multiply(x):
        return multiplier * x
    return multiply

>>> multiply_by_5 = multiply_by(5)    # no magic
>>> multiply_by_5(2)
10

Or using the lambda syntax:
def multiply_by(multiplier):
    return lambda x: multiplier * x

Note that partial is more succinct, more efficient, and more directly express your intent in a standard way. The above technique is an example of the concept called closure, which is means that a function defined in inner scope may refer to variables defined in enclosing scopes, and "close" over them, remembering them, and even mutating them.
Since this technique is more general, it might take the reader of your code more time to understand what exactly do you mean in your code, since your code may be arbitrarily complicated.

Specifically for multiplication (and other operators) partial can be combined with operator.mul:
>>> import functools, operator
>>> multiply_by_5 = functools.partial(operator.mul, 5)
>>> multiply_by_5(2)
10

A: Here's an alternative that doesn't use functools.partial. Instead we define a function inside a function. The inner function "remembers" any of the local variables of the outer function that it needs (including the outer function's arguments). The magic that makes this happen is called closure.
def multiply_factory(multiplier):
    def fixed_multiply(x):
        return x * multiplier
    return fixed_multiply

multiply_by_3 = multiply_factory(3)
multiply_by_5 = multiply_factory(5)

for i in range(5):
    print(i, multiply_by_3(i), multiply_by_5(i))

output
0 0 0
1 3 5
2 6 10
3 9 15
4 12 20

If you want, you can use your existing multiply_by function in the closure, although that's slightly less efficient, due to the overhead of an extra function call. Eg:
def multiply_factory(multiplier):
    def fixed_multiply(x):
        return multiply_by(x, multiplier)
    return fixed_multiply

That can be written more compactly using lambda syntax:
def multiply_factory(multiplier):
    return lambda x: multiply_by(x, multiplier)

A: If you cannot change the multiply_by() function, the simplest and perhaps best way is probably
def multiply_by_5(x):
    return multiply_by(x, 5)

You can also use lambda if you really want a one-liner.
However, you may want to change your first function to
def multiply_by(x, multiplier = 5):
    return x * multiplier

Then you can do either of these:
print(multiply_by(4, 3))
12

print(multiply_by(2))
10


text:
Q: Face Up orientation iPhone Can i somehow disable the Face Up orientation in my iPhone app? OR can i handle it somehow?
It distorts the app's view when kept on flat table.

A: Go to project settings in XCode , click on your target and choose "summary".
Then you'll be able to see under "iPhone/iPod deployment" the following section.
Just remove portrait/upside down and you're set.


text:
Q: Spreadsheetgear chart x-axis text orientation I am using Spreadsheetgear to create and modify charts.  I can create a chart and modify the data easily, however, I cannot seem to modify the orientation of text the way that I want.
The text lies on the x-axis and I am trying to get it to display at a 45 degree angle.  I can do this manually by right clicking on the chart and manually setting the orientation angle to 45, but I want to do this using C#.  Any help would be greatly appreciated.

A: IChart chart = ...;
chart.Axes[SpreadsheetGear.Charts.AxisType.Category].TickLabels.Orientation = 45;


text:
Q: Angular appending html with directives from within a directive I'm trying to write a small directive that will append the validation tags and ngMessages dynamically to the input. But I'm having trouble appending the ng-message attribute to the div.
The idea is to have this,

  <input name='fieldName'>

Turned in to the following according to the provided JSON.

  <input required="required"></input>

 scope.message

I've currently managed to get the ng-required appeneded using the answer to this answer. But I can't seem to append the ng-message tag using the same technique. What should be done differently to solve this issue?
The final directive should be able to generate something like this Fiddle
The current version can be found in the Fiddle here the example works as expected until 'scope' is added. But as soon as 'scope' is added, the example stops working.
Update
I've realized that this only occurse when you add a local scope. This error doesn't occure when using the global scope and accessing the variable using scope.$eval(attrs.message)


text:
Q: Multiple grouping variables using kableExtra I've got the following dataset:
tab <- tibble(year = c(2017,2017,2017,2018,2018,2018)
              mth  = c("Apr", "Apr", "Jun", "Jul", "Jul", "Sep"),
              var1 = 1:6,
              var2 = 10:15)

Is it possible to use kableExtra to generate a table of this data where there are two grouping variables, year and month? This would give:
        var1 var2
2017
    Apr
          1   10
          2   11
    Jun
          3   12
2018
    Jul
          4   13
          5   14
    Sep
          6   15

I've tried:
kable(tab[,3:4]) %>% pack_rows(index = table(year$Month, tab$mth))

It works fine with one grouping variable, but it doesn't work for two grouping variables.

A: This tutorial has great examples and explains how to do this.
library(dplyr)
library(kableExtra)

kable(tab, align = "c", col.names = c("","",names(tab)[3:4])) %>%
  kable_styling(full_width = F) %>%
  column_spec(1, bold = T) %>%
  collapse_rows(columns = 1:2, valign = "top")


text:
Q: Vue + Asp.net rendering issue I have a new asp.net mvc project (not .net core) and I am trying to incorporate Vue js into the project.  I have everything working in a sample project using Webpack+Vue+Asp.Net Mvc, which was created following this article https://medium.com/corebuild-software/vue-js-and-net-mvc-b5cede228626.
The app works great, except for the split second before Vue renders.  There is noticable flashing/popping of the Vue templated code before its rendered to html.  Below is a gif of me refreshing the page and users are able to see the template before Vue renders it into html.

I know why this is happening, but I do not know any ways around it.  Would Server Side Rendering fix this?  Can SSR be done in a non .net core project?
Unfortunately, switching to asp.net core is not an option.  The project will be using Umbraco 7, which cannot run on asp.net core (https://our.umbraco.com/forum/using-umbraco-and-getting-started/93640-net-core).
Below are my files
Index.cshtml
@{
    ViewBag.Title = "Home Page";
}

ASP.NET

ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.

Learn more »

Test

    {{ vueMessage }}
    {{ controllerData }}
    <first-component v-bind:time="new Date()" data="@Model"></first-component>
    <button v-on:click="test">Test</button>

Getting started

            ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
            enables a clean separation of concerns and gives you full control over markup
            for enjoyable, agile development.

Learn more »

Get more libraries

NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.

Learn more »

Web Hosting

You can easily find a web hosting company that offers the right mix of features and price for your applications.

Learn more »

@Scripts.Render("~/Scripts/bundle/home.js")

index.js  (gets compiled to Scripts/bundle/home.js by webpack)
import Vue from 'vue';
import FirstComponent from './sub-components/first-component.vue'

new Vue({
    el: '#app',
    components: {
        FirstComponent
    },
    props: {
        controllerData: Object
    },
    methods: {
        test: function () {
            console.log(this);
        }
    },
    data: function () {
        return {
            vueMessage: 'Message from Vue'
        };
    }
})

first-component.vue
<template>

        {{ time }}
        {{ data }}

</template>

A: Make use of the v-cloak attribute.

...

The attribute is automatically removed by vue when the framework has finished mounting.
The v-cloack attribute does not show or hide your elements - it is basically a marker that indicates if mounting is finished.  You write a css selector to target v-cloack to hide the elements or show a loading indicatior.

A: Switching to .net core or any other server side technology would not help.
The issue is because the html is rendered by the browser as it downloads & before all the script resources have downloaded/parsed/run & rendered the html from the Vue component.
When dealing with mixed rendering (partially server side & partially client side) your best option is to hide the template by default & "show" it once the vue component is setup & ready.
For example in your server side view, hide
 either with an attribute, style or class.

Then in your vue component mounted method set isLoaded to true. This is just one of many ways to hide the component before it's ready.


text:
Q: Kolmogorov Zero One Law First Part :I want to prove that, if I have a sequence of independent Randomvariables $X_{n}$ and $T=\{\exists N \in \mathbb{N}:\forall n\geq N, X_{n}=X_{n+2}\}$, that $P(T)\in\{0,1\}$. I know that I have to show that T is in the Terminal sigma Algebra and then use Kolmogrovs Zero One Law. But I dont know how to show that T is in the terminal sigma Algebra.
Second Part: If $P(T)=1$ and the sequence is i.i.d, then $X_{i}$ is almost sure constant. How would I proof this ?

A: Define $\mathcal{F}_n:=\sigma(X_n,X_{n+1},\ldots)$. Then the tail $\sigma$-algebra is $\tau=\bigcap_{n\ge 1}\mathcal{F}_n$. It is clear that the event $T$ belongs to each $\mathcal{F}_n$ because it does not depend on $(X_1,X_2,\ldots, X_m)$ for any finite $m$, i.e.,
$$
T=\{\exists N: \forall n\ge N\vee m, X_{n}=X_{n+2}\}\in \mathcal{F}_m
$$
for any $m\ge 1$. Thus, $T\in \tau$ and by Kolmogorov's 0-1 law, $\mathsf{P}(T)\in \{0,1\}$.
Next, if $\mathsf{P}(T)=1$, then
$$
\lim_{n\to\infty}\mathsf{P}\!\left(\bigcap_{m\ge n}\{X_m=X_{m+2}\}\right)=1.
$$
However, if $X_1$ is not a constant,
\begin{align}
\mathsf{P}\!\left(\bigcap_{m\ge n}\{X_m=X_{m+2}\}\right)&\le \mathsf{P}\!\left(\bigcap_{m\ge n}\{X_{3m}=X_{3m+2}\}\right) \\
&=\prod_{m\ge n}\mathsf{P}(X_{3m}=X_{3m+2})=0.
\end{align}


text:
Q: javascript reqular expression I am looking for an alternative to the C# Split where I can pass an array of strings.
string[] m_allOps = { "*", "/", "+", "-", "<", ">", "=", "<>", "<=", ">=", "&&", "||" };
string s = "@ans = .707 * sin(@angle)";
string[] tt = s.Split(m_allOps,StringSplitOptions.RemoveEmptyEntries);      // obtain sub string for everything in the equation that is not an operator

I'm sure there is a solution using regEx but I can't seem to figure out how to construct the regular expression.

A: First, get an escape extension method (to use the .NET term) on the RegExp prototype: https://stackoverflow.com/a/3561711/18771
Then:
var m_allOps = ["*", "/", "+", "-", "<", ">", "=", "<>", "<=", ">=", "&&", "||"];
var splitPattern = new RegExp( m_allOps.map(RegExp.escape).join('|') );
// result: /\*|\/|\+|\-|<|>|=|<>|<=|>=|&&|\|\|/

var s = "@ans = .707 * sin(@angle)";
var tt = s.split(splitPattern).filter(function (item) {
    return item != "";
});
// result: ["@ans ", " .707 ", " sin(@angle)"]

where the filter function is the replacement for StringSplitOptions.RemoveEmptyEntries.


text:
Q: Link to Custom list item from Workflow task in SharePoint 2013 How to implement a link field in Workflow task to show associated list item. Basically, user should able to open associated list item from workflow task(All tasks view or my task view)

A: If you mean the task form, use Infopath to edit your task form. From the 'Fields' window. Just drag the 'Related Content' field onto your task form.


text:
Q: How to compare object in mongodb update query We've a MongoDB collection like this:
[
  {
    "field1": {
      "key1": true,
      "key2": false
    }
  },
  {
    "field1": {
      "key1": true,
      "key2": true
    }
  }
  ...
  ...
]

which we need to update with a condition on field1 which is an object.
We have used a query like this:
document.update({
    { field1: { key1: false, key2: true } }
  }, {
    $set: required updates
  }, {
    multi: true
  })
  .then(() => {})
  .catch((err) => {});

however it doesn't seems to be having an effect.
How do we fix this?

A: Try this code:
document.update(
    {
        $and: [{ "field1.key1": false }, { "field1.key2": true }]
    },
    {
        $set:  required updates  // It (required updates) should be an object
    },
    {
        multi: true
    })
    .then(() => { })
    .catch((err) => { });

Hope it gives you an idea!!

A: You need to use .Dot notation for the fields inside object
document.update(
  { "field1.key1": false, "field1.key2": true },
  { "$set": required updates },
  { "multi": true }
)


text:
Q: JQuery scroll() too slow I have the following HTML design with 4 Divs as shown in the diagram.
--------------------------
 fixedHead  |  scrollHead
--------------------------
 fixedBody  |  scrollBody
--------------------------

My requirement is that

*

*when I scroll scrollBody horizontally scrollHead should move
horizontally.

*when I scroll scrollBody vertically fixedBody should
    move vertically.

I am able to achieve this by doing the below code but if the tables are very big around 100 columns and 100 rows
This becomes very slow
Is there any other faster way to achieve this
$('.scrollBody').scroll(function() {
    $('.fixedBody').scrollTop($(this).scrollTop());
    $(".scrollHead").scrollLeft($(this).scrollLeft());
});

A: The problem is that the scroll event can take place very often — dozens of times per second — and the browser will often end up repositioning the elements more often than is strictly necessary.
A common solution to this kind of problem is 'throttling':
$('.scrollBody').scroll( $.throttle( 100, function() {
    $('.fixedBody').scrollTop($(this).scrollTop());
    $(".scrollHead").scrollLeft($(this).scrollLeft());
} ) );

The example above uses Ben Alman's jQuery throttle / debounce plugin, and basically means that the function won't execute more than once every 100 milliseconds — you can alter that figure to try and find a happy responsive medium.

A: If I understand it correctly, this should make the animation last 100 ms:
var duration = 100;
$('.scrollBody').scroll(function() {
  $('.fixedBody').animate({ scrollTop: $(this).scrollTop() }, duration);
  $(".scrollHead").animate({ scrollLeft: $(this).scrollLeft() }, duration);
});

A: You may be able to leverage requestAnimationFrame (with custom throttling) to prevent locking, and saving painting time with the repositioning by using 3D transform offsets instead of modifying scrollLeft and scrollTop.
The code I wrote didn't play well with jsFiddle or jsBin (which is a bit worrying), but worked fine locally. The table is fairly large in size, but doesn't contain a very complicated DOM (each element only contains a text node), so its performance may not be indicative.
See if this works for you (Gist)…
The flow works as follows:

*

*Bind the table body's scroll event to a function which requests an animation frame (rather than executing immediately), unless we're already waiting on a request. Requesting an animation frame means the code will execute as and when the browser has a re-paint coming, instead of forcing it to act immediately, which means it won't block any other code.

*When the animation frame becomes available, check each axis' offset to see if it's changed since last time. If it has, apply the offset as a negative translate value on that axis. Transform is better than scroll offset for paint time since it doesn't need to recalculate any layout CSS: it just moves the existing rendering of the DOM element. 3D translate is even better since on some systems it can offset all the painting to a separate thread (the GPU), freeing up main CPU process even more.

The key elements of the code are below:
var $scrollBody = $( '.scrollBody' );
var $fixedBody  = $( '.fixedBody' );
var $scrollHead = $( '.scrollHead' );

void function persistScrollState(){
    var previousOffset = {
        x : 0,
        y : 0
    };
    var pendingScroll  = false;

    function persistScroll(){
        var offset = {
            x: -$scrollBody.scrollLeft(),
            y: -$scrollBody.scrollTop()
        };

        if( offset.x !== previousOffset.x ){
            $scrollHead.css( { transform : 'translateX( ' + offset.x + 'px ) translateZ( 0px )' } );
        }
        if( offset.y !== previousOffset.y ){
            $fixedBody.css(  { transform : 'translateY( ' + offset.y + 'px ) translateZ( 0px )' } );
        }

        previousOffset = offset;
        pendingScroll  = false;
    }

    $scrollBody.on( 'scroll', function handleScroll() {
        // requestAnimationFrame to avoid resource hogging:
        // https://gist.github.com/paulirish/1579671
        // Use polyfill for non-supporting browsers:
        // https://gist.github.com/paulirish/1579671

        if( !pendingScroll ){
            pendingScroll = requestAnimationFrame( persistScroll );
        }
    } );
}();


text:
Q: Wiki in Teams/Sharepoint we are using Office 365 for our development (Teams for communications and files, which are than stored on Sharepoint. Azure DevOps for agile development). I am struggling to find the right place to manage a central wiki. The Teams wiki for each Channel doesn't support search and you don't get any notifications about new articles. Also in Sharepoint you will only see MHT files, which aren't helpful.
Therefore I tried OneNote with a central wiki notebook that I created in Teams as a tab. This Notebook can also be opened from Sharepoint.
Would this be the best approach? Is there a way to create a NewsFeed in Sharepoint for new OneNote Articles and Changes? Or is there an even better option?
Thanks!

A: I would use the SharePoint modern pages if you need to share a wiki with a larger audience. For a small audience, OneNote wiki should work fine as well.
When someone opens the SharePoint modern pages you're by default in read-only mode and you can also specify who has read or edit access.
To notify people (internally) you can use the Alert Me on the Site Pages library. I have no idea on how to do this in OneNote...
If the wiki is technical, I would place it as close as possible to the repository. In your case Azure Devops.

A: You can use Confluence (Atlassian) and maybe connect it to Sharepoint via an SSO. You'd be able to search through it and it's way faster and user friendly than other alternatives.

A: While all solutions were good, I switched to Azure DevOps Wiki with a single project as this seems to satisfy all requirements the best way. Thanks all!


text:
Q: Word or phrase for behaviors that happen for a while,go away, and come back? I'm look for a word or phrase to describe patterns of behavior that happen for a while, go away for some time, and then happen again. No particular pattern with the phases.

A: It may depend on context, but intermittent is a good possibility here.

intermittent:
occurring at irregular intervals; not continuous or
  steady.

Examples of usage would be:

*

*The patient was having intermittent pains in his side.

*The forecast is for intermittent rain.

sporadic also works in this context.

sporadic:
occurring occasionally, singly, or in irregular or random instances

*

*sporadic loud noises kept startling everyone


text:
Q: Зачем нужно выравнивание в памяти? Зачем выравнивать в памяти,  например,  4 байтные int-ы,  так,  чтобы их адрес был кратен четырем? Ведь оперативная память может выдать на шину данных машинное слово,  начинающееся с любого адреса. Или все дело в кэше процессора,  в котором данные храняться построчно(например по 64 байта),  тогда выравнивание гарантирует что объект точно находиться в одной строке?

A: Цитата из Википедии:

Выравнивание данных в оперативной памяти компьютеров — способ
  размещения данных в памяти особым образом для ускорения доступа.
Центральные процессоры в качестве основной единицы при работе с
  памятью используют машинное слово, размер которого может быть
  различным. Однако, размер слова всегда равен нескольким байтам (байт
  является наименьшей единицей, в которой отсчитываются адреса). Как
  правило, машинное слово равно {\displaystyle 2^{k}} 2^k байтам, то
  есть состоит из одного, двух, четырёх, восьми и т. д. байтов.
Некоторые модели процессоров не могут обращаться к данным в памяти,
  нарушающим границы машинных слов. Некоторые могут обращаться, но к
  невыровненным данным дольше, нежели к данным, находящимся внутри
  целого «машинного слова» в памяти.


text:
Q: How to speed up string cleanup function? I need to cleanup a string, so that certain ASCII code characters are left out of the string, and others are replaced.
I am new to Postgres. My function ufn_cie_easy() performs way too slow:
DECLARE
  letter char = '';
  str_result TEXT = '';
  x integer;
  y integer;
  asc_code int;
BEGIN
  y:=1;
  x:=char_length(arg);
  LOOP
    letter=substring(arg from y for 1);
    asc_code=ascii(letter);
    IF (asc_code BETWEEN 47 and 58) or (asc_code BETWEEN 65 and 90) or (
        asc_code BETWEEN 97 and 122) THEN
      str_result := str_result || letter;
      ELSIF (asc_code BETWEEN 192 and 197) THEN
      str_result := str_result || 'A';
      ELSIF (asc_code BETWEEN 200 and 203) THEN
      str_result := str_result || 'E';
      ELSIF (asc_code BETWEEN 204 and 207) THEN
      str_result := str_result || 'I';
      ELSIF (asc_code BETWEEN 210 and 214) OR (asc_code=216) THEN
      str_result := str_result || 'O';
      ELSIF (asc_code BETWEEN 217 and 220) THEN
      str_result := str_result || 'U';
      ELSIF (asc_code BETWEEN 224 and 229) THEN
      str_result := str_result || 'a';
      ELSIF (asc_code BETWEEN 232 and 235) THEN
      str_result := str_result || 'e';
      ELSIF (asc_code BETWEEN 236 and 239) THEN
      str_result := str_result || 'i';
      ELSIF (asc_code BETWEEN 242 and 246) OR (asc_code=248) THEN
      str_result := str_result || 'o';
      ELSIF (asc_code BETWEEN 249 and 252) THEN
      str_result := str_result || 'u';
      ELSE
      CASE asc_code
        WHEN 352 THEN str_result := str_result || 'S';
        WHEN 338 THEN str_result := str_result || 'OE';
        WHEN 381 THEN str_result := str_result || 'Z';
        WHEN 353 THEN str_result := str_result || 's';
        WHEN 339 THEN str_result := str_result || 'oe';
        WHEN 382 THEN str_result := str_result || 'z';
        WHEN 162 THEN str_result := str_result || 'c';
        WHEN 198 THEN str_result := str_result || 'AE';
        WHEN 199 THEN str_result := str_result || 'C';
        WHEN 208 THEN str_result := str_result || 'D';
        WHEN 209 THEN str_result := str_result || 'N';
        WHEN 223 THEN str_result := str_result || 'ss';
        WHEN 230 THEN str_result := str_result || 'ae';
        WHEN 231 THEN str_result := str_result || 'c';
        WHEN 241 THEN str_result := str_result || 'n';
        WHEN 376 THEN str_result := str_result || 'Y';
        WHEN 221 THEN str_result := str_result || 'Y';
        WHEN 253 THEN str_result := str_result || 'y';
        WHEN 255 THEN str_result := str_result || 'y';
        ELSE str_result := str_result;
      END CASE;
      END IF;
    y:=y+1;
    exit when  y=x+1;
  END LOOP;
  return str_result;
END;

A: The function should be noticeably faster with fewer assignments (none, actually, in this updated version):
CREATE FUNCTION ufn_cie_easy(text)
  RETURNS text AS
$func$
BEGIN
RETURN replace(replace(replace(replace(replace(replace(
         translate($1,'ŠŽšžŸÝÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØÙÚÛÜàáâãäåçèéêëìíîïñòóôõöøùúûüýÿ!"#$%&()*+,-./:;<=>?@[\]^_`{|}~€'ƒ"…†‡ˆ‰‹''""•–—˜™›¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿×Þð÷þÐ'
                     ,'SZszYYAAAAAACEEEEIIIINOOOOOOUUUUaaaaaaceeeeiiiinoooooouuuuyy')
         ,'Œ','OE')
         ,'Æ','AE')
         ,'œ','oe')
         ,'æ','ae')
         ,'ß','ss')
         ,'''','');
END
$func$  LANGUAGE plpgsql;

Assignments are comparatively expensive in plpgsql.
But I suspect you really want to remove all accents (diacritic signs). Postgres provides the function unaccent() with the additional module unaccent:
CREATE OR REPLACE FUNCTION ufn_cie_easy(text)
  RETURNS text AS
$func$
SELECT translate(unaccent(
        replace(replace(replace(replace(replace(
          $1
         ,'Œ','OE')
         ,'Æ','AE')
         ,'œ','oe')
         ,'æ','ae')
         ,'ß','ss')
       ), '!"#$%&()*+,-./:;<=>?@[\]^_`{|}~€'ƒ"…†‡ˆ‰‹''""•–—˜™›¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿×Þð÷þÐ''', '');
$func$  LANGUAGE sql IMMUTABLE;

Substantially faster, yet. And superior in every aspect if you actually want to remove all diacritic signs.
In addition to unaccent():

*

*Include an escaped ' ('') in translate() directly.

*Make it a simple SQL function.

*Make the function IMMUTABLE.

Detailed explanation and more related issues to consider if you need an IMMUTABLE function with unaccent():

*

*Does PostgreSQL support "accent insensitive" collations?
In Postgres 9.5 or older we need to expand ligatures like 'Œ' or 'ß' manually, since unaccent() always substitutes a single letter:
    SELECT unaccent('Œ Æ œ æ ß');

    unaccent
    ----------
    E A e a S

What I would do in Postgres 9.6
After this update to unaccent:

Extend contrib/unaccent's standard unaccent.rules file to handle all
  diacritics known to Unicode, and expand ligatures correctly (Thomas
  Munro, Léonard Benedetti)

Bold emphasis mine. Using unaccent() like instructed in the linked answer above:
CREATE OR REPLACE FUNCTION ufn_cie_easy(text)
  RETURNS text AS
$func$
SELECT trim(regexp_replace(regexp_replace(public.unaccent('public.unaccent', $1)
                                        , '[^a-zA-Z\d\s]', '', 'g')
                         , '\s+', ' ', 'g'));
$func$  LANGUAGE sql IMMUTABLE;

Almost, but not quite 100 % identical to what you had. Better IMHO:

*

*Replace all accents and expands all ligatures with unaccent().

*Remove all noise characters (everything except ASCII letters, digits and white space).

*Fold whitespace to a single space (' ').

*Trim leading and trailing spaces.

A: From what I understand, you could use translate() to achieve what you want.
A small demonstration:
SELECT translate('Some ţext with ひ inţereşt平ing chăracters', 'ţşăひ平', 'tsa');
               translate
────────────────────────────────────────
 Some text with  interesting characters

So, first you put the characters you want to replace, each matching (in the given order!) their replacement in the third parameter to the function.  Then just list all characters that has to be removed, with no match in the replacement list.
For those characters that need a multi-character replacement, you can still use replace() in a similar fashion, but one call per character:
SELECT replace(replace('Æ small blæblæ', 'Æ', 'AE'), 'æ', 'ae');
      replace
───────────────────
 AE small blaeblae

A: FYI, reworked version of the function (incoming: text_to_clean text).
Doesn't look nice, but works:
DECLARE
result text;
BEGIN
result=translate(text_to_clean,'ŠŽšžŸÝÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØÙÚÛÜàáâãäåçèéêëìíîïñòóôõöøùúûüýÿ!"#$%&()*+,-./:;<=>?@[\]^_`{|}~€'ƒ"…†‡ˆ‰‹''""•–—˜™›¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿×Þð÷þÐ','SZszYYAAAAAACEEEEIIIINOOOOOOUUUUaaaaaaceeeeiiiinoooooouuuuyy');
result=replace(result,'Œ','OE');
result=replace(result,'Æ','AE');
result=replace(result,'œ','oe');
result=replace(result,'æ','ae');
result=replace(result,'ß','ss');
result=replace(result,'''','');
return result;
END;

Thanks again for the help.


text: Q: deleted every thing from android phone redmi 3s through twrp now phone can't boot i was installing a rom.I have installed TWRP software and accidentally i have selected all check boxes at the time of wiping the data.It deleted phones system and recovery .Now  my phone can't boot it remains on mi logo . It is not detectable by usb , and volume + power key is also not working it just restarts the phone and again mi logo comes up. what should i do now  make my phone work again. please help


text:
Q: Are there any rescue CD's which are bootable on UEFI and or UEFI with Secure Boot enabled? I'm looking for Rescue CD's like Hiren's Boot CD which allow me to boot without switching to BIOS or turning off Secure Boot. I had no luck finding such thing.
Is it even possible to launch such an utility with Secure Boot enabled?
How can I modify any Rescue CD to launch when in UEFI and Secure Boot enabled? (if possible)


text:
Q: Run after Init, before Page_Load After a PostBack caused by ddlPlant_SelectedIndexChanged, I need to set set HttpContext.Current.Session("PlantNumber").  This needs to happen after ddlPlant loads in Site.Master, but before the code in Default.aspx needs the value.
Public Class SiteMaster Inherits MasterPage
    Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Init
        If (Not Page.IsPostBack) Then
            ddlPlant.DataSource = myDataSource
            ddlPlant.DataBind()
            ddlPlant.SelectedValue = "1"
        End If

        HttpContext.Current.Session("PlantNumber") = ddlPlant.SelectedValue
    End Sub

    Protected Sub ddlPlant_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ddlPlant.SelectedIndexChanged
    End Sub
End Class

Public Class _Default Inherits Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        Dim units As New List(Of EquipmentModel)
        For Each unit As EquipmentModel In getUnits.Out.Results
            If (CStr(unit.Plant_ID) = HttpContext.Current.Session("PlantNumber")) Then
                units.Add(unit)
            End If
        Next

        gvEquipmentUnit.DataSource = units.OrderBy(Function(n) n.Equipment_ID)
        gvEquipmentUnit.DataBind()
End Sub

With the code above, when Session("PlantNumber") is set after PostBack, ddlPlant.SelectedIndex = Nothing, and ddlPlant.SelectedValue is an empty string.
I've tried moving the Session("PlantNumber") = ddlPlant.SelectedValue line to Site.Master's Page_Load instead, but that runs after it is needed in Default.aspx.vb

A: I looked up PreLoad, but apparently it doesn't work for the Master page.
Ultimately, I decided not to use a Session variable, and instead call the control directly from any page that needs that value on load (almost all of them):
DirectCast(Master.FindControl("ddlPlant"), DropDownList).SelectedValue


text:
Q: what's the scope of the variable in *ngFor If I have for example a list that I'm using the ngFor. For example:
<li *ngFor="let contact of Contacts">

What's the scope of contact? It's mean - when I write let contact of Contacts , is it actually declares a new variable? Or, just for the purpose of the list?
And if it is declares a new variable - is it a reusable variable like any other variables? And if yes, then what is the scope? And what is the type of the variable? The type that was declare in the component? (In this case - the contacts).
I try to understand it.


text:
Q: Common English Surnames ending in S A number of common English surnames are the same as common English given names, with the addition of an "S."  Examples are Peters, Daniels, Michaels, Matthews, Roberts, Phillips, Isaacs, Williams, etc.
What is the root cause of this phenomenon?  Is it related to the formation of surnames from patronyms?  Most of that same list also has common variations ending in "-son" (Peterson, Danielson, Robertson, etc.)
Note: I did a Google search around this question, but the results all had to do with pluralizing a surname, or making it possessive.

A: One of the better places to look is with The Guild of One Name Studies a web-site used by genealogists etc.
I couldn't find Peters (it appears not to be one of the names for which they supply a possible etymology). However one that falls into the category is Phillips which you will note from the etymology they deem to be patronymic.

A: According to Mckinley's A History of British Surnames, the major rise of surnames derived from a personal name with the addition of -s or -es was among the "peasant" classes in the late 13th century. These people didn't have hereditary surnames of their own, so the implication is that they adopted their master's name as befitted their social status as they were bonded to him. If you follow that logic, it primarily signified whose property they were as much as anything, although the passage in that link doesn't wholly explore this.
There was then a second wave of Welsh -s names that appeared more widespread in the British Isles in the 16th century. Together with the earlier English 'mutation', that generated most of the -s names we see today.
So they're not quite patronyms, then, but close.


text:
Q: OnLoadOptions cannot be hit in the AsyncPackage extension I want to get access to the VS2019 .suo file and I searched online and here is the suggested method.
Make your package class implements IVsPersistSolutionOpts.
public sealed class MyExtensionPackage : AsyncPackage, IVsPersistSolutionOpts

Add the following code to the package's InitializeAsync method:
var solutionPersistenceService = GetService(typeof(IVsSolutionPersistence)) as IVsSolutionPersistence; solutionPersistenceService.LoadPackageUserOpts(this, "MyOption"); solutionPersistenceService.LoadPackageUserOpts(this, "MyOption2");

Add the OnLoadOptions method
protected override void OnLoadOptions(string key, Stream stream)
{
    if (key.Equals("MyOption", StringComparison.InvariantCultureIgnoreCase))
    {
        _myOption = new StreamReader(stream).ReadToEnd();
    }
    else
    {
        base.OnLoadOptions(key, stream);
    }
}

But when I run and load the extension, I cannot enter into the OnLoadOptions(), is there anything else I need to do to make it work?