text:
Q: Mine Sweeper - getting all cells until they neighbor with a bomb I'm trying to perform the function where i click on a cell , and if it isn't in proximity of a bomb, it'll reveal all up until those who neighbour with a bomb.
I'm practically stuck :
I'm adding the code i think relevant here
//Click cells to reveal + placing mines for the first time
function cellClicked(elCell, i, j) {
  if (!gGame.isOn) return;
  if (gClickCounter === 0) {
    getRandomMine(gLevel.mines, i, j);
    startTimeInterval();
    gClickCounter++;
  }
  var cell = gBoard[i][j];
  console.log('cell:', cell);

  if (cell.isShown) return;
  if (!cell.isShown) {
    cell.isShown = true;
    elCell.classList.add('shown');
    gGame.shownCount++;
    console.log('gGame.shownCount:', gGame.shownCount);
  }
  if (cell.isMine === true) {
    gLivesLeft--;
    var elLives = document.querySelector('.lives');
    elLives.innerHTML = gLivesLeft;
    elCell.innerText = BOMB;
    if (gLivesLeft === 0) {
      gameOver();
    }
  } else {
    var gNegs = countNegs(i, j);
    elCell.innerText = gNegs;
    console.log('elCell:', elCell.dataset.i);
    console.log('elCell:', elCell.dataset.j);

    cell.minesAroundCount = gNegs;
    if (gNegs === 0) {
      //check up
      if (i > 0) {
        var uCell = document.getElementById(gBoard.length * (i - 1) + j);
        if (!gBoard[i - 1][j].isShown && !gBoard[i - 1][j].isMarked) {
          cellClicked(uCell, i - 1, j);
        }
      }
      //check down
      if (i < gBoard.length - 1) {
        var uCell = document.getElementById(gBoard.length * (i + 1) + j);
        if (!gBoard[i + 1][j].isShown && !gBoard[i + 1][j].isMarked) {
          cellClicked(uCell, i + 1, j);
        }
      }

      //check right
      if (j < gBoard.length - 1) {
        var uCell = document.getElementById(gBoard.length * i + (j + 1));
        if (!gBoard[i][j + 1].isShown && !gBoard[i][j + 1].isMarked) {
          cellClicked(uCell, i, j + 1);
        }
      }
    }
  }
}

//counting neighbors
function countNegs(cellI, cellJ) {
  var negsCount = 0;
  for (var i = cellI - 1; i <= cellI + 1; i++) {
    if (i < 0 || i > gBoard.length - 1) continue;
    for (var j = cellJ - 1; j <= cellJ + 1; j++) {
      if (j < 0 || j > gBoard[i].length - 1) continue;
      if (i === cellI && j === cellJ) continue;

      if (gBoard[i][j].isMine) {
        negsCount++;
      }
      if (negsCount === 0) {
      }
    }
  }
  return negsCount;
}

and the entire code is here :
https://codepen.io/Aegtar/pen/XWaLLzz
Would appreciate any life savers here!


text:
Q: STM32H743VI jumps randomly in a nonflashable state we are using a STM32H743VIT6 on a custom board with a JLink debugger. Out of the blue the processor jumps in a state where it isn't possible to flash the ECU anymore. The board is running but nether JMem nor our IDE (uVision) are able to access or detect the controller. Has anyone else encountered this behaviour so far? Google wasn't helpful either.

A: It is almost impossible to archive unless you enable RDP (which is very hard to archive if it was not the intention of the programmer).
You probably have screw-up the board design. You should have pull-up resistors on the debug lines and NRST connected to the programmer.
If you do not have NRST available simple solder the wire to the NRST, and when the programming probe connects to the uC, connect it to the GND.
If the NRST line is connected to the programmer you need to select nn the configuration "Connect under Reset"

A: We found the answer to our problem. Like @0___________ suggested we had an error in the board design. The NRST line had a condensator which after sufficient loading was pulling the pin up and causing the board to permanently stay in Reset until it had time to unload. After a bit of soldering the problem was solved.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Looping through columns and creating worksheets, error 1004 I have an original file "Categories_by_Year.xlsm" where I have sheets for each year between 2010 and 2014 containing different categories and data (one category per column). What I want is for each year a new workbook to be created and than each category to be saved as a new worksheet in the file. The first row of each column is the category name, which is used for the new worksheets' names. From row 2 to the last not empty row - the data is copied and then transposed in the new worksheet.
When I run the following code, the file and the first sheet is created (the first column is copied and transposed in the new file). However, after that i got run-time error '1004'. I tried starting with different columns and it still trows an error after creating the first one.
Sub NewShForEachCategory()
Dim LastRow As Double

For year = 2010 To 2014

      Workbooks.Add
      ActiveWorkbook.SaveAs Filename:="C:\" & CStr(year) & ".xls", FileFormat:=xlExcel8

      Workbooks("Categories_by_Year.xlsm").Activate

For col = 1 To 35

  If Not IsEmpty(Workbooks("Categories_by_Year.xlsm").Worksheets(CStr(year)).Cells(1, col)) Then

  Category = Workbooks("Categories_by_Year.xlsm").Worksheets(CStr(year)).Cells(1, col).Value
  LastRow = Workbooks("Categories_by_Year.xlsm").Worksheets(CStr(year)).Cells(Rows.Count, col).End(xlUp).Row

   Workbooks("Categories_by_Year.xlsm").Worksheets(CStr(year)).Range(Cells(2, col), Cells(LastRow, col)).Copy
   Workbooks(CStr(year) & ".xls").Activate
   Workbooks(CStr(year) & ".xls").Worksheets.Add.Name = Category
   Workbooks(CStr(year) & ".xls").Worksheets(Category).Cells(1, 1).PasteSpecial Transpose:=True
  End If

Next col

Next year

End Sub

A: Untested:
Sub NewShForEachCategory()

Dim wbCBY as Workbook, wbY as Workbook, Category
Dim sht as Worksheet, year as Long, col as Long

    Set wbCBY = Workbooks("Categories_by_Year.xlsm")

    For year = 2010 To 2014

         Set wbY = Workbooks.Add()
         wbY.SaveAs Filename:="C:\" & CStr(year) & ".xls", _
                   FileFormat:=xlExcel8

         Set sht = wbCBY.Worksheets(CStr(year))

         For col = 1 To 35

            Category = Trim(sht.Cells(1, col).Value)

            If Len(Category) > 0 Then

              sht.Range(sht.Cells(2, col), _
                        sht.Cells(sht.Rows.Count, col).End(xlUp)).Copy

              With wbY.Worksheets.Add()
                 .Name = Category
                 .Cells(1, 1).PasteSpecial Transpose:=True
              End With

            End If

        Next col

    Next year

End Sub


text:
Q: Trying To pass list of data in from controller to partial view in mvc I am trying to pass list of data through viewbag  from controller to partial view but getting error
in login form after submitting data taking it from formcollection through HttPost and once action complete it return to home page from there i am calling method Page_Init inside that in  'loadmessage' method i am trying to return list to a partial view "Header" based on condition.but not able to perform getting error
Home controller
[HttpPost]
public ActionResult Login(FormCollection form)
{
 return View("Home");
}

in Home.cshtml
calling method page_init in controller
$.get("/Home/Page_Init",null, function (data) {
           alert(data);
       });

Home controller
 public ActionResult Page_Init()
    {
     loadMessages();
     return view("Home");
    }

public ActionResult loadMessages()
{
 List<MessageModel> lstMessages = new List<MessageModel>();
 List<MessageModel> lstInfoMessages = new List<MessageModel>();
lstInfoMessages = lstMessages.Where(msg => msg.MESSAGE_TYPE.Equals(CommonConstants.SAFETY_MESSAGE_INFO, StringComparison.InvariantCultureIgnoreCase)).ToList<MessageModel>();
if (lstInfoMessages.Count > 0)
{
 ViewBag.lstInfoMessages = 1;
 ViewBag.lstInfoMessages1 = lstInfoMessages;
 return PartialView("Header", lstInfoMessages);
}

}

also trying to go to partial view from Home view
@ViewBag.lstInfoMessages1
@if (ViewBag.lstInfoMessages == 1)
{
    @Html.Partial("Header",ViewBag.lstInfoMessages1)
}

Expected that list of information should go to partial view and bind
Error:Not getting Exact syntax what to do and how to proceed the steps tried above throw error

A: @Html.Partial method does not accept the dynamic value – so we need to cast it to the actual type.
@model MessageModel   //you need to give correct path of MessageModel
@ViewBag.lstInfoMessages1
@if (ViewBag.lstInfoMessages == 1)
{
    @Html.Partial("Header", (List<MessageModel>)ViewBag.lstInfoMessages1)
}

In Header Partial view, you can retrieve list using @Model


text:
Q: redefinition of unused function in python I have 2 python files in the same folder utils.py and preprocessing.py.
I have two functions defined in utils.py file: preprocess_text, text2seq_generator
I need to use these functions in preprocessing.py. But I'm getting unable to import and warning saying redefinition of unused preprocess_text from line 19
Code:
utils.py
from __future__ import print_function
from collections import defaultdict
from collections import Counter
from string import punctuation
#import pdb

def filter_text(text):
    return ''.join([c for c in text if c not in punctuation]).lower()

def preprocess_text(file_path_src, file_path_tar, max_feats):
    f_src = open(file_path_src)
    f_tar = open(file_path_tar)
    vocab = defaultdict(int)
    freq_src = defaultdict(int)
    freq_tar = defaultdict(int)
    sents_src = [line.rstrip() for line in f_src.readlines()]
    sents_tar = [line.rstrip() for line in f_tar.readlines()]

    for sent in sents_src:
        sent = filter_text(sent)
        for word in sent.split():
            freq_src[word] += 1

   for sent in sents_tar:
       for word in sent.split():
           freq_tar[word] += 1

   freq_sorted_src = Counter(freq_src)
   freq_sorted_src = freq_sorted_src.most_common(max_feats)
   freq_sorted_tar = Counter(freq_tar)
   freq_sorted_tar = freq_sorted_tar.most_common(max_feats)

   freq_words_src = map(lambda x:x[0], freq_sorted_src)
   freq_words_tar = map(lambda x:x[0], freq_sorted_tar)

   vocab_src = dict({v:k for k, v in enumerate(freq_words_src)})
   vocab_tar = dict({v:k for k, v in enumerate(freq_words_tar)})

   vocab_src["UNK"] = max_feats
   vocab_src["<s>"] = max_feats + 1
   vocab_src["</s>"] = max_feats + 2

   vocab_tar["UNK"] = max_feats
   vocab_tar["<s>"] = max_feats + 1
   vocab_tar["</s>"] = max_feats + 2
   #pdb.set_trace()
   return vocab_src, vocab_tar, sents_src, sents_tar

def text2seq_generator(vocab_src, vocab_tar, sents_src, sents_tar):
    unk_key = vocab_src["UNK"]
    for sent_src, sent_tar in zip(sents_src, sents_tar):
        seq_src = map(lambda x:vocab_src.get(x, unk_key), filter_text(sent_src).split())
        seq_tar = map(lambda x:vocab_tar.get(x, unk_key), sent_tar.split())
        #pdb.set_trace()
        yield seq_src, seq_tar

 #vs, vt, ss, st = preprocess_text('../data/training.hi-en.en', '../data/training.hi-en.hi', 5000)
 #for x,y in text2seq_generator(vs, vt, ss, st):
 #print(y)

preprocessing.py file:
  from keras.preprocessing.text import Tokenizer
  from keras.preprocessing.sequence import pad_sequences
  import codecs
  import pdb
  import numpy as np
  from utils import preprocess_text,text2seq_generator

Error :
  from keras.preprocessing.text import Tokenizer
  from keras.preprocessing.sequence import pad_sequences
  import codecs
  import pdb
  import numpy as np
  from utils import preprocess_text

  Traceback (most recent call last):

   File "<ipython-input-8-335a30ab7871>", line 6, in <module>
from utils import preprocess_text

  ImportError: cannot import name 'preprocess_text'

warning:
   redefinition of unused preprocess_text from line 19

A: It seems you have another package called utils somewhere in your PYTHONPATH that conflicts with your current file.
You can explicitly load your module from its path with the importlib module.
Add these lines to preprocessing.py (python 3.3 and 3.4):
from importlib.machinery import SourceFileLoader

utils = SourceFileLoader("utils", "/path/to/utils.py").load_module()
utils.preprocess_text(...)

For python3.5+, you should use:
import importlib.util
spec = importlib.util.spec_from_file_location("utils", "/path/to/utils.py")
utils = importlib.util.module_from_spec(spec)
spec.loader.exec_module(utils)
utils.preprocess_text(...)

A: Option 1
You run it from a python IDE (instead of running it from the commandline). Then the IDE (at least with spyder this is the case) will look in your path environmental variable for the utils.py script. Which most likely isn't there.
Solution 1
Add these lines at the start of your script:
import sys
sys.path.insert(0, 'directory_of_utils.py_script')
from utils import preprocess_text, text2seq_generator

Or just change your working directory:
import os
os.chdir('directory_of_utils.py_script')
from utils import preprocess_text, text2seq_generator

Option 2
You already installed the module utils. Therefore, the script will try to find the function preprocess_text in this module (BTW: this will not happen if you run it via the commandline).
Solution 2
Rename utils.py (And if running from IDE add the lines from solution 1!).


text:
Q: SQL Query- To get a record specific to one particular value only I have a table like below:
SID   GRADE
1       A
1       B
1       C
2       A
2       D
3       A
4       A
5       B

Now, I want only those records as an output wherein if a SID is only having grade as 'A', but no other grades-- those SIDs will be selected
Output will be:
SID     GRADE
3         A
4         A

I have already implemented this via below:
SELECT SID, MIN(GRADE)
FROM MYTABLE
GROUP BY SID
HAVING COUNT(GRADE) = 1
   AND MIN(GRADE) = 'A'

Just want to check if there is any other options available to achieve this output?

A: I'd use STRING_AGG as an aggregation function. It's a little simpler as you save the count condition and it does also work for other grades (..which are not by chance at the beginning of the alphabet).
SELECT sid, string_agg(grade)
FROM MYTABLE
GROUP BY sid
HAVING string_agg(grade) = 'A'

A: If inside one SID there is no way to have multiple A grades then below query will be enough
select a.SID from MYTABLE a
where a.grade = 'A'
  and not exists (select * from MYTABLE b where b.SID = a.SID and b.grade != 'A')

In case, when grade may be null condiftion should be slight different
select a.SID from MYTABLE a
where a.grade = 'A'
  and not exists (select * from MYTABLE b where b.SID = a.SID and (b.grade != 'A' or b.grade is null))

And full version - where there may be multiple A grades inside one SID and grade may be null
select DISTINCT a.SID from MYTABLE a
where a.grade = 'A'
  and not exists (select * from MYTABLE b where b.SID = a.SID and (b.grade != 'A' or b.grade is null))

A: Solution:
SELECT SID, 'A' AS GRADE
FROM (
SELECT SID,
SUM(CASE WHEN GRADE <> 'A' THEN 1 ELSE 0 END) AS LOGIC
FROM MYTABLE
GROUP BY SID
)
WHERE LOGIC = 0
ORDER BY SID

A: Do a GROUP BY. Use HAVING to return each SID which has MAX(GRADE) = 'A', i.e. no other grades.
SELECT SID, MAX(GRADE)
FROM MYTABLE
GROUP BY SID
HAVING MAX(GRADE) = 'A'

Edit: If you instead want to search for another grade, that is not the minimum (or maximum), you can add a MIN(GRADE) condition to the HAVING clause. E.g.
SELECT SID, MAX(GRADE)
FROM MYTABLE
GROUP BY SID
HAVING MAX(GRADE) = 'B'
   AND MIN(GRADE) = 'B'

Will perform well on most databases. (However, Hana is unknown territory to me.)


text:
Q: Is it a bad idea to use Apache HTTPD to proxy tomcat Fronting tomcat with httpd solves a big problem for us. We can separate httpd and tomcat to different machines, i.e., put the sever that hosts httpd in DMZ and leave the server that hosts tomcat behind a more secure firewall, as it needs to make database connections,
which is not allowed from within DMZ. We use AJP (mod_proxy_ajp).
We haven't seen any performance issues in our production environment. But I bumped into the following recently
"Whatever you do, using Apache HTTPD to proxy your requests should be avoided at all costs, as it will decrease your performance by nearly 50%."
from http://www.mulesoft.com/tomcat-performance.
I'd like get people's expert opinion regarding the statement.
Thanks,

A:
Is it a bad idea to use Apache HTTPD to proxy tomcat

NO, it can actually speed up services if configured and utilized correctly. Just keep in mind what environment you're using it in. It may not be necessary to run this in a development environment or internal private network, unless you're running a mixed environment of different services on the same server.
In fact, you can take a ton of load off tomcat by proxying request through Apache. You can setup Apache to perform all compression, encryption, and CA Cert management, while at the same time proxing request via AJP to tomcat. You can also leverage it to run multiple services off the same server using virtual hosts and sub-domains.

We haven't seen any performance issues in our production environment.
  But I bumped into the following recently "Whatever you do, using
  Apache HTTPD to proxy your requests should be avoided at all costs, as
  it will decrease your performance by nearly 50%." from
  http://www.mulesoft.com/tomcat-performance.

It's all according to how you setup Apache and what protocols you configure for proxying. Some protocols and modules are slower than others. However, I haven't seem much degradation as a result of using AJP with mod_proxy. It's been working great. Plus we also use mod_security for added intrusion and exploit detection.
One of the biggest advantages, which comes with Apache, is the ability to load balance and scale services.


text:
Q: How to make a bubble sort function utilizing a given total number of list of elements and indexes by user input? (kotlin) I am trying to make a bubble sort function ( bubbleSort() ) to sort the numbers given by user input,  then order these numbers in ascending order.
So far, in my code:

*

*this part cannot be modified

fun main(args: Array<String>) {
    var list = mutableListOf<Int>()
    print("Please Enter the Total Number of Elements :")
    var number = readLine()!!.toInt()
    for (i in 1..number) {
        print("Please enter the $i Element :")
        var value = readLine()!!.toInt()
        list.add(value)
    }
    val sorted = bubbleSort(list)
    println("The Sorted List in Ascending Order : $sorted")
}

*this part is where I am able to make all the changes

fun bubbleSort(list: MutableList<Int>): Unit {
    var swap = true
    while(swap){
        swap = false
        for(i in 0 until list.size-1){
            if(list[i] > list[i+1]){
                var temp = list[i]
                list[i] = list[i+1]
                list[i + 1] = temp
                swap = true
            }
        }
    }
    for (k in list) print("$k ")
}

An expected output could be:

*

*Please Enter the Total Number of Elements :5

*Please enter the 1 Element :4

*Please enter the 2 Element :3

*Please enter the 3 Element :-1

*Please enter the 4 Element :9

*Please enter the 5 Element :6

*The Sorted List in Ascending Order : [-1, 3, 4, 6, 9]
when I run my current code the output is:

*

*Please Enter the Total Number of Elements :5

*Please enter the 1 Element :4

*Please enter the 2 Element :3

*Please enter the 3 Element :-1

*Please enter the 4 Element :9

*Please enter the 5 Element :6

*-1 3 4 6 9 The Sorted List in Ascending Order : kotlin.Unit

Any possible feedback or hint on how to approach the format of the sorted list is greatly appreciated.


text:
Q: C, Getting errors in symbolic constant definitions (possibly in function parameters) I have been getting this error in a C program that I'm writing:
progra10.c:48:25: error: expected ';', ',' or ')' before numeric constant
#define LAST_INDEX ARRAY_SIZE - 1

and
program10.c:47:25: error: expected ';', ',' or ')' before numeric constant
 #define ARRAY_SIZE       20
                         ^
program10.c:48:25: note: in expansion of macro 'DATA_SIZE'
 #define LAST_INDEX      ARRAY_SIZE - 1
                         ^~~~~~~~~~
program10.c:64:42: note: in expansion of macro 'LAST_INDEX'
 int  sequential_search(int seq_data, int LAST_INDEX, int search_target,

I use the GCC compiler with this command:

gcc -Wall -ansi -oprogram10.exe program10.c -lm

This is the code that the error seems to be referring to:
#define COURSE_NUMBER "C Programming" /* Class */
#define PROGRAM_NUMBER 10 /* Program Number */
#define PROGRAMMER_NAME "Name" /* Programmer's Name */
#define ARRAY_SIZE 20 /* Size of the array */
#define LAST_INDEX ARRAY_SIZE - 1 /* The last index in the array */

I have no clue why it would be causing that error.  I've checked for open comments, tabs, open strings, among other things, and I have not been able to fix this error.  While compiling, this error is the only error, only it repeats for every time that LAST_INDEX is used in a function call parameter in main.  I know the rest of my program has errors, but the compilation doesn't even show them, leading me to believe that it can't get past this.
The functions look like this:
Function Prototype:
int  sequential_search(int seq_data, int LAST_INDEX, int search_target,
                                                   int target_location);

Function Call:
sequential_search(seq_data, LAST_INDEX, search_target, target_location);

Function Definition:
int sequential_search(int seq_data, int LAST_INDEX, int search_target,
                                                    int target_location)

Thanks for your help!

A: The problem is that you're trying to declare a function parameter call LAST_INDEX, but LAST_INDEX is defined as a macro, so expands to an expression.  The declarator for a function parameter needs to be a single identifier (the name you want to give the parameter), not an expression.


text:
Q: TinyMCE & Flask - Image upload I am trying to integrate tinyMce on a blog app using Flask.  I have the images uploading and displaying correctly inside the editor but when the user wants to read the entire article my image does not display.
     * Serving Flask app "blog.py"
     * Environment: production
       WARNING: This is a development server. Do not use it in a production deployment.
       Use a production WSGI server instead.
     * Debug mode: off
    [2020-08-31 19:08:56,321] INFO in __init__: Blog site startup.
     * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

    ...

    127.0.0.1 - - [31/Aug/2020 19:09:07] "POST /image-upload HTTP/1.1" 200 -
    Validating Image....[OK]
    /static/user_uploads/img_0992.jpeg
    127.0.0.1 - - [31/Aug/2020 19:09:37] "POST /create-post HTTP/1.1" 302 -
    127.0.0.1 - - [31/Aug/2020 19:09:37] "GET /index HTTP/1.1" 200 -
    127.0.0.1 - - [31/Aug/2020 19:09:37] "GET /jsglue.js HTTP/1.1" 200 -
    127.0.0.1 - - [31/Aug/2020 19:09:40] "GET /post/1 HTTP/1.1" 200 -
    127.0.0.1 - - [31/Aug/2020 19:09:40] "GET /jsglue.js HTTP/1.1" 200 -
    127.0.0.1 - - [31/Aug/2020 19:09:40] "GET /post/static/user_uploads/img_0992.jpeg HTTP/1.1" 404

TinyMCE init:
tinymce.init({
    selector: 'textarea',
    plugins: [
        'advlist autolink link image imagetools lists charmap print preview hr anchor pagebreak spellchecker',
        'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking',
        'save table contextmenu directionality template paste textcolor codesample'
    ],
    toolbar: 'insertfile undo redo | styleselect | bold italic forecolor | alignleft aligncenter alignright alignjustify | bullist numlist | link image | print preview media fullpage | emoticons',
    images_upload_url: Flask.url_for('blog.image_uploader'),
    images_reuse_filename: false,
    automatic_uploads: true,
});

Flask view:
@blog.route('/image-upload', methods=['POST'])
@login_required
def image_uploader():
    """
    Upload post images from tinyMce editor.
    Save image to path.
    returns: json { location: path }
    """

    # Get the file user has uploaded inside the tinymce editor.
    uploaded_file = request.files.get('file')

    if uploaded_file:
        filename = secure_filename(uploaded_file.filename).lower()

        # Validate the contents of the file.  Check the header of the file is infact an image.
        valid_img_ext = validate_img(uploaded_file.stream)

        # Split filename and extension, rename & add correct extension.
        filename = secure_filename(os.path.splitext(filename)[0] + valid_img_ext)

        img_path = os.path.join(current_app.config['IMG_UPLOAD_PATH'], filename)

        # Check if user directory exists, create if nessecary.
        if not os.path.exists(current_app.config['IMG_UPLOAD_PATH']):
            try:
                os.makedirs(current_app.config['IMG_UPLOAD_PATH'])
            except OSError as e:
                if e.errno != errno.EEXIST:
                    raise

        # Save the image.
        uploaded_file.save(img_path)
        location = url_for('static', filename='user_uploads/' + filename)
        print(location)

        # Return image path back to editor
        return jsonify({'location': location})

    abort(Response('404 - Image failed to upload'))

@blog.route('/post/<post_id>')
def post_detail(post_id):
    post = Post.query.get(post_id)
    return render_template('article.html', post=post)

As you can see above, the image validates and saves correctly.  I then try to view the article and I get a 404 - /post/static/user_uploads/img_0992.jpeg How do I stop the path being prefixed with /post/ so I simply get /static/user_uploads/img_0992.jpeg
for example, changing
@blog.route('/post/<post_id>')

to
@blog.route('/<post_id>')

The image loads as it should, but this isn't a feasible solution
127.0.0.1 - - [31/Aug/2020 19:45:05] "GET /static/user_uploads/img_0992.jpeg HTTP/1.1" 200 -

Also, if I open up the console and add a / to the img src, the image loads as it should.

to

Where am I going wrong with this?

A: Solved:
Needed to add
    relative_urls: false,
    images_upload_base_path: '/static/user_uploads',

to the tinymce.init()
example:
tinymce.init({
    selector: 'textarea',
    relative_urls: false,
    plugins: [
        'advlist autolink link image imagetools lists charmap print preview hr anchor pagebreak spellchecker',
        'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking',
        'save table directionality template paste codesample'
    ],
    toolbar: 'insertfile undo redo | styleselect | bold italic forecolor | alignleft aligncenter alignright alignjustify | bullist numlist | link image | print preview media fullpage | emoticons',
    images_upload_url: Flask.url_for('blog.image_uploader'),
    images_reuse_filename: false,
    automatic_uploads: true,
    images_upload_base_path: '/static/user_uploads',
});

and return the filename from the view
return jsonify({'location': filename})

A: It prevents a new copy from being created when the uploaded file is edited with "images Tools". It is created only when you upload a new file.
Make the following setting.
tinymce.init({
            paste_data_images: false,
            images_reuse_filename: true,
            automatic_uploads: true,
            images_upload_handler: function (blobInfo, success, failure, progress) {

                var  formData = new FormData();
                formData.append('file', blobInfo.blob(), blobInfo.filename());

                $.ajax({
                    type:'POST',
                    url:  'ajax.upload.php',
                    data: formData,
                    dataType: 'json',
                    cache:false,
                    contentType: false,
                    processData: false,
                    success:function(r){
                        if (r.error) {
                            alert("r.error");
                        } else if (r.message) {
                            success(r.message.location);
                        }
                    },
                    complete: function (jqXHR,exception) {
                       $('.tox-dialog__busy-spinner').hide();
                    },
                    error: function (jqXHR,exception) {

                    }
                });

            }
  });

PHP CODE:
 // Yüklenecek dosya adı, yüklenen dosyaların adlarında var ise mevcut ad kullanılır.
    if( $_SESSION['TEMP_UPLOADED_IMAGES'][$handle_normal->file_src_name] === true ){

        // Dosya zaten mevcut ise otomatik olarak yeniden adlandırmayı devre dışı bırakır. Bu durumda mevcut dosya isimleri var ise üzerine yazılır.
        $handle_normal->file_overwrite = true;

        // Yüklenecek dosyanın adı mevcut adıyla kullanılır. Yeni adlandırma yapılmaz.
        $random_file_name = $handle_normal->file_src_name_body;
    } else {
        // Yüklenecek dosya rastgele adlandırılır.
        $random_file_name = $vd->randomNumbers(10));
    }

This code will run on every file upload. (after upload)
$_SESSION['TEMP_UPLOADED_IMAGES'][$handle_normal->file_dst_name] = true;


text:
Q: Axios 403 response springboot I have a backend api and when i try to access it from a frontend client i get 403.
I set the base URL
const api = axios.create({
    baseURL: 'http://localhost:8080'
});

Then i make login with an user and password and store the accessToken. The axius.post works fine
export default function Login() {

    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');

    const history = useHistory();

    async function login(e){
        e.preventDefault();

        const data = {
            username,
            password,
        };

        try {
            const response = await api.post('auth/signin', data);

            console.log(response.data.accessToken)

            localStorage.setItem('username', username);
            localStorage.setItem('accessToken', response.data.accessToken);

            history.push('/books')
        } catch (err) {
            alert('Login failed! Try again!');
        }
    };

When i try to authenticate using the accesToken and make the axius.get i receive error 403
export default function Books(){

    const [books, setBooks] = useState([]);
    const [page, setPage] = useState(0);

    const username = localStorage.getItem('username');
    const access_token = localStorage.getItem('accessToken');

    const history = useHistory();

    useEffect(() => {

        api.get('api/book/v1', {
            Headers: {
                Authorization: `Bearer ${access_token}`
            },
            params: {
                page: 0,
                size: 10,
                direction: 'asc'
            }
        }).then(response => {
            setBooks(response.data._embedded.bookVOList)
        })

    })

The client runs on localhost:3000 and the server on localhost:8000
Here's the SecurityConfig class
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .httpBasic().disable()
            .csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                    .authorizeRequests()
                    .antMatchers("/auth/signin", "/auth/refresh", "/api-docs/**", "/swagger-ui.html**").permitAll()
                    .antMatchers("/api/**").authenticated()
                    .antMatchers("/users").denyAll()
                .and()
                    .cors()
                .and()
                .apply(new JwtConfigurer(tokenProvider));
    }}

And here's the WebConfig class
@Configuration
public class WebConfig implements WebMvcConfigurer {

        @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            .allowedOrigins("http://localhost:3000", "http://localhost", "http://localhost:8080")
            .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD", "TRACE", "CONNECT")
            .allowCredentials(true);
    }

I've already tried to use proxy and adding @CrossOrigin to the controller class
I've used .allowedMethods("*") on addCorsMapping too but also didn't work


text:
Q: How To Track For Which Foreign Key To Add A Value To? (ex: Add The Data For The Correct User FK) I have no idea how to even phrase this correctly, so I hope my title was not too far off.
I know how to add values to a table using PHP and passing values via SQL. However, what I don't know how to do is how to ensure the correct foreign key is used for the particular entry.
I think it's best to describe through example.
Say I have a userbase table that has a usernameID(PK). Now say I have another table called age and that has a column called age and usernameID(FK).
So what I'm saying is that there is a usernameID as a foreign key in the age table. Now, say when I have a form on a website and it asks for an age for a person and that person is logged in, how can I ensure that when I add the age of this particular user, that it gets added for the correct usernameID(FK). I'm going to make the assumption that the usernameID is all ready created, but I juts need to know how to ensure that the data gets connected to the right FK.
Does this make sense what I am saying? I've been searching google for this but have no idea how to describe what I even want!

A: While creating table define foreign key constraint.
Eg.
CREATE TABLE Age
(
id int NOT NULL,
age int NOT NULL,
username varchar(10),
PRIMARY KEY (id),
FOREIGN KEY (username) REFERENCES User(username)
);

Here, User is the parent table where username column as primary key and in age table as foreign key. If you have used this in your DB for defining FK then on your PHP code it auto show err if trying to put anything other than value allowed.
I hope it will help.


text:
Q: Str_Replace with query results I have a MySql DB and in the Table 'Klant' I have the column names:
ID
Naam
Email
Soort
Status

I get the column names with this query:
$strSQL = "select column_name from information_schema.columns where table_name='Klant'";

And I am selecting the data from the Table with this simple query:
$strSQL1    = "SELECT * FROM NAW.Klant";

What I want to do is search a text and with str_replace I want to replace the column_names with the data from the DB. For example:
If I type in Hello Naam, your email adress is Email I would want it to display Hello Robert your email adress is robert@gmail.com. And I will put that in a loop to do it for every row. I am currently using this:
$ID         = $row['Klant_ID'];
$Naam       = $row['Naam'];
$Email      = $row['Email'];
$Soort      = $row['Soort'];
$Naam       = $row['Status'];
$vaaw       = array("[ID]","[Naam]", "[Email]", "[Soort]", "[Status]");
$vervang    = array("$ID","$Naam", "$Email", "$Soort", "$Status");

echo str_replace($vaaw, $vervang, $message);

The reason I do not want to use this anymore is because if I ever need to change/add/delete a column the code would still work. (I know it is a bad idea to change columns but you never know.) And also this code will work with other Tables/DB's to.
I have tried loads of things to get this to work but I just haven't got a clue how to do this and it has been bugging me for almost 2 days now. If someone knows a function or a way to do this it would be very helpful!

A: Try this:
<?php
$strSQL = "select column_name from information_schema.columns where table_name='Klant'";

$con=mysqli_connect('host', 'username', 'password', 'db');

if(!$con){
    //error
}

$result=mysqli_query($con,$strSQL);

if(!$result){
    //error
}

$table_columns=array();
//$row=mysqli_fetch_assoc($result);
while($row=mysqli_fetch_assoc($result))
{
    $table_columns[]=$row['column_name'];
}

$query="select * from NAW.Klant "; //limit 10";

$result=mysqli_query($con,$query);

if(!$result){
    //error
}

$greeting_text="";

while($row=mysqli_fetch_assoc($result)){
    $greeting_text.= (isset($row['naam']))? "Hello {$row['naam']}":""; // because you want the 'hello'
    for($i=1;$i< count($table_columns);$i++){
        $greeting_text.=" Your ".$table_columns[$i]." is ".$row[$table_columns[$i]].", ";
    }
   $greeting_text.="\n";
}
echo $greeting_text; //test your result

If you have a predefined string template (to be replaced by column names or their values), you need to change that code when there is any change in the table columns. I simply choose to dynamically generate the string depending on the availability of columns. But if you need to use a predefined string, it is not difficult to do so.

A: I solved it using the script that HamZa linked in the comments. Since he is not posting it as an answer I will do it myself because I think it could help others.
The code that solved the problem is this:
$connection = mysql_connect('localhost', 'root', 'pw') or die('couldn\'t connect to the database.
'. mysql_error());
mysql_select_db("NAW");
$strSQL1    = "SELECT * FROM Klant";
$result = mysql_query($strSQL1, $connection) or die('Something went wrong with the query.
'. mysql_error());
while($row = mysql_fetch_assoc($result)){
    $text = $_POST['naam'];
    foreach($row as $k => $v){
        $text = str_replace('['.$k.']', $v, $text);
    }
    echo $text;
    echo "
";
}


text:
Q: Firestore Security Rules: 'request.auth.uid' Is Null With Android Request Environment

*

*Android device: Google Pixel 2

*Android OS version: 9

*Google Play Services version: 14.3.66 (100400-213742215)

*Firebase/Play Services SDK version: 16.0.1

*FirebaseUI version: ui-firestore:4.2.0, ui-auth:4.1.0.

Issue
request.auth.uid != null is always null when using Firestore security rules.
When the uid is null the user on the Android client is both logged in via the Firebase UI and showing in the Firestore Authentication console.

Implementation
Sample Firestore Security Rule
service cloud.firestore {
function signedInOrPublic() {
  return request.auth.uid != null;
}

match /databases/{database}/documents {
  match /{document=**} {
    allow read;
  }
}

// Add to user collection.
match /databases/{database}/documents {
  match /users/{userId}/{collectionOrAction}/{content} {
    allow create: if signedInOrPublic();
  }
}

Android Call to Firestore Collection
The call works as expected without any stringent rules set.
usersCollection.document(userId).collection(actionCollection)
.document(content.id)
.set(ContentAction(Date(), content.id, content.title, content.creator,
content.qualityScore)).addOnSuccessListener {
updateUserActionCounter(userId, countType)
}.addOnFailureListener {
Log.w(LOG_TAG, "User content action update FAIL.")
}

Firebase Libraries
implementation 'com.firebase:firebase-client-android:2.5.2'
implementation 'com.google.firebase:firebase-core:16.0.3'
implementation 'com.google.firebase:firebase-firestore:17.1.0'
implementation 'com.firebaseui:firebase-ui-firestore:4.1.0'
implementation 'com.firebaseui:firebase-ui-auth:4.0.0'

google-services.json Configuration
I have a version of the google-services.json for my debug and release builds in order to keep a separate Firestore project / environment / analytics for the production version of the app. I'm wondering if this could be effecting Firestore rules even though this setup is working as expected for every other part of Firebase so far (Firestore db, Analytics, etc.).
app>src>debug>google-services.json
app>src>release>google-services.json
Attempted Solutions

*

*I tried checking if request.auth was not null in the Firestore Rules file.

*I attempted to use request.auth.uid == userId in the rule above comparing the request.auth.uid to the userId in the path route.

*I attempted to use request.auth.token.email == userEmail in a rule which fails.

*Adding additional Firebase Auth library even though I already have the Firebase UI Auth library which is already as seen above: implementation 'com.google.firebase:firebase-auth:16.0.4

*Adding implementation 'com.google.android.gms:play-services-auth:16.0.1'

*Upgrading Firestore libraries to firebase-core:16.0.4, firebase-firestore:17.1.1, firebase-ui-firestore:4.2.0, firebase-ui-auth:4.1.0.

*I built a simple sample app in order to see if the security rules worked with a straightforward implementation.

Sample App
In the sample app there is a Sign in /out button which signs the user in and out depending on their current sign in state. The sign in state is displayed in the top left corner. The Get data button retrieves a String field from Firestore database based on the Firestore Security Rules.

Error
2018-10-14 15:21:59.123 24192-24192/firebase_security_sample.adamhurwitz.firebasesecuritysample
E/AndroidRuntime: FATAL EXCEPTION: main
Process: firebase_security_sample.adamhurwitz.firebasesecuritysample, PID: 24192
com.google.android.gms.tasks.RuntimeExecutionException: com.google.firebase.firestore.FirebaseFirestoreException: PERMISSION_DENIED: Missing or insufficient permissions.
    at com.google.android.gms.tasks.zzu.getResult(Unknown Source:15)
    at firebase_security_sample.adamhurwitz.firebasesecuritysample.MainActivity$onCreate$2$1.onComplete(MainActivity.kt:63)
    at com.google.android.gms.tasks.zzj.run(Unknown Source:4)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
 Caused by: com.google.firebase.firestore.FirebaseFirestoreException: PERMISSION_DENIED: Missing or insufficient permissions.
    at com.google.firebase.firestore.obfuscated.zzhc.zza(com.google.firebase:firebase-firestore@@17.1.1:119)
    at com.google.firebase.firestore.obfuscated.zzk.zza(com.google.firebase:firebase-firestore@@17.1.1:134)
    at com.google.firebase.firestore.obfuscated.zzak.zza(com.google.firebase:firebase-firestore@@17.1.1:384)
    at com.google.firebase.firestore.obfuscated.zzm.zza(com.google.firebase:firebase-firestore@@17.1.1:235)
    at com.google.firebase.firestore.obfuscated.zzfv.zza(com.google.firebase:firebase-firestore@@17.1.1:7521)
    at com.google.firebase.firestore.obfuscated.zzfv$1.zza(com.google.firebase:firebase-firestore@@17.1.1:172)
    at com.google.firebase.firestore.obfuscated.zzgc.zzb(com.google.firebase:firebase-firestore@@17.1.1:3109)
    at com.google.firebase.firestore.obfuscated.zzfh.run(com.google.firebase:firebase-firestore@@17.1.1:1117)
    at com.google.firebase.firestore.obfuscated.zzfc$zza.zza(com.google.firebase:firebase-firestore@@17.1.1:67)
    at com.google.firebase.firestore.obfuscated.zzfc$zzc.zza(com.google.firebase:firebase-firestore@@17.1.1:110)
    at com.google.firebase.firestore.obfuscated.zzgv$1.onMessage(com.google.firebase:firebase-firestore@@17.1.1:107)
    at io.grpc.ForwardingClientCallListener.onMessage(ForwardingClientCallListener.java:33)
    at io.grpc.ForwardingClientCallListener.onMessage(ForwardingClientCallListener.java:33)
    at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1MessagesAvailable.runInContext(ClientCallImpl.java:526)
    at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37)
    at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:123)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at com.google.firebase.firestore.obfuscated.zzgf$zza.run(com.google.firebase:firebase-firestore@@17.1.1:203)
    at java.lang.Thread.run(Thread.java:764)
 Caused by: io.grpc.StatusException: PERMISSION_DENIED: Missing or insufficient permissions.
    at io.grpc.Status.asException(Status.java:534)
    at com.google.firebase.firestore.obfuscated.zzhc.zza(com.google.firebase:firebase-firestore@@17.1.1:117)
    at com.google.firebase.firestore.obfuscated.zzk.zza(com.google.firebase:firebase-firestore@@17.1.1:134)
    at com.google.firebase.firestore.obfuscated.zzak.zza(com.google.firebase:firebase-firestore@@17.1.1:384)
    at com.google.firebase.firestore.obfuscated.zzm.zza(com.google.firebase:firebase-firestore@@17.1.1:235)
    at com.google.firebase.firestore.obfuscated.zzfv.zza(com.google.firebase:firebase-firestore@@17.1.1:7521)
    at com.google.firebase.firestore.obfuscated.zzfv$1.zza(com.google.firebase:firebase-firestore@@17.1.1:172)
    at com.google.firebase.firestore.obfuscated.zzgc.zzb(com.google.firebase:firebase-firestore@@17.1.1:3109)
    at com.google.firebase.firestore.obfuscated.zzfh.run(com.google.firebase:firebase-firestore@@17.1.1:1117)
    at com.google.firebase.firestore.obfuscated.zzfc$zza.zza(com.google.firebase:firebase-firestore@@17.1.1:67)
    at com.google.firebase.firestore.obfuscated.zzfc$zzc.zza(com.google.firebase:firebase-firestore@@17.1.1:110)
    at com.google.firebase.firestore.obfuscated.zzgv$1.onMessage(com.google.firebase:firebase-firestore@@17.1.1:107)
    at io.grpc.ForwardingClientCallListener.onMessage(ForwardingClientCallListener.java:33)
    at io.grpc.ForwardingClientCallListener.onMessage(ForwardingClientCallListener.java:33)
    at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1MessagesAvailable.runInContext(ClientCallImpl.java:526)
    at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:37)
    at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:123)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
    at com.google.firebase.firestore.obfuscated.zzgf$zza.run(com.google.firebase:firebase-firestore@@17.1.1:203)
    at java.lang.Thread.run(Thread.java:764)

Firebase Security Rule
service cloud.firestore {

    match /databases/{database}/documents {
        match /testCollection/testDoc {
            allow read: if request.auth.uid != null
        }
    }
}

build.gradle (app)
buildscript {
ext.kotlin_version = '1.2.71'
repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.2.1'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    classpath 'com.google.gms:google-services:4.1.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}

allprojects {
repositories {
    google()
    jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

build.gradle (project)
apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
       applicationId "firebase_security_sample.adamhurwitz.firebasesecuritysample"
    minSdkVersion 21
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'

    implementation 'com.google.android.gms:play-services-auth:16.0.1'
    implementation 'com.google.firebase:firebase-core:16.0.4'
    implementation 'com.google.firebase:firebase-auth:16.0.4'
    implementation 'com.google.firebase:firebase-firestore:17.1.1'
    implementation 'com.firebaseui:firebase-ui-firestore:4.2.0'
    implementation 'com.firebaseui:firebase-ui-auth:4.1.0'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

apply plugin: 'com.google.gms.google-services'

MainActivity
class MainActivity : AppCompatActivity() {

lateinit var signInStatus: TextView

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    FirebaseApp.initializeApp(
            this,
            FirebaseOptions.Builder()
                    .setApplicationId("1:63924060965:android:c387085babd1a8a4") // Required for Analytics.
                    .setApiKey("AIzaSyCi4h6WBX495xmzaRsLYro2_Vd9UcB3bpg") // Required for Auth.
                    .setDatabaseUrl("https://security-rules-sample.firebaseio.com") // Required for RTDB.
                    .setProjectId("security-rules-sample")
                    .build(),
            "firestoreSecuritySample")
    signInStatus = findViewById(R.id.signInStatus) as TextView

    val user = FirebaseAuth.getInstance().currentUser
    if (user != null) {
        signInStatus.text = user.displayName
    } else {
        signInStatus.text = "logged out"
    }

    signInButton.setOnClickListener {
        if (FirebaseAuth.getInstance().currentUser == null) {
            val providers = Arrays.asList<AuthUI.IdpConfig>(
                    AuthUI.IdpConfig.GoogleBuilder().build())

            startActivityForResult(
                    AuthUI.getInstance()
                            .createSignInIntentBuilder()
                            .setAvailableProviders(providers)
                            .build(),
                    123)
        } else {
            AuthUI.getInstance().signOut(this).addOnCompleteListener {
                signInStatus.text = "logged out"
            }
        }
    }

    getDataButton.setOnClickListener {
        FirebaseFirestore.getInstance(FirebaseApp.getInstance("firestoreSecuritySample"))
                .collection("testCollection").document("testDoc").get().addOnCompleteListener {
                    if (FirebaseAuth.getInstance().currentUser != null) {
                        firestoreResult.text = it.result!!.get("testField").toString()
                    }
                }
    }
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == 123) {
        if (resultCode == Activity.RESULT_OK) {
            val user = FirebaseAuth.getInstance().currentUser
            if (user != null) {
                signInStatus.text = user.displayName
            }
        }
    }

}

A: Thank you to Sam Stern from the Google Developer Relations team for helping debug! I've tested the fix below for both the sample app I created above as well as my app in production.

I am pretty sure your issue comes from this line:
FirebaseApp.getInstance("firestoreSecuritySample")
  You are using a custom FirebaseApp to talk to the database, but you're not using the same FirebaseApp when you sign in. There's a separate auth state for each app instance.
Try changing your sign in code to pass the app to getInstance:

        startActivityForResult(
                // SEE BELOW FOR CHANGE
                > AuthUI.getInstance(FirebaseApp.getInstance("firestoreSecuritySample"))
                        .createSignInIntentBuilder()
                        .setAvailableProviders(providers)
                        .build(),
                123)


text:
Q: Get the same exact syntax of Javascript engine (and code) representation of Arrays I guess I need something like Array.toString() but it alters a little how we represent an Array in code.
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.toString();

It returns "Banana,Orange,Apple,Mango" which is different from["Banana", "Orange", "Apple", "Mango"],
My purpose is to inject it to some JS-SQL driver statement. I hope this is clear.

A: For that you can just stringify it via JSON.stringify() and get the array's representation as JSON.

let fruits = ["Banana", "Orange", "Apple", "Mango"];
let str = JSON.stringify(fruits);

console.log(str);


text:
Q: Openstack All-In-One Single Machine Networking I'm having a hard time configuring an Openstack environment based on the All-In-One Single Machine installer for bridged networking in my LAN.
My objective is to SSH into the instances created in Openstack from my LAN.
The server is an Ubuntu 16.04 LTS with minimal installation and OpenSSH. The network configuration of the server is:

auto enp3s0
iface enp3s0 inet static
address 10.4.4.1
netmask 255.255.255.0
gateway 10.4.4.254
broadcast 10.4.4.255
network 10.4.4.0
dns-nameservers 10.4.1.12 10.4.1.10

Basically my network details are the following:

LAN 10.4.4.0
MASK 255.255.255.0
Gateway/DHCP Server  10.4.4.254

The local.conf file I've used for deploying the devstack is the following:

# Sample ``local.conf`` for user-configurable variables in ``stack.sh``

# NOTE: Copy this file to the root DevStack directory for it to work properly.

# ``local.conf`` is a user-maintained settings file that is sourced from ``stackrc``.
# This gives it the ability to override any variables set in ``stackrc``.
# Also, most of the settings in ``stack.sh`` are written to only be set if no
# value has already been set; this lets ``local.conf`` effectively override the
# default values.

# This is a collection of some of the settings we have found to be useful
# in our DevStack development environments. Additional settings are described
# in https://docs.openstack.org/devstack/latest/configuration.html#local-conf
# These should be considered as samples and are unsupported DevStack code.

# The ``localrc`` section replaces the old ``localrc`` configuration file.
# Note that if ``localrc`` is present it will be used in favor of this section.
[[local|localrc]]

# Minimal Contents
# ----------------

# While ``stack.sh`` is happy to run without ``localrc``, devlife is better when
# there are a few minimal variables set:

# If the ``*_PASSWORD`` variables are not set here you will be prompted to enter
# values for them by ``stack.sh``and they will be added to ``local.conf``.
FLOATING_RANGE=10.4.4.192/27
FIXED_RANGE=192.168.0.0/24
FIXED_NETWORK_SIZE=256
FLAT_INTERFACE=enp3s0
ADMIN_PASSWORD=nomoresecret
DATABASE_PASSWORD=stackdb
RABBIT_PASSWORD=stackqueue
SERVICE_PASSWORD=$ADMIN_PASSWORD

# ``HOST_IP`` and ``HOST_IPV6`` should be set manually for best results if
# the NIC configuration of the host is unusual, i.e. ``eth1`` has the default
# route but ``eth0`` is the public interface.  They are auto-detected in
# ``stack.sh`` but often is indeterminate on later runs due to the IP moving
# from an Ethernet interface to a bridge on the host. Setting it here also
# makes it available for ``openrc`` to include when setting ``OS_AUTH_URL``.
# Neither is set by default.
HOST_IP=10.4.4.1
#HOST_IPV6=2001:db8::7

# Logging
# -------

# By default ``stack.sh`` output only goes to the terminal where it runs.  It can
# be configured to additionally log to a file by setting ``LOGFILE`` to the full
# path of the destination log file.  A timestamp will be appended to the given name.
LOGFILE=$DEST/logs/stack.sh.log

# Old log files are automatically removed after 7 days to keep things neat.  Change
# the number of days by setting ``LOGDAYS``.
LOGDAYS=2

# Nova logs will be colorized if ``SYSLOG`` is not set; turn this off by setting
# ``LOG_COLOR`` false.
#LOG_COLOR=False

# Using milestone-proposed branches
# ---------------------------------

# Uncomment these to grab the milestone-proposed branches from the
# repos:
#CINDER_BRANCH=milestone-proposed
#GLANCE_BRANCH=milestone-proposed
#HORIZON_BRANCH=milestone-proposed
#KEYSTONE_BRANCH=milestone-proposed
#KEYSTONECLIENT_BRANCH=milestone-proposed
#NOVA_BRANCH=milestone-proposed
#NOVACLIENT_BRANCH=milestone-proposed
#NEUTRON_BRANCH=milestone-proposed
#SWIFT_BRANCH=milestone-proposed

# Using git versions of clients
# -----------------------------
# By default clients are installed from pip.  See LIBS_FROM_GIT in
# stackrc for details on getting clients from specific branches or
# revisions.  e.g.
# LIBS_FROM_GIT="python-ironicclient"
# IRONICCLIENT_BRANCH=refs/changes/44/2.../1

# Swift
# -----

# Swift is now used as the back-end for the S3-like object store. Setting the
# hash value is required and you will be prompted for it if Swift is enabled
# so just set it to something already:
SWIFT_HASH=66a3d6b56c1f479c8b4e70ab5c2000f5

# For development purposes the default of 3 replicas is usually not required.
# Set this to 1 to save some resources:
SWIFT_REPLICAS=1

# The data for Swift is stored by default in (``$DEST/data/swift``),
# or (``$DATA_DIR/swift``) if ``DATA_DIR`` has been set, and can be
# moved by setting ``SWIFT_DATA_DIR``. The directory will be created
# if it does not exist.
SWIFT_DATA_DIR=$DEST/data

At the end of the deployment I'm able to ping from the instance to my LAN and do nslookup on google.com for example, but I can't do it backwards, ping/ssh/telnet the instance in Openstack.
The security group permits all traffic, all ICMP ingress/egress, SSH from everywhere.
I've tried to telnet on my local computer from the Openstack instance and it's showing the IP of the Openstack host, not the host. So I'm missing something in the network topology.

netstat -ant | grep 1716
tcp6       0      0 :::1716                 :::*                    LISTEN
tcp6       0      0 10.4.3.34:1716          10.4.4.1:42992          ESTABLISHED

Is there any type of network deployment I'm missing?
Any advice would be much appreciated!

A: If you are trying to access your instances from the "outside", you will need to create a floating IP pool and assign a floating IP to one of your instances.


text:
Q: (Nuxt.js) Firebase error when using Nuxt.js on top of Vue.js, but works fine with vanilla Vue.js I made a website with pure Vue.js, everything works fine.
However, I transferred the project to Nuxt.js, after setting up "everything", I get this error in the development page:
Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app).

Here's the firebase file ('fb.js') which I used to export the database:
"fb.js" (Root folder)
import firebase from 'firebase/app';
import 'firebase/firestore'

// Initialize Firebase
var config = {
    apiKey: "KEY",
    authDomain: "DOMAIN",
    databaseURL: "DBURL",
    projectId: "PID",
    storageBucket: "SBUCKET",
    messagingSenderId: "MSID"
};

firebase.initializeApp(config);

const db = firebase.firestore();

db.settings({timestampsInSnapshots: true})

export default db;

"component.vue" (Components folder) *This code is not exactly the same as my files, but the key parts are here
<template>

<div class="allprojects" v-for="(project, key) in projects" :key="key">
<span> {{project.title}} </span>
<span> {{project.person}} </span>
<span> {{project.due_date}} </span>
<span> {{project.status}} </span>
</div>

</template>

<script>
import db from '@/fb.js';

export default {

data() {
    return {
        projects: []
    },
created() {
        db.collection('projects').onSnapshot(res => {
            const changes = res.docChanges();

            changes.forEach(change => {
                if (change.type === 'added') {
                    this.projects.push({
                        ...change.doc.data(),
                        id: change.doc.id
            })
          }

}
</script>

"package.json" (Nuxt.js)

{
  "name": "web",
  "version": "1.0.0",
  "description": "Nuxt.js + Vuetify.js project",
  "author": "Alexsander Bispo <35003248+Lexszin@users.noreply.github.com>",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate"
  },
  "dependencies": {
    "date-fns": "^1.30.1",
    "firebase": "^5.9.2",
    "nuxt": "^2.2.0",
    "vuetify": "^1.3.6",
    "vuetify-loader": "^1.0.5"
  },
  "devDependencies": {
    "babel-eslint": "^10.0.1",
    "babel-plugin-transform-imports": "^1.5.1",
    "eslint-config-standard": "^12.0.0",
    "eslint-loader": "^2.1.1",
    "eslint-plugin-html": "^4.0.6",
    "eslint-plugin-import": "^2.14.0",
    "eslint-plugin-node": "^7.0.1",
    "eslint-plugin-promise": "^4.0.1",
    "eslint-plugin-standard": "^4.0.0",
    "stylus": "^0.54.5",
    "stylus-loader": "^3.0.2"
  },
  "main": ".eslintrc.js",
  "license": "ISC"
}

"package.json" (Vue.js)
{
  "name": "tify",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "date-fns": "^1.30.1",
    "firebase": "^5.9.2",
    "vue": "^2.6.6",
    "vue-router": "^3.0.1"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^3.5.0",
    "@vue/cli-plugin-eslint": "^3.5.0",
    "@vue/cli-service": "^3.5.0",
    "babel-eslint": "^10.0.1",
    "eslint": "^5.8.0",
    "eslint-plugin-vue": "^5.0.0",
    "postcss": "^7.0.14",
    "stylus": "^0.54.5",
    "stylus-loader": "^3.0.2",
    "vue-cli-plugin-vuetify": "^0.5.0",
    "vue-template-compiler": "^2.5.21",
    "vuetify": "^1.5.8",
    "vuetify-loader": "^1.0.5"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ],
    "rules": {},
    "parserOptions": {
      "parser": "babel-eslint"
    }
  },
  "postcss": {
    "plugins": {
      "autoprefixer": {}
    }
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not ie <= 8"
  ]
}

As mentioned in the title, this works fine with the vanilla Vue.js, but when built with Nuxt.js, I get this error...


text:
Q: How to center align a group floating buttons in vuetify? This is my code:
<v-container height="0">

  <v-row align="center" justify="center">
    <v-hover v-slot:default="{ hover }" v-for="(option, index) in options" :key="index">
      <v-tooltip top color="transparent">
        <template v-slot:activator="{ on, attrs }">
          <v-btn
            v-bind="attrs"
            v-on="on"
            color="white"
            fab
            dark
            medium
            absolute
            bottom
            left
            @click="OptionSelected(option)"
            :style="{ marginBottom: '120px', marginLeft: 10 + 65*(index) + 'px', marginRight: 10 + 65*(index) + 'px'}"
          >
            <v-img
              height="55"
              width="40"
              style="object-fit: contain; border-radius: 50%"
              :src="option.thumbnail"
            >
            </v-img>
            <v-expand-transition>
              <div
                v-if="hover || option.selected"
                class="d-flex amber v-card--reveal body-1"
                style="border-radius: 50%;"
              >
              </div>
            </v-expand-transition>
          </v-btn>
        </template>
        <div style="margin-bottom: 100px; background-color: white; color: black; padding: 10px; border: 2px solid grey; border-radius: 5px">
          {{ option.title }}
        </div>
      </v-tooltip>
    </v-hover>
  </v-row>
  .......
  </v-container>

I have a group of floating buttons which I am trying to center align horizontally. I tried style="left: 50%; transform: translateX(-50%)". But the buttons did not center align. Can anyone tell me how to do it?
This is my updated code. There are tooltips and hover elements also in my code.

A: Put the <v-btn>s inside a <v-row>, with its justify and align props set to center:

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
})
<script src="https://unpkg.com/vue@2.6.12"></script>
<script src="https://unpkg.com/vuetify@2.3.15/dist/vuetify.js"></script>
<link rel="stylesheet" href="https://unpkg.com/vuetify@2.3.15/dist/vuetify.min.css">

<v-app id="app">
  <v-container class="grey lighten-5 mb-6" >
    <v-row align="center" justify="center">
      <v-btn
             fab
             dark
             medium
             v-for="index in 3"
             >
        {{index}}
      </v-btn>
    </v-row>
  </v-container>
</v-app>


text:
Q: Chrome driver for Selenium stuck in black screen I use Chrome webdriver with Selenium for web scraping on Ubuntu 16.04. Everything works fine until after a few hours, the browser randomly gets stuck into the status of a black screen and does not do anything but wait. I need to manually refresh the browser to make it work again. Some other times the browser is dead shown by not responding to any clicking or scrolling, but is still doing the work in the back.
My question is: can I use the headless mode of Chrome webdriver to avoid this problem? I'm not sure if this is just related to the UI, and there is no way for me to tell whether the webdriver is stuck again without the UI because the problem happens randomly.


text:
Q: KRL convert XML to JSON I'm working on a KRL module for S3. Each request has to be signed, and the signature covers a Date object which has to be within 15 minutes of the current time on AWS. The signature is sent as an 'Authorization' HTTP header.
If I set it up as a datasource I would get the XML > JSON for free. Unfortunately you can't set headers for a datasource request.
I tried content.as('json') but that converts JSON in a string to actual Javascript objects.
k=xml_string.as('json') // returns the xml_string unchanged

How can I convert the returned XML to JSON?


text:
Q: How to create a user control for IPhone? So I read about Interface Builder Plug-Ins but from what I understood they're not supported on IPhone on the MAC.
Basically I want to create a User Control (this is a .NET term) is this possible in iPhone development? A user control is basically like me trying to create my own custom button, or own custom slider, etc so that it is easily re-usable.
Any suggestions? thanks!

A: Nothing so generic as "User Control" (from the sound of it) exists in Cocoa Touch, except that you can directly subclass UIView to make a wholly-new kind of view.
However, you'll probably find it easier to subclass the existing UIButton, UISlider, etc. classes instead. Such subclasses should be lightweight: You shouldn't need to do more than change the control's part images (e.g., the slider's thumb and tracks).
Besides being easier, subclassing the existing classes will also mean your controls will remain consistent in behavior with standard controls. Imagine if you'd implemented your own text field from the ground up prior to Apple adding copy and paste.
Once you've made your subclasses, you should be able to select your controls in IB and set their custom class names to the names of your custom subclasses. You should then be able to add those controls to the Library to reuse them. (Caveat: I only write Mac software, so I don't know whether IB has these features for iPhone development.)

A: My Objective-C is a little rusty (I'm digging back into it as we speak), but what I would do is create an object to control the button. Then you can send messages to the button so it acts consistently between instantiations of the button.
I'd add some code for you to look at, but I've got nephews and nieces climbing all over me (happy 4th of July!) - good luck! (by the way, I'm a fan of adium!)

A: It's easier than you think, actually. While you can't make your own "User Control" so to speak, you can actually customize the appearance of almost every UIKit control anyway, such as custom buttons, and editing text field properties and fonts, etc. You could make a view with this in it, and add it to a parent view at runtime if you so desired. It can be used multiple times, or you can just customize them individually as you need them, which is how I prefer because of the simplicity.


text:
Q: Using a tabstrip with datasource I am pulling in a tabstrip to show details within a template on the kendo grid.  I do my initial pull for the grid, but would like to use a separate datasource for the tabstrip.  I only have one tab that holds all these detail.  Is there a better way of achieving this?  I do want to show everything in the table like the HTML shows, but want to pull it from its own datasource when the detail table is displayed.
I do it elsewhere successfully but that's with using a grid within the template.
Below is the grid code and the template code :
@(Html.Kendo().Grid<InvoiceVM>()
              .Name("grid")
              .Columns(columns =>
              {
                  columns.Bound(i => i.DarwinInvoiceNumber).Title("Invoice").ClientTemplate("#: DarwinInvoiceNumber#").Width(100);
                  columns.Bound(i => i.DivisionID);
                  //columns.Bound(i => i.Date).Format("{0:MM/dd/yyyy}");
                  //columns.Bound(i => i.CheckDate).Format("{0:MM/dd/yyyy}");
                  columns.Bound(i => i.DateDisplay).Title("Date"); //09/26/2017 DS TFS # 2798
                  columns.Bound(i => i.CheckDateDisplay).Title("Check Date"); //09/26/2017 DS TFS # 2798
                  columns.Bound(i => i.Total).Format("{0:C}");
                  columns.Bound(i => i.Employees);
                  columns.Bound(i => i.Employees).Title("Checks").Width(100);
                  columns.Bound(i => i.TotalGross).Title("Gross Wages").Format("{0:C}");
              })
              .Sortable()
            //.Selectable()
              .Scrollable()
              .ToolBar(tools => tools.Excel())
              .Excel(excel => excel
                  .FileName("PayInvoices.xlsx")
                  .Filterable(true)
              )
              .Groupable()
              .ColumnMenu()
              .Pageable()
              .Filterable()
              .ClientDetailTemplateId("template")
              .HtmlAttributes(new { style = "height:600px;" })
              .Reorderable(reorder => reorder.Columns(true))
              .Resizable(resize => resize.Columns(true))
              .DataSource(dataSource => dataSource
                  .Ajax()
                  .PageSize(15)
                  .Read(read => read.Action("Get_InvoicesRead", "PayrollInvoices"))

              )
              .Excel(excel => excel
                  .FileName("InvoiceList.xlsx")
                  .Filterable(true)
                  .AllPages(true)
    //.ProxyURL(Url.Action("Excel_Export_Summaries_Save", "Reports"))
              )
              .Events(events => events.DataBound("dataBound"))
        )

A: Regarding the progress indicator, we use the Kendo Progress Indicator which we start on the select event and stop on the load event:
@(Html.Kendo().TabStrip().Name("myTabStrip")
    .Items(tabs =>
    {
        tabs.Add().Text("T1").LoadContentFrom("Tab1", "Controller", new { Id = Model.Id });
        tabs.Add().Text("T2").LoadContentFrom("Tab2", "Controller", new { Id = Model.Id });
        tabs.Add().Text("T3").LoadContentFrom("Tab3", "Controller", new { Id = Model.Id });
    })
    .Events(e => e
        .ContentLoad("onContentLoad")
        .Select("onTabSelect")
    )
)

Then this script:

You could probably roll your own indicator with same concept.


text:
Q: Rails: Single button boolean form - determining whether to post to :create or :delete I have an app that allows a user to track a song on different websites. A User has_many :trackables and has_many :songs through :trackables.
:trackables table has song_id, user_id, and website
On my index page, I render all @songs. Each song has 3 icons and each icon is an ajax form that, when clicked, posts to trackables_controller with :website as "spotify", "rdio", or "songza" depending on the icon clicked.
If the user has never clicked the icon before, form should post to :create. If the icon was already clicked, but clicked again, form should post to :delete.
I hope that makes sense. I suppose I could just post to create, check if identical record exists (and if so delete). I'm trying to figure out the Railsy way to do this.

A: I believe there should be toggle action in TrackablesController that all three forms point to (but with different song_id and website params). And the logic that creates/deletes trackable should be placed in model Trackable, like so:
class Trackable < ActiveRecord::Base
  ...
  def self.toggle(user, song, website)
    existing_trackable = where(user_id: user.id, song_id: song.id, website: website)

    if existing_trackable.present?
      existing_trackable.destroy_all
    else
      create(user_id: user.id, song_id: song.id, website: website)
    end
  end
end

And it's called likes so:
class TrackableControllers < ApplicationController
  def toggle
    return render json: false unless user_signed_in?
    song = Song.find(params[:song_id])
    return render json: false unless song.present?

    Trackable.toggle(current_user, song, params[:website])
    render json: true
  end
end

It's not CRUD, yep, but it's still REST: there's a resource (Trackable) and there's an action (toggle).


text:
Q: Pointer to a nested list element Take the following list:
lst <- list(a = 1, b = list(c = 2, d = 3))

Now I would like to have a pointer to the d element so that when I update its value, it is reflected in the original list. E.g.:
d <- lst[['b']][['d']] # d should be a reference.
update(d, 5) # custom function for updating by reference.
lst[['b']][['d']]
#> [1] 5

Why do I want this? Because I do all kinds of updates on lists several levels deep, which results in tedious code similar to the following:
lst[['b']][['d']] <- some_function(lst[['b']][['d']], lst[['b']][['c']])

So I wonder if there are any idioms in R which would make the code more concise and readable?

A: We could make use of assign_in from purrr if we can provide the names or index of the nested list
library(purrr)
assign_in(lst, list('b', 'd'), 5)
#$a
#[1] 1

#$b
#$b$c
#[1] 2

#$b$d
#[1] 5

Or with magrittr to update the original object
library(magrittr)
lst %<>%
   assign_in(list('b', 'd'), 5)

A: Here is a base-purrr solution not tested on very deep lists:
lapply(lst, function(x) purrr::modify_at(x,2,function(x) 5))

Or as suggested by @akrun, modify_in that negates the need for lapply:
modify_in(lst, list('b', 'd'), ~ 5)

Result:
$a
[1] 1

$b
$b$c
[1] 2

$b$d
[1] 5


text:
Q: Exceeded maximum execution time google sheets script work around I have a script that runs a function for a set of data that is drawn from a master sheet. Each time the function runs, it draws and processes a data set based on a date designated in a cell in a sheet (cell A3). The date in this cell is updated via a 'for' loop for a date range that I specified. the script can execute 5 complete runs (aka each run execute the function for a day worth of data) of these loops before I run into "Exceeded maximum execution time" some time during the 6th run. All of my data are already saved to the spreadsheet in a continual updating fashion after every run so what I have to do after five cycles is to manually restart the run for another 5 days starting at the 6th day by modifying my script. I am reading about time driven trigger where someone is pausing the script every 5 minutes to get around the 6 minutes execution time limit but it does not suit my needs because I would like a break after every 5 cycles, (not based on time). What I need is to write a script where after running 5 cycles, the script can break and then resume running again for another 5 cycles. Here is what my code looks like:

function runMultipleDates() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  var start = new Date("2018-11-05");
  var end = new Date("2018-11-09");
  var step = 1;

  for (var date1 = start; date1 <= end; date1.setDate(date1.getDate() + step)) {
    var date2 = new Date(date1.getTime());
    date2.setDate(date2.getDate() + 1);
    ss.getSheetByName('Time Range').getRange("A3").setValue(date2);
    runEverything();

  };
}

As you can see, right now I am adjusting the start and end date manually for 5 days, let it run and then restart the process again by adjusting my script start date to be 2018-11-09 and end date to be 2018-11-13 for the next run. This function, on its own, is to able to run for far more than 5 days cycles without the execution time restriction. So the question is whether there is away to pause the script and resume running after 5 cycles of the above script. Any help is greatly appreciated.

A: Thanks for the ideas sent my way. I have found an answer for this problem with the following codes adapted slightly from benlcollins on gitHub. As @Cooper suggested, I ran my function every 5.5 minutes which was just a little more than what it took for me to complete the main function runMultipleDates() (this function processes 5 days at a time on its own) ; I am repeating this 20 times which means it will cover 20x5=100 days which is good enough for me. I am posting this in case it helps someone.

// -----------------------------------------------------------------------------
// add menu
// -----------------------------------------------------------------------------
function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu("Auto Trigger")
    .addItem("Run","runAuto")
    .addToUi();
}
function runAuto() {
  // resets the loop counter if it's not 0
  refreshUserProps();
  // create trigger to run program automatically
  createTrigger();
}

function refreshUserProps() {
  var userProperties = PropertiesService.getUserProperties();
  userProperties.setProperty('loopCounter', 0);
}

function createTrigger() {
    ScriptApp.newTrigger('runGlobal')
      .timeBased()
      .everyMinutes(5.5)
      .create();
}

// -----------------------------------------------------------------------------
// function to delete triggers
// -----------------------------------------------------------------------------
function deleteTrigger() {

  // Loop over all triggers and delete them
  var allTriggers = ScriptApp.getProjectTriggers();

  for (var i = 0; i < allTriggers.length; i++) {
    ScriptApp.deleteTrigger(allTriggers[i]);
  }
}

// -----------------------------------------------------------------------------
// function to run called by trigger once per each iteration of loop
// -----------------------------------------------------------------------------
function runGlobal() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Data');
  // get the current loop counter
  var userProperties = PropertiesService.getUserProperties();
  var loopCounter = Number(userProperties.getProperty('loopCounter'));
  var limit = 20; // create trigger to run program automatically
  // if loop counter < limit number, run the repeatable action
  if (loopCounter < limit) {
    // do stuff
    runMultipleDates();
    // increment the properties service counter for the loop
    loopCounter +=1;
    userProperties.setProperty('loopCounter', loopCounter);
    // see what the counter value is at the end of the loop
    Logger.log(loopCounter);
  }
  // if the loop counter is no longer smaller than the limit number
  else {
    Browser.msgBox("Run Completed");    // Log message to confirm loop is finished
    deleteTrigger();
  }
}


text:
Q: Has RN disabled style prop checking in 0.57.3? Some time back, whenever I used to write <Component styles={{...}}/>
and React used to throw an error, helpfully saying that perhaps I meant style and not styles.
Recently, I wasted a lot of time in figuring out why a certain Text component was not receiving any styles and it turned out that instead of style, I used styles.
My question is, how to enable those errors again?

A: After looking for such warnings in the React & React Native source code, here is what I found.
The function responsible of these warnings is throwOnStylesProp. It is defined in NativeMethodsMixinUtils.js  and used in NativeMethodsMixin.js.
To be able to see these warnings:

*

*You need to be on __DEV__ environment (debug config);

*The component on which you pass styles has to use the NativeMethodsMixin.

Based on these search results, it seems like only some specific RN components uses that Mixin (TextInput, TouchableHighlight, TouchableOpacity).


text:
Q: How can ADO.NET be forced to infer the type of Excel columns as String rather than Double? I have a column in an excel file that contains both strings and numbers. I found through trial and error that ADO.NET infers the type of the column depending on the type of the cells of the first 8 rows. When that happens, all the strings under the column simply don't get added to the DataTable.
My goal is to have ADO.NET read the values under that column as strings.
How can that be done?

A: add imex = 1 to your connection string similar to:
    string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
     "Data Source=" + savePath +
      "; Extended Properties=" + (char)34 + "Excel 8.0;IMEX=1;"
      + (char)34;

The IMEX parameter (1 is input mode) forces the data type of the column to text so that alphanumeric values are handled properly.


text:
Q: Java - Draw a ruler (line with tick marks at 90 degree angle) I'm using Java AWT to draw lines on a panel (Line2D and Graphics2D.drawLine()) and I'm wondering how I can draw a line with tick marks, similar to:
|----|----|----|----|----|
I know the positions I'd like to draw the ticks at in advance.
The lines could be in any position, so the ticks must be drawn at an angle releative to the line itself.
My basic geometry & ability to apply it in Java is failing me. :)

A: I suggest you

*

*implement a ruler-drawing-method that draws a simple horizontal ruler from left to right

*Figure out the desired angle using Math.atan2.

*Apply an AffineTransform with translation and rotation before invoking the ruler-drawing-method.

Here is a complete test-program. (The Graphics.create method is used to create a copy of the original graphics object, so we don't mess up the original transform.)
import java.awt.*;

public class RulerExample {

    public static void main(String args[]) {
        JFrame f = new JFrame();
        f.add(new JComponent() {

            private final double TICK_DIST = 20;

            void drawRuler(Graphics g1, int x1, int y1, int x2, int y2) {
                Graphics2D g = (Graphics2D) g1.create();

                double dx = x2 - x1, dy = y2 - y1;
                double len = Math.sqrt(dx*dx + dy*dy);
                AffineTransform at = AffineTransform.getTranslateInstance(x1, y1);
                at.concatenate(AffineTransform.getRotateInstance(Math.atan2(dy, dx)));
                g.transform(at);

                // Draw horizontal ruler starting in (0, 0)
                g.drawLine(0, 0, (int) len, 0);
                for (double i = 0; i < len; i += TICK_DIST)
                    g.drawLine((int) i, -3, (int) i, 3);
            }

            public void paintComponent(Graphics g) {
                drawRuler(g, 10, 30, 300, 150);
                drawRuler(g, 300, 150, 100, 100);
                drawRuler(g, 100, 100, 120, 350);
                drawRuler(g, 50, 350, 350, 50);
            }
        });

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(400, 400);
        f.setVisible(true);
    }
}

Note, that you could just as easily draw numbers above the ticks. The drawString-calls would go through the same transformation and get nicely "tilted" along the line.

A: Things that need noting:

*

*A perpendicular line has a slope of -1/oldslope.

*In order to support lines in any direction, you need to do it parametrically

*Thus, you have dy and dx across the original line, which means that newdx=dy; newdy=-1*dx.

*If you have it such that <dx, dy> is a unit vector (sqrt(dx*dx+dy+dy)==1, or dx==cos(theta); dy=sin(theta) for some theta), you then just need to know how far apart you want the tick marks.

*sx, sy are your start x and y

*length is the length of the line

*seglength is the length of the dashes

*dx, dy is the slopes of the original line

*newdx, newdy are the (calculated above) slopes of the cross lines

Thus,

*

*Draw a line from <sx,sy> (start x,y) to <sx+dx*length,sy+dy*length>

*Draw a set of lines (for(i=0;i<=length;i+=interval) from <sx+dx*i-newdx*seglength/2,sy+dy*i-newdy*seglength/2> to <sx+dx*i+newdx*seglength/2,sy+dy*i+newdy*seglength/2>

A: I hope you know matrix multiplication. In order to rotate a line you need to multiple it by rotation matrix. (I coudln't draw a proper matrix but assume both line are not separated)
|x'| = |cos(an) -sin(an)| |x|

|y`| = |sin(an)  cos(an)| |y|

The old points are x,y and the new is x',y'. Let us illustrate by an example, lets say you have a vertical line from (0,0) to (0,1), now you want to rotate it by 90 degrees. (0,0) will remain zero so lets just see what happens to (0,1)
|x'| = |cos(90) -sin(90)| |0|

|y`| = |sin(90)  cos(90)| |1|

==
|1 0| |0|

|0 1| |1|

==
| 1*0 + 0*1|

| 0*0 + 1*1|

== |0|

   |1|

you get to horizontal line (0,0),(0,1) like you would expect.
Hope it helps,
Roni


text:
Q: "to ensue" : usage questions Is there an active form to "to ensue" ? I'm familiar with constructions like "The fire started, chaos ensued".

*

*Can one write "The fire ensued chaos" or "The fire ensued by chaos" ? If not, which verb can replace "ensue" here ?

*Does "to ensue" imply a causation effect ? Or can I write "After friday, saturday will ensue"


text:
Q: Storyboard animation I made a small WPF application to slide UserControls in and out, the problem I have is when a UserControl animated to slide in, then I click the button to slide another UserControl in, they both slide out - I'm not sure why this is?
public UserControl1()
{
    InitializeComponent();
}

public void SlideIn(UserControl uc)
{
    ThicknessAnimation tAnimation = new ThicknessAnimation();
    tAnimation.Duration = new Duration(TimeSpan.FromSeconds(0.5));
    tAnimation.From = new Thickness(500, 0, -500, 0);
    tAnimation.To = new Thickness(0);
    tAnimation.DecelerationRatio = 0.9;

    Storyboard.SetTargetName(tAnimation, uc.Name);
    Storyboard.SetTargetProperty(tAnimation, new PropertyPath(MarginProperty));

    Storyboard storyboard = new Storyboard();
    storyboard.Children.Add(tAnimation);
    storyboard.Begin(uc);
    this.Content = uc;
}

public void SlideOut(UserControl uc)
{
    ThicknessAnimation tAnimation = new ThicknessAnimation();
    tAnimation.Duration = new Duration(TimeSpan.FromSeconds(0.5));
    tAnimation.To = new Thickness(-500, 0, 500, 0);
    tAnimation.DecelerationRatio = 0.9;

    Storyboard.SetTargetName(tAnimation, uc.Name);
    Storyboard.SetTargetProperty(tAnimation, new PropertyPath(MarginProperty));

    Storyboard storyboard = new Storyboard();
    storyboard.Children.Add(tAnimation);
    storyboard.Begin(this);
}

private void button1_Click(object sender, RoutedEventArgs e)
{
    SlideOut(userControl1);
    UserControl2 uc2 = new UserControl2();
    SlideIn(uc2);
}

A: Do you set the Name property of the UserControl somewhere? Or to be more precise, do you give the second UserControl a different Name than the first one? Your animations get their target set by
Storyboard.SetTargetName(tAnimation, uc.Name);

so names should be different. Alternatively you may call
Storyboard.SetTarget(tAnimation, uc);

to specify the target.


text:
Q: remove text between ',' and 'space ,' if found using regular expression I have text like this
Vindu1: Antall: 4, Bredde i mm:  , Hoyde i mm: 1.

If there is an empty space followed by ',' (' ,') I want to remove all the text before it until find ','
the result will looks like
Vindu1: Antall 4, Hoyde i mm: 1.

I know I should use preg_replace function to do it but I can't figuere out what is the regular expression

A: You could do:
preg_replace('/(?<=,|^)[^,]+ ,/', '', $str);

Example:
$str = "Vindu1: Antall: 4, Bredde i mm: , Hoyde i mm: 1.";
echo preg_replace('/(?<=,|^)[^,]+ ,/', '', $str);

Output:
Vindu1: Antall: 4, Hoyde i mm: 1.

A: preg_replace('/\\s+,/', ',') should do it

A: $text = 'Vindu1: Antall: 4, Bredde i mm: , Hoyde i mm: 1.'

if(strstr($text, ' ,'))
{

    $text=explode(' ,', $text);
    $text1 = $text[0];
    $text2 = $text[1];

    $text = explode(',', $text1);

    $result = $text[0].','.$text2;

}

Apologies for the variable naming, can't think of anything sensible at the moment.


text:
Q: SQL Counting and Average in one query I have the following tables:

*

*employee(ename,street,city) where ename is primary key

*company(cname, city) where cname is primary key

*works(ename,cname,salary) where ename,cname is primary key and ename references employee and cname references company.

For each employee name in the works table, I need to find the total number of companies they work for and the average salary.
I have some simple SQL experience, but this advanced aggregate and nested queries is pretty new to me.
I need one query to do this, so the output would be equal to the number of distinct enames in the works table, where each row in the output would have a number of jobs and a number - avg(salary), and i assume a employee name as well.
Any help or suggestions i could use would be appreciated.
This is a homework question, it's the last one on the list, all the other ones are working within the XAMMP environment, using PHPmyAdmin.
Thank you!

A: Select
    employee.ename
    , avg(works.salary) as avgsalary
    , count(company.cname) as numjobs
from
   employee
left join
    works
      on employee.ename = works.ename
left join
    companies
      on works.cname = companies.cname
group by employee.ename

Try that.
Mike


text:
Q: How to decouple things in Wix? I want to install a product with some dll with Wix 3.5.
These dll are determined during the msi installation through a radio buttons group.
I have :

*

*a (fragment) wxs for myDllv1

*a (fragment) wxs for myDllv2

*a (UI fragment) wxs with the RadioButtonGroup to choose between myDll v1 and myDll v2 with a property INSTALLTYPE

*a main wxs file which installs the correct version of myDll.

Problem : I have another set of dll to add and I want to modify as less files as possible.
I don't want to introduce bugs and I want to keep things decoupled.
I would like to modify only the UI fragment with the radio buttons and add a myDllv3 fragment (without doing any changes to my main wxs file, so no condition in that file..).
Is it possible?

A: Why don't you use pre-processors to select the correct fragments when building the msi?
<?if $(env.SomeBuildParameter) = SetA ?>
  <?include myDllSetAv1.wxs ?>
  <?include myDllSetAv2.wxs ?>
<?else ?>
  <?include myDllSetBv1.wxs ?>
  <?include myDllSetBv2.wxs ?>
<?endif ?>

A: I may be misunderstanding the question, but it sounds like your different set of Dlls should be grouped by features within WIX. I'd suggest creating independent WIX fragments that represents a feature for each of your set of Dlls and then you can tie your UI to install a specific feature as appropriate.
You represent a feature at the product level like so:
<Feature Id="Feature.One" Title="Feature One">
            <ComponentGroupRef Id="FeatureOneDlls.Group" />
</Feature>

<Feature Id="Feature.Two" Title="Feature Two">
            <ComponentGroupRef Id="FeatureTwoDlls.Group" />
</Feature>

And within each of the features I'd recommend using a separate wxs file to supply the fragment information that contains the files for that feature.


text:
Q: azure databricks vscode: ERROR: TypeError: Cannot read property 'data' of undefined Originally, the connection between vscode and Databricks worked absolutely fine. Databricks-connect and the extension Databricks vscode worked seamlessly together and I had no problem until last week. Last week the workspaces of Databricks vscode did not properly load as seen here: empty databricks workspaces.
I checked the paiqo.databricks-vscode and this is the error that I got:
ERROR: TypeError: Cannot read property 'data' of undefined
I also did some digging and I only found one discussed which could point me in the right direction:
https://githubmemory.com/repo/paiqo/Databricks-VSCode/issues/48
It has something to do with the SSH connection but I do not know which settings I need to adjust in vscode or azure. If someone could point me in the right direction that would be great.


text:
Q: Cloning a transactional version in ArcGIS In ArcGIS documentation, I cannot find any references to cloning a transactional version. Is there a built in method for it?
I think I know how to do it manually in Arcpy, basically creating a new state branching from a parent and copying all the deltas with the given state (clone source) to the new state (clone) and of course adding the new state to the version tree under the parent, but I am wondering if there is a more neat way of doing it.
Update: Lets put it in more abstract way: Assume version hierarchy like A->B, A->C and C->D. i.e. B and C are decedents of A and D is decedent of C. The objective is to get an independent copy of C and call it E, while keeping the proper hierarchy. That is, after cloning, we will have A->E and E will contain exactly all the changes in C.
Note that, creating a version off of C will not cut it b/c if C changes, those changes will be reflected in E, which we do not want. Also, taking a branch off of A will not work since it does not have what is in C. Of course, we do not want to reconcile C into A and then get a version off of A - that is against the whole goal of having all these versions around.

A: Yes there is a 'neat way' of doing it, and I believe all of the APIs are present in order to do this in automation.  However, to test the process, I performed a version copy by-hand as follows:

*

*Inside ArcMap, create a new EDIT version and switch to it to make it current. (I'm using ArcGIS for Desktop Version 10.2.2.3557 for reference.)

*Reconcile this new EDIT version with the TARGET version you want to copy. During the reconcile, specify that the TARGET version changes should take precedence for any/all conflicts.

*Verify that the EDIT version contains differences against DEFAULT by using the Version Changes tool    . Also check that the EDIT version contains NO differences compared against the TARGET version which was the copy source.
Using the API, you want the Reconcile Versions (Data Management) tool. It requires a connection string to the geodatabase, then original (TARGET) version, and the new (EDIT) version.
Be sure to assign the following parameters as well:

*

*Reconcile Mode: ALL_VERSIONS

*Conflict Detection: BY_OBJECT  /because it is faster/

*Conflict Resolution: FAVOR_TARGET_VERSION
Bottom line: reconciling with a target version means bringing those changes into a current version....when you start with a fresh edit version and immediately reconcile with a target, the result is a version copy of the target.
UPDATE:  Comments below are supplemented by this image which shows the net effect of a new version+reconcile against various targets.


text:
Q: Sorting and removing non-duplicate rows in google sheet and keeping non-duplicate rows and duplicate rows I am fairly new to Google sheets, and essentially what I am trying to do is remove all non-duplicate values that do not exist or is listed in another sheet or row - and also store the non-duplicate values somewhere else
In my example sheet here, I am trying to only keep the Alcohol names that are listed in column G
So in my case, I only want to keep the following records:
Alcohol Name    Alcohol Type    Origin
Martell Cognac  France
Captain Morgans Rum Jamaica
Wray & Nephew   Rum Jamaica
Hennessey   Cognac  France
Barcardi    Rum Cuba
Courvoiser  Cognac  France
Famous Grouse   Scotch  Scotland
Jack Daniels    Whisky  USA
Grants  Scotch  Scotland
Ciroc   Vodka   France

I also want to keep any that did not appear in the list in a separate table like this:
Alcohol Name    Alcohol Type    Origin
Russian Standard    Vodka   Russia
Southern Comfort    Bourbon USA
Ciroc   Whisky  France

At the moment I am having to manually check a longer list one by one and it is taking lot of time and my arm hurts..
If someone can please help me with sorting it such that it looks like this, would be great! I don't know if there are formulas we can use

A: Use this formula to only keep the Alcohol names that are listed in column G
=QUERY(A1:C," where A matches '"&TEXTJOIN("|",1,G2:G)&"' ",1)

To order them use
=QUERY(A1:C," where A matches '"&TEXTJOIN("|",1,G2:G)&"' order by A",1)

Use this to keep any that did not appear in the list in a separate table.
You see, you only put not in the formula
=QUERY(A1:C," where not A matches '"&TEXTJOIN("|",1,G2:G)&"' ",1)


text:
Q: SQL Server: Canonical way to get a substring from a particular index to the end of the string? In SQL Server, given a string, is there an established, canonical "best" way to get a substring starting at a particular index, and continuing to the end of the string?
"Best" here means a balance of the following considerations:

*

*Most efficient performance-wise

*Easiest for developers to read and understand

*Shortest / easiest to remember without having to look up the syntax

Ways I've come across to do this, using 2 in these examples as the index from which to start the substring:
SUBSTRING(mystring, 2, 1000000)

*

*Source: https://stackoverflow.com/a/8302533/12484

*Con: The use of the "magic number" 1000000 (which could be any "sufficiently large" value) seems not ideal.

*Con: What my code encounters a string that is longer than that value?

.
SUBSTRING(mystring, 2, 2147483647)

*

*Con: There's no built-in constant that we can substitute for that "max int" value.

*Con: That "max int" value is hard to remember, and is annoying to have to Google every time.

*Con: Even assuming we're talking about an varchar(max) or nvarchar(max), the string length might possibly exceed that size, depending on the SQL Server version?

.
SUBSTRING(mystring, 2, LEN(mystring) - 2 + 1)

*

*Con: This syntax is somewhat cumbersome.

.
RIGHT(mystring, LEN(mystring) - 2 + 1)

*

*Con: This is still is fairly cumbersome.

.
SUBSTRING(mystring, 2, LEN(mystring))

*

*Con: Per the docs, it's okay for the "length" parameter to have a value that goes past the end of the string, but this might initially seem like a possible index-out-of-range bug to developers reading this code (until they also look up the docs and see that this approach is ok)?

Is there a better general solution to this problem, taking into account the considerations that I mentioned above (performance, readability, ease of use)?

A: As I mentioned in the comment, another option you could use is
STUFF(mystring, 1,2,'')

This should be easy to understand and remember for developers.

A: SUBSTRING(mystring, 2, LEN(mystring) - 2 + 1)

This would definitely be my preferred way to do it.  Even if "canonically" you can extend beyond the bounds of the string's length in a SUBSTRING() function, its better not to.  If you are concerned about confusions with the syntax, simply preface the line with a comment explaining.  In fact, I would probably preface a this kind of operation with a comment anyway to explain why I am using a substring and what I anticipate the substring to consist of