text:
Q: What do I have to change about my activity to integrate Swipe View? So this is what my current activity looks like:
package com.example;

import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

import android.app.Activity;
import android.os.Bundle;

public class TestActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_layout);

        // Look up the AdView as a resource and load a request.
        AdView adView = (AdView)this.findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        adView.loadAd(adRequest);
    }

    @Override
    protected void onStart() {
        super.onStart();
        EasyTracker.getInstance(this).activityStart(this); // Add this method.
    }

    @Override
    protected void onStop() {
        super.onStop();
        EasyTracker.getInstance(this).activityStop(this); // Add this method.
    }
}

My layout file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_weight="1"
        ads:adSize="SMART_BANNER"
        ads:adUnitId="ca-app-pub-1596992408570157/3380743224" />

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/adView"
        android:layout_alignParentTop="true" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/textView1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text=""
                android:textSize="24sp"
                android:textStyle="bold" />

            <ImageView
                android:id="@+id/imageView1"
                android:layout_width="wrap_content"
                android:layout_height="250dp"
                android:src="" />

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="" />

            <TextView
                android:id="@+id/textView3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="" />

            <TextView
                android:id="@+id/textView4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="" />

            <TextView
                android:id="@+id/textView5"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Currency: Afghan Afghani" />

            <TextView
                android:id="@+id/textView6"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="" />

            <TextView
                android:id="@+id/textView7"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="" />
        </LinearLayout>
    </ScrollView>
</RelativeLayout>

I would like to add a page that consists of a single webview. I want the user to be able to swipe from this activity to that activity (the one with the webview). I'm having a lot of problems figuring out how to implement the swipeviews. Does anyone know what I have to add/change about my current layout/activity file to get the swipe view with webview to work? Thank you!

A: You should use ViewPager and your activity must extend FragmentActivity. Look at this link.


text:
Q: Selecting values greater than x in 2d array I have np 2d array (called old_array) which looks like this:
1 2 3 4 5 6 7 8 9
4 3 5 1 6 7 3 2 8
8 3 4 1 8 3 2 9 3
7 3 5 8 2 5 9 2 6
Trying to select only values greater than 4 and would like to have output like this:
5 6 7 8 9
5 6 7 8
8 8 9
7 5 8 5 9 6
I was trying to use new_array = old_array[old_array>4] but not getting desired solution.
Any explanation what I am doing wrong, or how this should be done. Also trying to avoid loops if possible.
Thanks.

A: If these arrays are NumPy arrays and you'd like to get the indexing of the elements rather than 4, you can use
np.argwhere(array > 4)
This function returns you another array with the indexes of the original array where the condition is True.
np.argwhere(array>4)
array([[0, 4],
       [0, 5],
       [0, 6],
       [0, 7],
       [0, 8],
       [1, 2],
       [1, 4],
       [1, 5],
       [1, 8],
       [2, 0],
       [2, 4],
       [2, 7],
       [3, 0],
       [3, 2],
       [3, 3],
       [3, 5],
       [3, 6],
       [3, 8]])

Otherwise
array>4
array([[False, False, False, False,  True,  True,  True,  True,  True],
       [False, False,  True, False,  True,  True, False, False,  True],
       [ True, False, False, False,  True, False, False,  True, False],
       [ True, False,  True,  True, False,  True,  True, False,  True]])

In this case, you obtain a mask on which you can loop through.
Hope it works

A: You are trying to force numpy to work in a way it is not designed for. It is not designed to work with arrays that contain rows of not equal length.
Now, as you are informed about that, you can still do it using np.split but this is slow in general.
Here is a way to go along with:
x = np.array([[1, 2, 3, 4, 5, 6, 7, 8, 9], [4, 3, 5, 1, 6, 7, 3, 2, 8], [8, 3, 4, 1, 8, 3, 2, 9, 3], [7, 3, 5, 8, 2, 5, 9, 2, 6]])
trues = x > 4
row_lengths = np.sum(trues, axis=1)
split_idx = np.cumsum(row_lengths[:-1])
>>> np.split(x[trues], split_idx)
[array([5, 6, 7, 8, 9]),
 array([5, 6, 7, 8]),
 array([8, 8, 9]),
 array([7, 5, 8, 5, 9, 6])]

And some tests explaining how it works:
>>> trues
array([[False, False, False, False,  True,  True,  True,  True,  True],
       [False, False,  True, False,  True,  True, False, False,  True],
       [ True, False, False, False,  True, False, False,  True, False],
       [ True, False,  True,  True, False,  True,  True, False,  True]])
>>> x[trues]
array([5, 6, 7, 8, 9, 5, 6, 7, 8, 8, 8, 9, 7, 5, 8, 5, 9, 6])
>>> row_lengths
array([5, 4, 3, 6])
>>> split_idx
array([ 5,  9, 12], dtype=int32)

redpajama_set_name: RedPajamaStackExchange


text:
Q: compare words from a list with a text file using counter.collection I am making a small script that tries to compare words from a text file, for now, I have been able to compare extracting all the words and counting their frequency, now, how could I make the algorithm only extract the words from the .txt that are in a list determined by me... so far I have this
from collections import Counter
def word_count(filename):
    with open('hola.txt','r') as f:
        return Counter(f.read().split())

counter = word_count('hola.txt')
for i in counter:
    print (i, ":", counter [i])

A: You can create your set of the words you want to consider, and feed the Counter a generator that contains only the words in your set, using a generator comprehension:
from collections import Counter

words_to_keep = {'only', 'keep', 'these', 'words'}

def word_count(filename):
    with open(filename, 'r') as f: # use `filename`
        return Counter(w for w in f.read().split() if w in words_to_keep)

counter = word_count('hola.txt')

for w, c in counter.items():
    print (w, ":", c)


text:
Q: orthogonality and implication of normal vectors Let $\{u_1,..,u_k\}$ be orthonormal.
Then that means
$\langle u_i,u_j\rangle = \begin{cases}1 & ,i = j\\0 & , else\end{cases}$
"What happens when $\langle u_k,u_k\rangle\neq 1$?"
Well, then it's (obviously) not orthonormal anymore?
No idea. What are the implications beyond that?

A: As was pointed out int he comments, such a basis would be called an orthogonal basis - so long as $\langle u_k, u_k \rangle \neq 0$ for all $k$. It doesn't have all the nice properties that an orthonormal basis would though; with an orthonormal basis it's not hard to prove that one can compute the inner product of two vectors by summing the products of the coordinates:
$$ \langle a, b \rangle = \sum_{i=1}^n a_ib_i,$$
where $a_i, b_i \in \mathbb{R}$ denote the coordinates of $a$ resp. $b$. With an orthogonal basis (as with all others), this doesn't hold in general. Any orthogonal basis can be easily 'transformed' into an orthonormal one though, by some simple rescaling of each vector (though any basis can be transformed into an orthonormal one by a Gram-Schmidt process, so it's not a very special property or anything).


text:
Q: File.ReadAllLines() - Reads more lines than what's in the file as null entries I'm having an issue where I have a text file as [filename].config and I use the File.ReadAllLines() method to read every line within it. The file only has 97 lines yet when I read it in, it has 3,973 lines stored in the string[] array. The 97 lines are all accurate but the rest after that are a bunch of null lines. I've searched online and on stack here but have seen nothing about this.
var file = File.ReadAllLines(mainConfigFile); is the line of code I'm using just to debug reading in the file. Just to view the values in debug mode.
Anyone have any idea of what I'm not understanding?

A: It's highly unlikely (though remotely possible) that ReadAllLines is broken. More likely is that what that function defines as a line break delimiter is not the same as what the programs you are viewing the file with define as line break delimiters. In the MSDN docs you'll find this:

A line is defined as a sequence of characters followed by a carriage
  return ('\r'), a line feed ('\n'), or a carriage return immediately
  followed by a line feed.

So, for example if your last line ended with a carriage return and 1000 line feeds, ReadAllLines would return blank lines (empty strings) for all those trailing line feeds. But if the program you open the file in only treats carriage return + line feeds as newlines, you wouldn't see a bunch of blank lines in it.
Note that because of the way ReadAllLines is written, although you can get empty strings in the results, elements in the returned array of strings will never be null. As it reads lines, it looks for a null returned from the ReadLine method it uses as the indication that the end of file was reached. When it gets that null, it stops reading, and doesn't add the null to the results.
A possibility is that it has nothing to do with ReadAllLines, but instead, there is something going on with your actual config file (and ReadAllLines is revealing that). Some process may be subtly adding cruft to your file. Something similar to this old bug in the config transform, or repeated round trip conversions of Windows style newlines vs. Unix style newlines while copying files, or via source control.


text:
Q: How to calculate rank from multiple parameters to get best/trustworthy peer How to calculate rank from multiple parameters ?
Parameters are bandwidth, delay, success ratio, these parameters values are used to determine the trustworthiness of a peer while accessing a service from a peer?.  My aim is to get the best peer, by using any ranking method ... which method can I use?

A: Do you have data with rankings? If yes, you can build a linear regression model that predicts the score/rank given the 4 features. The feature weights will be learned from the training set. A positive weight will suggest that the feature adds positively to the rank (e.g bandwidth); a negative weight will suggest that increasing feature value will decrease the rank (e.g. delay).
You can use LIBSVM to fit a linear regression model or any other package for this task.


text:
Q: Accessing audio out in Windows I am looking to write an Arduino script that uses whatever audio signal is going to the speakers to create a physical visualization.
The Arduino is connected to the windows machine only through USB, so I need to use USB to find out what is being sent to the speakers. How would I access this information?

A: As of right now, the Arduino can only communicate with the computer via serial over USB.  Things have changed with the new Arduino Uno, but the examples have not yet been released to show how to have the new Arduino act as other USB devices.
You would have to write something for the Windows box that monitor's the system audio and sends the info about it over serial to the Arduino, as long as you want it to only connect via USB.

A: There is a Java library for processing called ESS that lets you access audio out.

A: There isn't a very good way to interface an audio signal to an Arduino without some external hardware.
One way to do it though would be to connect the audio line to a biased pin with a capacitor, then you could use the ADC directly.  There will be pretty terrible dynamic range, but it only takes 3 passive parts.  Running that through an opamp before going to the ADC pin could significantly improve dynamic range and provide a filtering opportunity (see below).  Alternatively, you could switch on an on-chip voltage reference to use (typically 1-1.5 V) instead of the main supply.
It doesn't matter that much for a straight visualization, but the sample rate will not be good enough to capture the full spectral content of the audio (in addition to the poor dynamic range resolution).  The default Arduino sample rate is 10 kHz(-ish...possibly asynchronous), so you will only get valid data if your signal is below 5 kHz, otherwise aliasing will muck it up.  (If you write your own analog driver for the ATmega32P you could get up to 76 kHz sample rate with 8-bit samples)
Then to actually communicate that data to a computer, you can fairly easily throw all those ADC values onto the UART for the computer to pick up and process as it sees fit.  An ATmega will not have the power to compute FFTs on the fly (what you'd do almost always do for a viz anyways).

Or to skip all that, connect the audio signal to your computer's sound card (or USB sound card...they're pretty nice) and use some audio driver.


text:
Q: How to print TukeyHSD to pretty table format in for example .pdf with R? I can run ANOVA and TukeyHSD on my dataset, and the output can easily be saved to a txt format as such:
#AOV test
res.aov <- aov(variable_of_interest ~ Treatment*some_variable*some_parameter, data = dataframe)

#save output to text file
capture.output(TukeyHSD(res.aov), file="TUKEY_outfile.txt")

However, the output is pretty ugly in my opinion, and it takes a lot of time to get it into Excel and format it into a pretty format. Is there a way to directly print the outputs to a nice table format in for example excel or .pdf? I saw a LATEX solution, but it was unfortunately very complicated.
As a working example, the following code could be used:
fm1 <- aov(breaks ~ wool + tension, data = warpbreaks)
capture.output(TukeyHSD(fm1), file="example_tukey.txt")

A: Here is a possible solution. If you plan to move code/output/tables/graphics from R to pdf/html/latex format files regularly, you should invest in the time to learn Rmarkdown or Bookdown which are specifically designed exactly for this purpose. If you just want to export a few tables to html or latex, the package xtable may work for you. The following code uses the example on the TukeyHSD manual page to illustrate producing an html file containing three tables:
fm1 <- aov(breaks ~ wool * tension, data = warpbreaks)
TK <- TukeyHSD(fm1)
print(xtable(TK$wool), type="html", file="TukeyTables.html")
cat("

", file="TukeyTables.html", append=TRUE)
print(xtable(TK$tension), type="html", file="TukeyTables.html", append=TRUE)
cat("

", file="TukeyTables.html", append=TRUE)
print(xtable(TK$'wool:tension'), type="html", file="TukeyTables.html", append=TRUE)

This code produces an html file with three tables will look something like the figure. There are many arguments in xtable function that give you substantial control over the formatting, but the package is really designed for latex.
.


text:
Q: Access forbidden when trying to submit form in php I am new to php. I have some lab work that I needed to do at home. A problem has to do something very simple, just to display the squared number in another php page.. But that is not happening. I have been struggling to fix this for days. I rememeber when using xampp in old days I did not have this issue.
Every time I try to submit the form I get this:

Access forbidden!
You don't have permission to access the requested object. It is either read-protected or not readable by the server.

If you think this is a server error, please contact the webmaster.

Error 403
127.0.0.1
Apache/2.4.33 (Win32) OpenSSL/1.1.0g PHP/7.2.4

I try other programs like easyPHP or wampp.. still same issue.. This is the code:

//prelucrare.php
<?php
$a = $_POST['a'];
echo $a * $a;
?>
//index.php

<form action="http://localhost:80/prelucrare.php" method="post">
    <input type="text" name="a">

    <button type="submit">Square it</button>
</form>

And my httpd-xampp.conf file:

#
# XAMPP settings
#

<IfModule env_module>
    SetEnv MIBDIRS "C:/xampp/php/extras/mibs"
    SetEnv MYSQL_HOME "\\xampp\\mysql\\bin"
    SetEnv OPENSSL_CONF "C:/xampp/apache/bin/openssl.cnf"
    SetEnv PHP_PEAR_SYSCONF_DIR "\\xampp\\php"
    SetEnv PHPRC "\\xampp\\php"
    SetEnv TMP "\\xampp\\tmp"
</IfModule>

#
# PHP-Module setup
#
LoadFile "C:/xampp/php/php7ts.dll"
LoadFile "C:/xampp/php/libpq.dll"
LoadModule php7_module "C:/xampp/php/php7apache2_4.dll"

<FilesMatch "\.php$">
    SetHandler application/x-httpd-php
</FilesMatch>
<FilesMatch "\.phps$">
    SetHandler application/x-httpd-php-source
</FilesMatch>

#
# PHP-CGI setup
#
#<FilesMatch "\.php$">
#    SetHandler application/x-httpd-php-cgi
#</FilesMatch>
#<IfModule actions_module>
#    Action application/x-httpd-php-cgi "/php-cgi/php-cgi.exe"
#</IfModule>

<IfModule php7_module>
    PHPINIDir "C:/xampp/php"
</IfModule>

<IfModule mime_module>
    AddType text/html .php .phps
</IfModule>

ScriptAlias /php-cgi/ "C:/xampp/php/"
<Directory "C:/xampp/php">
    AllowOverride None
    Order Allow,Deny
    Allow from All
</Directory>

<Directory "C:/xampp/cgi-bin">
    <FilesMatch "\.php$">
        SetHandler cgi-script
    </FilesMatch>
    <FilesMatch "\.phps$">
        SetHandler None
    </FilesMatch>
</Directory>

<Directory "C:/xampp/htdocs/xampp">
    <IfModule php7_module>
     <Files "status.php">
      php_admin_flag safe_mode off
     </Files>
    </IfModule>
    AllowOverride AuthConfig
</Directory>

<IfModule alias_module>
    Alias /licenses "C:/xampp/licenses/"
    <Directory "C:/xampp/licenses">
        Options +Indexes
        <IfModule autoindex_color_module>
            DirectoryIndexTextColor  "#000000"
            DirectoryIndexBGColor "#f8e8a0"
            DirectoryIndexLinkColor "#bb3902"
            DirectoryIndexVLinkColor "#bb3902"
            DirectoryIndexALinkColor "#bb3902"
        </IfModule>
        Require local
        ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
   </Directory>

    Alias /phpmyadmin "C:/xampp/phpMyAdmin/"
    <Directory "C:/xampp/phpMyAdmin">
        AllowOverride AuthConfig
        Require local
        ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
    </Directory>

    Alias /webalizer "C:/xampp/webalizer/"
    <Directory "C:/xampp/webalizer">
        <IfModule php7_module>
      <Files "webalizer.php">
       php_admin_flag safe_mode off
      </Files>
        </IfModule>
        AllowOverride AuthConfig
        Require local
        ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
    </Directory>
</IfModule>

A:

//prelucrare.php
<?php
$a = $_POST['a'];
$b = $a * $a;
echo $b;
?>

<form action="prelucrare.php" method="POST">
<input type="number" name="a">

<button type="submit">Square it</button>
</form>

The above code works perfectly. Please update your code and try again.


text:
Q: How are these two Breadth First Search problems different from each other Below are two breadth first search traversal problems.
Problem 1 : 317 - Shortest Distance From All Buildings

The solution for this problem is to do a breadth first search traversal from each building, and record the distance to the reachable cells from it.
The shortest distance would be the cell that is reachable from each of the buildings, and have the cumulative shortest distance over distance to reach that cell from each building.
Problem 2 : 296 - Best Meeting Point

I find this problem to be exactly the same as previous, except that there are no 2, that is, obstacles here. Why is there a different solution however?
I am trying to understand the difference between the two problems, and why the solution of the first problem won't work for the second. Does Manhattan distance have anything to do with it?
EDIT : Based on SimMac's answer below, I have tried to update the Manhattan and Travelling distance starting from the building at (0,1). The input as well as Manhattan and Travelling distance are below. SimMac, could you please validate these.
Input
0 - 1 - 2 - 0 - 1
|   |   |   |   |
0 - 2 - 0 - 0 - 0
|   |   |   |   |
0 - 0 - 0 - 0 - 1

Manhattan distance
1 - source - INF - 8 -   9
|      |     |     |     |
2 -   INF -  6 -   7 -   8
|      |     |     |     |
3 -    4 -   5 -   6 -   7

Travelling Distance
1-   source- INF - INF - INF
|      |     |     |     |
2 -   INF - INF - INF - INF
|      |     |     |     |
3 -   INF - INF - INF - INF

A: You can use first algorithm for second problem, but it isn't neccessary.
You already mentioned the Manhattan distance. Instead of doing a BFS to calculate the distance between two points, you can now simply calculate the Manhattan distance and use this value. Because the manhattan distance between two points (x1, y1), (x2, y2) is simply the absolute difference of x1 and x2 plus the absolute difference of y1 and y2, it is much faster to calculate the distance this way.
You can't use the Manhattan distance on the first problem, because you may have a situation like this:
0 - 1 - 2 - 0 - 1
|   |   |   |   |
0 - 2 - 0 - 0 - 0
|   |   |   |   |
0 - 0 - 0 - 0 - 1

You can easily see how the traveling distance from the building at (0,1) to any point not in the rightmost column differs from the Manhattan distance.
Let's draw the traveling distances from the building to every other field:
1 - x - + - 8 - 9
|   |   |   |   |
2 - + - 6 - 7 - 8
|   |   |   |   |
3 - 4 - 5 - 6 - 7

The Manhattan distance would look like this (it isn't affected by the obstacles):
1 - x - + - 2 - 3
|   |   |   |   |
2 - + - 2 - 3 - 4
|   |   |   |   |
3 - 2 - 3 - 4 - 5


text:
Q: SQL select string between known identical characters I have code which selects the string between the first and second '/' in a typical string which may look like this:

2014-Ceilings/Ceilings/Repair/Asbestos/Supalux

The following code correctly returns the value 'Ceilings' in the above example.
SELECT
REPLACE (LEFT(SUBSTRING(ElementPath,CHARINDEX
            ('/',ElementPath)+1,LEN(ElementPath)),CHARINDEX
        ('/',SUBSTRING(ElementPath, CHARINDEX
                ('/',ElementPath)+1,LEN(ElementPath)))),'/','')
FROM K2_Master.dbo.tbElement

How can I amend it to select the string between the second and third '/' to return the value 'Repair'?

A: Check this little trick may work :
DECLARE @String VARCHAR(100)= '2014-Ceilings/Ceilings/Repair/Asbestos/Supalux'

SET @String = '<N>' + Replace(@String, '/', '</N><N>')
              + '</N>'

SELECT c.value('/N[1]', 'varchar(30)'),
       c.value('/N[2]', 'varchar(30)'),
       c.value('/N[3]', 'varchar(30)')
FROM   (SELECT Cast(@String AS XML)) t(c)

SELECT c1.value('.', 'varchar(30)')
FROM   (SELECT CAST(@String AS XML)) t(c)
       CROSS APPLY c.nodes('/N') AS t1(c1)

SELECT value
FROM   (SELECT c1.value('.', 'varchar(30)') AS value,
               ROW_NUMBER()
                 OVER(
                   ORDER BY (SELECT 1))     rn
        FROM   (SELECT Cast(@String AS XML)) t(c)
               CROSS APPLY c.nodes('/N') AS t1(c1)) temp
WHERE  rn = 3

In your case
SELECT c.value('/N[1]', 'varchar(30)'),
       c.value('/N[2]', 'varchar(30)'),
       c.value('/N[3]', 'varchar(30)')
FROM   (SELECT Cast ('<N>' + Replace( Replace (ElementPath, '/', '</N><N>'),'&','&')
                     + '</N>' AS XML)
        FROM   K2_Master.dbo.tbElement) t(c)

A: I chased your question, and reached a lengthy result..
DECLARE @a VARCHAR(40) = '2014-Ceilings/Ceilings/Repair/Asbestos/Supalux'

SELECT      @a
            ,LEFT(
            SUBSTRING(SUBSTRING(@a,CHARINDEX('/',@a,1)+1,LEN(@a)),CHARINDEX('/',SUBSTRING(@a,CHARINDEX('/',@a,1)+1,LEN(@a)),1)+1,LEN(SUBSTRING(@a,CHARINDEX('/',@a,1)+1,LEN(@a)))),
            CHARINDEX('/',SUBSTRING(SUBSTRING(@a,CHARINDEX('/',@a,1)+1,LEN(@a)),CHARINDEX('/',SUBSTRING(@a,CHARINDEX('/',@a,1)+1,LEN(@a)),1)+1,LEN(SUBSTRING(@a,CHARINDEX('/',@a,1)+1,LEN(@a)))),1) - 1
            )

Result:

Answer to you comment.
DECLARE @String VARCHAR(100)= '2014-Ceilings/Ceilings/Repair/Asbestos/Supalux',
        @value INT = 2
DECLARE @itra INT = 1

WHILE @itra <= @value
BEGIN
    SET @String = (SELECT SUBSTRING(@String,CHARINDEX('/',@String,1)+1,LEN(@String)))
    --SELECT @String
    SET @itra = @itra + 1
END

SELECT LEFT(@String, CHARINDEX('/',@String,1) - 1)

Give the position of '/' as @value and see the result. For the above sql, the result is Repair. If you give @value = 3, result is Asbestos


text:
Q: YouTrack Workflows not Firing I have a basic scheduled workflow that creates issues, but can't get the flow to trigger as it should on the projects to which it is attached:

*

*I have 3 projects: A, B and C

*I have a scheduled workflow that creates a single issue (summary and description only) in each of A, B and C.

*When the workflow is attached to project B, it triggers and all 3 issues are created.

*When the workflow is attached to A and/or C, the workflow does not trigger.

Many of the project fields overlap, but given that I'm only setting the summary and description, i don't see that being a problem?
I can't find where workflow execution gets logged, so don't know if there are problems (but the flow does execute on project B)...?
Any help appreciated!

A: Be aware that stateless and state machine rules are executed on behalf of a user who actually made changes that triggered a workflow. Scheduled rules, in turn, run on behalf of their author. Thus, make sure the author has respective permissions in all of the projects the rule is attached to.

A: Although not an answer to the problem, this problem was resolved by upgrading from YT5 to YT6.
Part of the upgrade involved going through this problem: http://forum.jetbrains.com/thread/YouTrack-1810 (resolved by backing up, uninstalling YT5, removing all YT folders, then installing YT and restoring backup)
That leads me to wonder if the problem wasn't related to a bad/locked/corrupted file somewhere in the YT directory?
Nevertheless, post upgrade, I attached the scheduled workflows as they were and they fired without hindrance.


text:
Q: Laravel session regenerate() and invalidate() functions I am implementing some custom auth functionality in to my application, which is built in Laravel v8. I have been looking at Laravel Breeze to see how it is has been implemented there.
These are the relevant functions from Laravel Breeze (https://github.com/laravel/breeze/blob/1.x/stubs/default/App/Http/Controllers/Auth/AuthenticatedSessionController.php):
class AuthenticatedSessionController extends Controller
{
    /**
     * Handle an incoming authentication request.
     *
     * @param  \App\Http\Requests\Auth\LoginRequest  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(LoginRequest $request)
    {
        $request->authenticate();

        $request->session()->regenerate();

        return redirect()->intended(RouteServiceProvider::HOME);
    }

    /**
     * Destroy an authenticated session.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(Request $request)
    {
        Auth::guard('web')->logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        return redirect('/');
    }
}

So you will notice:

*

*In the store() function, which is called during Login, it does $request->session()->regenerate();

*In the destroy() function, which is called during Logout, it does $request->session()->invalidate();
In my application custom auth code, I have applied the same implementation in my login and logout actions.
What I have found is, when I logout, it deletes the existing session file inside storage/framework/sessions but then creates another one.
Then when I login, it creates a brand new session file. This essentially means the folder gets full of session files.
Does anyone know the reason why it is implemented this way? I would have thought logout would just delete the session file without creating a new one?

A: That is the normal behavior of PHP and it is not specific to Laravel.
In PHP by default, all sessions are files that are stored in a tmp directory which if you analyze the session.save_path value in php.ini file, you will see where it is. These files include the serialized session data that you access using $_SESSION keyword.
Laravel utilize basically the original session file store but acts a little bit different. Beside changing the directory they are saved, when you call the regenerate function it creates another session file and deletes the old one. You can see it the implementation Illuminate\Session\Store.php. The migrate function is used to delete the session and return new session id.
public function regenerate($destroy = false)
{
    return tap($this->migrate($destroy), function () {
        $this->regenerateToken();
    });
}

For the invalidate function it deletes the session file actually. If you inspect the implementation, the invalidate calls for migrate method, it calls a destroy method with session id as input and this function simply deletes the session file. But soon after it deletes the file, it needs to create a new session file, why? Because the logged out user needs a new session id so we can track them.
public function invalidate()
{
    $this->flush();

    return $this->migrate(true);
}

Laravel Session Cleanup
Laravel has a garbage cleanup functionality which runs randomly and deletes the session files that are not valid. What does it mean randomly? Well the cleanup operation is triggered based on a randomness and traffic. So in each request Laravel checks the odd of triggering the clean or not, and the odds are 2 out of 100 by default. This means if applications receives 50 requests, there is a high chance that it will trigger this cleanup.
So if you have a high traffic, there is a high chance that the session directory will be cleared at short intervals, which is quire cool since it always makes sure that the specified directory does not get over populated when visiting users increase.
By the way if you want to act aggressively and delete on a higher chance, you can change the lottery odds in the config\session.php file:
    /*
    |--------------------------------------------------------------------------
    | Session Sweeping Lottery
    |--------------------------------------------------------------------------
    |
    | Some session drivers must manually sweep their storage location to get
    | rid of old sessions from storage. Here are the chances that it will
    | happen on a given request. By default, the odds are 2 out of 100.
    |
    */

    'lottery' => [2, 100],


text:
Q: How do i add adsense code in vbulletin archive page? How do I add adsense code into vbulletin archive page?
Which method can I use?
I need to place the code in the archive index page.

A: Which vBulletin version do you use? Use the template manager to edit the default archive template and insert the ad sense code.

A: vBulletin 4.x contains default locations which you use to insert advertising throughout your forum in a range of predefined locations including it's archive. In addition you can also configure your own from a list of options.
To use a default location:
Admin Control Panel > Advertising > Manage Ads > Archive
and follow the prompts to configure your ad.
To configure your own:
Admin Control Panel > Advertising > Manage Ads > Ad a New Ad > Archive
and follow the prompts to configure your ad.
However note that Adsense's code will disable any links which it deems too close to it's own so you'll need to use the Below Content location in order to avoid disabling your Archive's existing navigation links.


text:
Q: ffmpeg: Low framerate when capturing with -vcodec mjpeg but not with -vcodec copy I'm trying to capture video from a webcam, and I find that when I use the -vcodec copy option, it works really well (far better than any other software I've tried).  However, I'd like my files to be a bit smaller, and it seems that every attempt I make to compress the video leads to extremely jumpy video.  If, for example, I switch the output vcodec to mjpeg, it changes from reporting 15 fps to reporting between 3 and 4 fps.  Am I doing something wrong??  Here is the call with -vcodec copy:
ffmpeg -y -f dshow -vcodec mjpeg -s 1184x656 -framerate 25 -i video="HD 720P Webcam" -vcodec copy test.avi

-- which gets me 15 fps.  But if I change to mjpeg, I get only 3-4 fps:
ffmpeg -y -f dshow -vcodec mjpeg -s 1184x656 -framerate 25 -i video="HD 720P Webcam" -vcodec mjpeg test.avi

Experimental attempts to put -framerate 25 or -r 25 before test.avi also does nothing to help the situation.  I'm not getting any smoother video when experimenting with mpeg4 or libx264 either.  Only the copy option gives me smooth video (btw I'm filming my hands playing a piano, so there is a lot of fast motion in the videos).
Help!!!!  And thank you...

A: I don't understand why the framerate drops so much, but you could try a 2 pass approach where you first record it using -vcodec copy (as you pasted in the question)
ffmpeg -y -f dshow -vcodec mjpeg -s 1184x656 -framerate 25 -i video="HD 720P Webcam" -vcodec copy test.avi

Then transcode it into mjpeg once it's done (something like this):
ffmpeg -i test.avi -vcodec mjpeg test.mjpeg

note: I haven't actually tested any of the above command lines.

A: Sounds like your webcam is outputting a variable frame rate stream. Try the below on one of your copy captured files.
ffmpeg -i test.avi -vcodec libx264 -r 30 test.mp4

(You should avoid capturing to AVI, use MKV instead)


text:
Q: Steps for testing external flash memory I have a blackfin 533 and I connect it with external flash memory.
I have a software driver that erases a block, fills data, write to flash memory.
I'm using the following chip ST M29W800D.
How would I test and verify the flash that's working ?
Should I earse it, fill it with data and read it ?
but how would I erase it, and I'm running the software that is checking the correctness of the flash eeprom ?

A: We are again on the same question as in your previous question - what are you going to test? That flash is there? If it was soldered onto the board, then flash has to be there physically. If it is operational or not? You will not know if it is operational or not without knowing something which should be in specific places of flash, or have checksum as @st2000 proposed.
You have answered your question by saying

I have a software driver that erases a block, fills data, write to flash memory.

Do it, then read data you filled with to compare with original. For that you need some distinguishable data to write, first which comes to mind you should not write FFs if you have data line pullups and 00s if you have data line pulldowns.
But in general flash is usually needed to hold some information. When application updates the flash chip, it must check that update is done properly by comparing sector written with content being read after programming.
If you need algorithm how to perform erase/program/read, you should refer to datasheet of the chip or application note for it.
Hope it helps.
I suspect that question you ask may not describe your main problem; you try to gather some side data to solve issue yourself.
ADD #1: (I removed comment, putting addition here)

my problem is, how would I erase block, fills the data, and I'm running the software on the flash itself.

Ah, this is for sure different problem. If you run code which is located in flash chip, then:

*

*you must ensure that you do not erase/rewrite sector with code you are running. This is first thing.

*then check datasheet if, during erase/write cycles, flash chip is readable for external device for the page which was not erased; it may happen that during erase/write cycles chip will be only outputting state of the erase/write operation, then processor will not be able to get proper instruction to run and malfunction;

*if you need to erase everything, you will need to copy code you execute to some other physical location - e.g. in SRAM, and run it from there. After you update flash chip device will anyway need a hard reset to ensure new code within flash chip is in effect.

There're several issues with approach reading data from flash which is being erased and programmed. I would simply copy code somewhere else and run it from there - this way you will be 100% safe from malfunction of flash during erase and programming.
ADD #2

sorry I didn't understand, how would I copy the flash software into SRAM ? should I read the whole data and save it in a buffer for example ? but what should I do with this data ? how to verify it is correct ? so the steps is to read the whole flash and save it in a buffer, then what to do else

This is software technique, which must be allowed at hardware level. Processor must be able to "see" flash and SRAM in its addressing space. Flash chip programming code must be relocatable to SRAM addressing space, and after you copy this code to SRAM from flash, you just jump to it, and execution continues in SRAM.
Contents you are going to write to flash of course should not be located in flash because you are going to erase it. Thus SRAM (or some other source emulating RAM) needs to be used as source for data you are going to write to flash (as well as for instruction fetch for executing during flashing).
Some processors/MCUs may have small flash inside them, if this one is having such, you can put you flash chip flashing code in there.
The task actually is not an easy one, and results of implementation will much depend on architecture of your device.
I took a brief look into application note, it says

During the Program/Erase mode of the M29F800 a read cycle will output the Status Register of the P/E.C. The Status Register contains valuable information about the program or erase operation which is happening or has finished.

If it means that during program/erase cycles it can not give instruction code to CPU to run from flash, then you can not flash the chip executing flashing code from it.

am using blackfin 533

Looking to datasheet I see

Up to 148K bytes of on-chip memory

Thus there's a place to put flashing code inside the processor. Maybe you can
use scratchpad RAM, or data bank SRAMs (I am not sure, not so much familiar with this chip)

External memory controller with glueless support for SDRAM, SRAM, flash, and ROM

And you can also connect external SRAM, SDRAM :)


text:
Q: JToolBar not showing I had a simple drawing application.  I need to add a menu and a toolbar on the left side.
So now, instead of using a simple JFrame, I'm creating a simple class that extends JFrame. I was able to add the menu following some examples online, but can't figure out how to add a JToolBar.  I've tried a few different ways, but nothing works.  I don't get an error, everything complies just fine, but I don't see any JToolBar.
Here's the code for my JFrame, I hope you can help.
class Menu extends JFrame {
private JMenuItem openItem;
private JMenuItem saveItem;
private JMenuItem saveAsItem;

public Menu(String title) {

    openItem = new JMenuItem("Open...");
    openItem.setMnemonic('O');
    openItem.setAccelerator(KeyStroke.getKeyStroke("control O"));

    saveItem = new JMenuItem("Save");
    saveItem.setMnemonic('S');
    saveItem.setAccelerator(KeyStroke.getKeyStroke("control S"));

    saveAsItem = new JMenuItem("Save As...");
    saveAsItem.setMnemonic('S');
    saveAsItem.setAccelerator(KeyStroke.getKeyStroke("control S"));

    // (2) Build  menubar, menus, and add menuitems.
    JMenuBar menubar = new JMenuBar();
    JMenu fileMenu = new JMenu("File");
    fileMenu.setMnemonic('F');
    menubar.add(fileMenu);
    fileMenu.add(openItem);
    fileMenu.addSeparator();
    fileMenu.add(saveItem);

    // (3) Add listeners to menu items
    openItem.addActionListener(new OpenAction()); // TODO change

    setJMenuBar(menubar);

    JToolBar toolbar = new JToolBar("Toolbar", JToolBar.VERTICAL);//);
//      JPanel panel = new JPanel();
//      panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
    JButton newb = new JButton("new");
    toolbar.add(newb);
//      toolbar.setOpaque(true);
    toolbar.setLocation(100, 100);
    toolbar.setVisible(true);
//      toolbar.setMinimumSize(new Dimension(100, 100));
//      toolbar.setAlignmentX(0);

//      panel.add(toolbar);
    add(toolbar, BorderLayout.NORTH);
    getContentPane().add(toolbar, BorderLayout.NORTH);
//      getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);

    setTitle(title);

    pack();
    setLocationRelativeTo(null);  // Center window.
}

// OpenAction
class OpenAction implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(Menu.this, "Can't Open.");
    }
}
}

A: its work fine, and you don't need to setVisible tool bar because its showing by default, also don't add the tool bar two time in the same place (NORTH)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MenuDemo {
    public static void main(String... args) {
        EventQueue.invokeLater(
            new Runnable() {
                @Override
                public void run() {
                    JFrame menu = new Menu("Testing");
                    menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    menu.setVisible(true);
                }
            }
        );
    }
}

class Menu extends JFrame {
    private JMenuItem openItem;
    private JMenuItem saveItem;
    private JMenuItem saveAsItem;

    public Menu(String title) {

        openItem = new JMenuItem("Open...");
        openItem.setMnemonic('O');
        openItem.setAccelerator(KeyStroke.getKeyStroke("control O"));

        saveItem = new JMenuItem("Save");
        saveItem.setMnemonic('S');
        saveItem.setAccelerator(KeyStroke.getKeyStroke("control S"));

        saveAsItem = new JMenuItem("Save As...");
        saveAsItem.setMnemonic('S');
        saveAsItem.setAccelerator(KeyStroke.getKeyStroke("control S"));

        // (2) Build  menubar, menus, and add menuitems.
        JMenuBar menubar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        fileMenu.setMnemonic('F');
        menubar.add(fileMenu);
        fileMenu.add(openItem);
        fileMenu.addSeparator();
        fileMenu.add(saveItem);

        // (3) Add listeners to menu items
        openItem.addActionListener(new OpenAction()); // TODO change

        setJMenuBar(menubar);

        JToolBar toolbar = new JToolBar("Toolbar", JToolBar.VERTICAL);//);

        JButton newb = new JButton("new");
        toolbar.add(newb);

        add(toolbar, BorderLayout.NORTH);
        setTitle(title);
        setLocationRelativeTo(null);
        pack();
    }

    // OpenAction
    private class OpenAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(Menu.this, "Can't Open.");
        }
    }

}

A: My problem was that I was the way I was instantiating my JFrame.  I was using a helper function like this one:
public static JFrame openInJFrame(Container content, int width, int height,
        String title, Color bgColor) {

    // ...
    frame.setContentPane(content);

    frame.setVisible(true);
    return (frame);
}

So my JToolBar was getting replaced by the Container object...
Thanks guys! Your answers helped me figure out my problem.


text:
Q: android studio lldb display std::vector's incorrect value I debug JNI std:: vector code in the android studio, LLDB display std:: vector's element incorrect value, but the std:: vector memory is correct. the effect is below image:
https://i.stack.imgur.com/9BVgF.png
develop environment:
MacBook Pro 10.12.6
Android Studio:3.1.1
LLDB: 3.1
The "hello-libs" demo is one of google git https://github.com/googlesamples/android-ndk.git
Similar problems link:Bug in Android C++/C debugger, incorrect argument values


text:
Q: How to link Boost library with CMake (on a cluster if boost is in non-standard location)? I have a strange problem, when I try to build a simple Boost test program on a cluster.
On my machine, everything works just fine.
First the example:
//main.cpp
#include <iostream>
#include <string>
#include "boost/program_options.hpp"

namespace po = boost::program_options;

int main( int argc , char* argv[] ) {

  po::options_description desc("Allowed options");
  desc.add_options()
  ("help", "produce help message")
  ("greet", po::value<std::string>()->default_value("World"), "the greeting")
  ;

  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);

  std::cout << "Hello, " << vm["greet"].as<std::string>() << "!" << std::endl;
  return 0;
}

And the CMakeLists.txt
cmake_minimum_required(VERSION 3.5)
project(boost_test)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

find_package(Boost COMPONENTS program_options)

set(SOURCE_FILES main.cpp)

if(Boost_FOUND)
    add_executable(boost_test ${SOURCE_FILES})
    target_include_directories(boost_test PRIVATE ${Boost_INCLUDE_DIRS})
    target_link_libraries(boost_test PRIVATE ${Boost_LIBRARIES})
endif(Boost_FOUND)

I use cmake like
cmake -G "Unix Makefiles" /path/to/code
make

The error I get is a undefined reference error during linking:
Linking CXX executable boost_test
CMakeFiles/boost_test.dir/main.cpp.o: In function `main':
main.cpp:(.text+0x6d): undefined reference to `boost::program_options::options_description::options_description(std::string const&, unsigned int, unsigned int)'
CMakeFiles/boost_test.dir/main.cpp.o: In function `boost::program_options::variables_map::operator[](std::string const&) const':
main.cpp:(.text._ZNK5boost15program_options13variables_mapixERKSs[_ZNK5boost15program_options13variables_mapixERKSs]+0x1f): undefined reference to `boost::program_options::abstract_variables_map::operator[](std::string const&) const'

and so on ...
So I thought that maybe the installation of boost is not correct and I tried to write a makefile myself.
boost-test-1: ../code/main.cpp
    g++ ../code/main.cpp -o boost-test-1 -lboost_program_options

boost-test-2: ../code/main.cpp
    g++ ../code/main.cpp -o boost-test-2 /some/fancy/cluster/path/certainly/non/standard/Boost/lib/libboost_program_options.so

Both ways to build the program work fine. But what cmake is doing is basically the following: first, build a object file, second link the object file and the library together and that fails.
boost-test-3: ../code/main.cpp
    /usr/bin/c++    -I/some/fancy/cluster/path/certainly/non/standard/Boost/include  -std=c++11   -o main.cpp.o -c ../code/main.cpp
    /usr/bin/c++    -std=c++11   main.cpp.o  -o boost-test-3 /some/fancy/cluster/path/certainly/non/standard/Boost/lib/libboost_program_options.so

As already mentioned, on my computer all described ways to build the program work, but on the cluster, the cmake way unfortunately fails. The problem is that I have another larger project that uses cmake and I am looking for a way to build it on that particular cluster.
Do you have any idea what could cause the problem and how to solve it?
Thank you!

Update: This is the whole output of the build process. I shortened the paths to cmake and boost to "path/to/cmake" and "path/to/boost" to make it shorter and better readable, but it is the same long path as described above.
$ cmake -G "Unix Makefiles" ../code/
-- The C compiler identification is GNU 4.8.5
-- The CXX compiler identification is GNU 4.8.5
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Boost version: 1.61.0
-- Found the following Boost libraries:
--   program_options
-- Boost include directories (Boost_INCLUDE_DIRS): /path/to/Boost/include
-- Link directories for Boost libraries (Boost_LIBRARY_DIRS): /path/to/Boost/lib
-- Boost component libraries to be linked (Boost_LIBRARIES): /path/to/Boost/lib/libboost_program_options.so
-- Configuring done
-- Generating done
-- Build files have been written to: /home/test/build

$ make VERBOSE=1
/path/to/CMake/bin/cmake -H/home/test/code -B/home/test/build --check-build-system CMakeFiles/Makefile.cmake 0
/path/to/CMake/bin/cmake -E cmake_progress_start /home/test/build/CMakeFiles /home/test/build/CMakeFiles/progress.marks
make -f CMakeFiles/Makefile2 all
make[1]: Entering directory `/home/test/build'
make -f CMakeFiles/boost_test.dir/build.make CMakeFiles/boost_test.dir/depend
make[2]: Entering directory `/home/test/build'
cd /home/test/build && /path/to/CMake/bin/cmake -E cmake_depends "Unix Makefiles" /home/test/code /home/test/code /home/test/build /home/test/build /home/test/build/CMakeFiles/boost_test.dir/DependInfo.cmake --color=
Dependee "/home/test/build/CMakeFiles/boost_test.dir/DependInfo.cmake" is newer than depender "/home/test/build/CMakeFiles/boost_test.dir/depend.internal".
Dependee "/home/test/build/CMakeFiles/CMakeDirectoryInformation.cmake" is newer than depender "/home/test/build/CMakeFiles/boost_test.dir/depend.internal".
Scanning dependencies of target boost_test
make[2]: Leaving directory `/home/test/build'
make -f CMakeFiles/boost_test.dir/build.make CMakeFiles/boost_test.dir/build
make[2]: Entering directory `/home/test/build'
[ 50%] Building CXX object CMakeFiles/boost_test.dir/main.cpp.o
/usr/bin/c++    -I/path/to/Boost/include  -std=c++11   -o CMakeFiles/boost_test.dir/main.cpp.o -c /home/test/code/main.cpp
[100%] Linking CXX executable boost_test
/path/to/CMake/bin/cmake -E cmake_link_script CMakeFiles/boost_test.dir/link.txt --verbose=1
/usr/bin/c++    -std=c++11   CMakeFiles/boost_test.dir/main.cpp.o  -o boost_test /path/to/Boost/lib/libboost_program_options.so
CMakeFiles/boost_test.dir/main.cpp.o: In function `main':
main.cpp:(.text+0x6d): undefined reference to `boost::program_options::options_description::options_description(std::string const&, unsigned int, unsigned int)'
CMakeFiles/boost_test.dir/main.cpp.o: In function `boost::program_options::variables_map::operator[](std::string const&) const':
main.cpp:(.text._ZNK5boost15program_options13variables_mapixERKSs[_ZNK5boost15program_options13variables_mapixERKSs]+0x1f): undefined reference to `boost::program_options::abstract_variables_map::operator[](std::string const&) const'
CMakeFiles/boost_test.dir/main.cpp.o: In function `boost::program_options::basic_command_line_parser<char>::basic_command_line_parser(int, char const* const*)':
main.cpp:(.text._ZN5boost15program_options25basic_command_line_parserIcEC2EiPKPKc[_ZN5boost15program_options25basic_command_line_parserIcEC5EiPKPKc]+0x76): undefined reference to `boost::program_options::detail::cmdline::cmdline(std::vector<std::string, std::allocator<std::string> > const&)'
CMakeFiles/boost_test.dir/main.cpp.o: In function `boost::program_options::basic_command_line_parser<char>::extra_parser(boost::function1<std::pair<std::string, std::string>, std::string const&>)':
main.cpp:(.text._ZN5boost15program_options25basic_command_line_parserIcE12extra_parserENS_9function1ISt4pairISsSsERKSsEE[_ZN5boost15program_options25basic_command_line_parserIcE12extra_parserENS_9function1ISt4pairISsSsERKSsEE]+0x33): undefined reference to `boost::program_options::detail::cmdline::set_additional_parser(boost::function1<std::pair<std::string, std::string>, std::string const&>)'
CMakeFiles/boost_test.dir/main.cpp.o: In function `std::vector<std::string, std::allocator<std::string> > boost::program_options::to_internal<std::string>(std::vector<std::string, std::allocator<std::string> > const&)':
main.cpp:(.text._ZN5boost15program_options11to_internalISsEESt6vectorISsSaISsEERKS2_IT_SaIS5_EE[_ZN5boost15program_options11to_internalISsEESt6vectorISsSaISsEERKS2_IT_SaIS5_EE]+0x46): undefined reference to `boost::program_options::to_internal(std::string const&)'
CMakeFiles/boost_test.dir/main.cpp.o:(.rodata._ZTVN5boost15program_options11typed_valueISscEE[_ZTVN5boost15program_options11typed_valueISscEE]+0x40): undefined reference to `boost::program_options::value_semantic_codecvt_helper<char>::parse(boost::any&, std::vector<std::string, std::allocator<std::string> > const&, bool) const'
CMakeFiles/boost_test.dir/main.cpp.o: In function `boost::program_options::typed_value<std::string, char>::name() const':
main.cpp:(.text._ZNK5boost15program_options11typed_valueISscE4nameEv[_ZNK5boost15program_options11typed_valueISscE4nameEv]+0x32): undefined reference to `boost::program_options::arg'
CMakeFiles/boost_test.dir/main.cpp.o: In function `boost::program_options::typed_value<std::string, char>::xparse(boost::any&, std::vector<std::string, std::allocator<std::string> > const&) const':
main.cpp:(.text._ZNK5boost15program_options11typed_valueISscE6xparseERNS_3anyERKSt6vectorISsSaISsEE[_ZNK5boost15program_options11typed_valueISscE6xparseERNS_3anyERKSt6vectorISsSaISsEE]+0x7a): undefined reference to `boost::program_options::validate(boost::any&, std::vector<std::string, std::allocator<std::string> > const&, std::string*, int)'
collect2: error: ld returned 1 exit status
make[2]: *** [boost_test] Error 1
make[2]: Leaving directory `/home/test/build'
make[1]: *** [CMakeFiles/boost_test.dir/all] Error 2
make[1]: Leaving directory `/home/test/build'
make: *** [all] Error 2

A: Thank you Amadeus, Someprogrammerdude and Tsyvarev for leading me in the right direction here :)
In fact, it was a compiler issue: The default compiler on the cluster was gcc-4.8.5, which cannot handle the latest Boost versions. Therefore, we loaded a module for gcc-5.4 but /usr/bin/gcc was still gcc-4.8.5. When we set the cxx compiler for cmake to gcc-5.4 the build process still failed, since we also use CUDA and per default the host code is not forwarded to the cxx compiler but the c compiler, which was still gcc-4.8.5. So after setting CUDA_HOST_COMPILER to CMAKE_CXX_COMPILER it works fine now.


text:
Q: How to set a permanent time and date on Raspberry Pi? I am using the Debian flavor of Linux on Raspberry Pi, and I want to set the date and time permanently. I am using the following command.
sudo date -s "Mar  08:10"

How can I achieve this?

A: Try to change date & time in /etc/fake-hwclock.data. This helped me,
it was found there.
But there is still a chance of me misunderstanding the question. It would help if you want to set default date & time.

A: I assume that by "set permanent time" you mean you want to set the date (at most) once and then have it power up with the correct time. I have three suggestions.
Option 1 - The Raspberry Pi does not have a clock, but one could be added.  See this question in the Raspberry Pi Forum and this aftermarket hardware clock.  I'm sure there are other hardware clocks available.
Option 2 - Use some sort of network connection and get the time via NTP, but I expect that is not what you were looking for.
Option 3 - Use a GPS chip and collect the time from that. If you get one with NMEA output to a serial port (available from the vendor in the above link and others) you don't need any special software. See this description of NMEA sentences for help in extracting the date from the GPS output. This will not work very well if the device is not able to get a GPS fix.


text:
Q: UWP: WebAuthenticationBroker.AuthenticateAsync not working for dropbox? The method WebAuthenticationBroker.AuthenticateAsync from the Windows.Security.Authentication.Web namespace seems to work for Google, but not for Dropbox. For Dropbox, it shows "Can't connect to the service".
Fastest way to reproduce (for UWP and Xamarin.UWP):
Use
var requestUri = new Uri("https://dropbox.com/oauth2/authorize?dummyQueryString"); in a call with
var response = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, requestUri, new Uri("dummycallbackUri:/"));
This results in:

Calling it with
var requestUri = new Uri("https://accounts.google.com/o/oauth2/auth?dummyQueryString");
results in Google-content being displayed (a 400 Bad Request, but that is as expected with a dummy query string).
I tested another random requestUri "https://stackoverflow.com/" that has nothing to do with OAuth, I get:

This last example may provide some information on how the WebAuthenticationBroker works... is it really using an old browser while I'm using the latest version of Mozilla FireFox as my default browser?
How can I use WebAuthenticationBroker.AuthenticateAsync for Dropbox?

A: I can't speak to why it's showing an error instead of the page, but Dropbox doesn't officially support processing the OAuth app authorization flow in a web view like this (per docs), so you should send this through the system browser instead anyway.
These web views sometimes do use old browser engines instead of whatever you have installed as your system browser, so they are more prone to compatibility issues like that.

A: good luck. i know your pain. this is a heinou tangle
that i just sorted out.
few things:
yes use the AuthenticateAsync(starturi);
no dont use the overload AuthenticateAsync(starturi, callbackuri);
overload if you are a public client (desktop app not using a client cert). it wont work. you only need to provide the reply url in the query string. i cant find now, buti learned in a weird place, i think a token descriptor table in a microsoft learn doc that, public clients use the sso flow, and that you cant use that second reply url param in authasync for sso. but you d still need to add the reply url as a query arg on you start uri. you can construct the start uri bylooking here:
https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#request-an-authorization-code
for 3p account providers, you need to set it up in the appx manifext under declaration>webaccountprovider.

the reply url needs to be "real." if you want to use localhost, thats a whole other uwp shit show. localhost needs to be registered as a reply url with the app registration. its insecure so dont do if ur appid is already GA or in prod. also, even if you do register it, you also still needs to move mountins to allow uwp to app to not block. you need to add it to a loopback exemption by ding this
cmd window
> Get-AppxPackage <your app name>
Name              :
...
PackageFamilyName : someprefix.someprefix.CamelCaseName_alplhanumwekyb3d8bbwe
PublisherId       : alplhanumwekyb3d8bbwe
...
Status            : Ok

> CheckNetIsolation.exe LoopbackExempt -a -n=CamelCaseName_alplhanumwekyb3d8bbwe
OK.
> CheckNetIsolation.exe LoopbackExempt -s
List Loopback Exempted AppContainers

[1] -----------------------------------------------------------------
    Name: AppContainer NOT FOUND
    SID:  S-1-15-2-1...

[2] -----------------------------------------------------------------
    Name: someprefix.CamelCaseName_alplhanumwekyb3d8bbwe
    SID:  S-1-15-2-...<legit SID>


text:
Q: Condense "flat" list of occurrences for analysis with arules eclat I have a file that looks like this (list of person ID and product name)
123   A
123   B
123   D
456   A
456   B
123   C

And I'd like to convert it for use with eclat to something like this (list of products each person purchased)
list(
   c("A", "B", "D", "C"),
   c("A", "B" )
 )

The best I've been able to do is to read it as a data frame, and attempt using the variants of the apply function to make the new data strucutre.
collectValues <- function(obs,map) {
  a = obs[1][1]
  b = obs[2][1]
  if( ! (a %in% map) ) {
    map[[a]] <- list(b)
  } else {
    c(map[[a]], b)
  }
}

but I'm too new to R to get this to work...

A: I think you're after split as in:
dat <- read.table(text="123   A
123   B
123   D
456   A
456   B
123   C", header=FALSE, stringsAsFactors = FALSE)

lapply(split(dat[, 2], dat[, 1]), sort)

## $`123`
## [1] "A" "B" "C" "D"
##
## $`456`
## [1] "A" "B"

I used the lapply with sort as that's what you're desired output looked like but you may not need it.


text:
Q: iPhone - MapKit : How may I customize the color and alpha of an overlay on the fly? I have a MapView onto which I put some overlays (MKPolygon).
I have to maintain groups of MKPolygon.
For this, I have a PolyGonGroupClass that keeps each poly and the color and alpha that should be used to display all these polygons.
So, each time I find a poly, I add it as a map overlay and memorize in into the correct group of polys.
All my groups of poly are kepts into an instance var.
[self.mapView addOverlay:poly];
[thecorrectpolygroup addObject:poly];
...
[self.mypolygroups addObject:thecorrectpolygroup];

@interface PolyGonGroupClass : NSObject {
    UIColor* __color;
    float __alpha;
    NSMutableArray* __polygons;
}

Well...
At this point, how may I tell to the MapView the color and alpha of each poly and update them on the fly when one of these color change ?
I found a - (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay method, but I don't see how I may use it to retrieve the values I put into the memorised values.
I guess I should use the overlay parameter, but how may I retrieve the correct group of poly that correspond to that overlay ?

A: In viewForOverlay, you can loop through your mypolygroups array and check if the overlay is in that group's polygons array:
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
    if ([overlay isKindOfClass:[MKPolygon class]])
    {
        MKPolygonView *pv = [[[MKPolygonView alloc] initWithPolygon:overlay] autorelease];

        for (PolyGonGroupClass *pgc in mypolygroups)
        {
            if ([pgc.polygons containsObject:overlay])
            {
                pv.fillColor = pgc.color;
                pv.alpha = pgc.alpha;
                break;
            }
        }

        return pv;
    }

    return nil;
}

However, for this to work right, you'll have to slightly change where you call addOverlay.  In the code you've shown, you are calling addOverlay before adding it to the polygons array and before adding the group to the mypolygroups array.  This can cause viewForOverlay to fire before the arrays contain data.
Instead, move just the addOverlay calls to after the mypolygroups array is fully populated.  So after adding the last group to mypolygroups:
...
[self.mypolygroups addObject:theLastPolygroup];

for (PolyGonGroupClass *pgc in mypolygroups)
{
    for (MKPolygon *p in pgc.polygons)
    {
        [mapView addOverlay:p];
    }
}

Finally, to update a group's color and alpha later after it's already on the map, you can do something like this:
//pgc is some instance of PolyGonGroupClass
pgc.alpha = newAlpha;
pgc.color = newColor;

for (MKPolygon *p in pgc.polygons)
{
    MKPolygonView *pv = (MKPolygonView *)[mapView viewForOverlay:p];
    pv.alpha = pgc.alpha;
    pv.fillColor = pgc.color;
}


text:
Q: C++ Add number to Array Object? I am implementing a communication interface for the operating system Rodos from C++ to Java.
My C++ is a little bit "rusty" and I've never seen this operation before: header+0 for an array!
rodos/api/gateway/networkmessage.h:
class NetworkMessage {
    static const int HEADER_SIZE = 26;
    uint8_t header [HEADER_SIZE];
public:
    inline void    put_checkSum(uint16_t x)          {int16_tToBigEndian(header+0, x); }
    inline void    put_senderNode(int32_t x)         {int32_tToBigEndian(header+2, x); }

rodos/support_libs/stream-bytesex.cpp:
void int16_tToBigEndian(void* buff, uint16_t value) {
    uint8_t* byteStream = (uint8_t*)buff;
    if (byteStream == 0) return;
    byteStream[0] = (uint8_t) ((value >> 8) & 0xFF);
    byteStream[1] = (uint8_t) ((value >> 0) & 0xFF);
}

How do I have to implement this addition of an integer-array and an integer in Java?

A: Arrays in C are mostly syntactic sugar over typed pointers. For T foo[...] declaration, an expression foo + 2 means pointer to the 3rd element of array foo.


text:
Q: Prevent previously requests on click I have list of tables,
<table id="<%#DataBinder.Eval(Container.DataItem, "Certificate")%>" class="tbl_evenSearchResultRow" onmouseover="this.className='ResultGridRowSeleted'" onmouseout="this.className='tbl_evenSearchResultRow'" onclick="return SynopsisWindowOpen(this)">

onclick of each i use next function:
 function SynopsisWindowOpen(obj) {
var title = $(obj).find("strong[name='title']").html();

var isParentools = 0;
if (window.location.href.indexOf('recent_releases.aspx') > -1)
    isParentools = 1;

var url = "/ratings/Synopsis.aspx?logoonly=1&Certificate=" + obj.id + "&Title=" + encodeURIComponent(title) + "&parentools=" + isParentools;

$("#ratingModal").on("show.bs.modal", function (e) {
    $.ajax({
        url: url,
        cache: false,
        dataType: "html",
        success: function (data) {
            $("#ratingModal").find(".modal-body").html(data);
        }
    });
});
$("#ratingModal").on("hide.bs.modal", function (e) {
    $(this).find(".modal-body").html('');
});
$("#ratingModal").modal('show');

return false;
}

By url i render body of modal : i get certificate from request.query and according to it render body
LoadSynopsisContent(Request.QueryString["Certificate"], Request.QueryString["parentools"]);

Problem : when i click at first - everything seems to be good, on second click in modal body firstly rendered body of first click and then of second click. And so on.
I don't know where is problem.
Firstly i use jquery load function, but then i change to simple ajax call with disabled caching.

A: Move the all event bindings to outside of the function and everything should work fine.
Thus, these parts should not be inside the function:
$("#ratingModal").on("show.bs.modal", ....);

$("#ratingModal").on("hide.bs.modal", ....);

Here is one way you could organize your code:
var url; //a global variable ... not a good idea though
function SynopsisWindowOpen(obj) {
    ....
    url = .....
}

$(function() {
    $("#ratingModal").on("show.bs.modal", ....);

    $("#ratingModal").on("hide.bs.modal", ....);
});

However, the way would be to not use inline JavaScript but to take advantage of the power of jQuery to separate structure from behavior.
UPDATE
Instead of using a global variable url you can store the new url in a data attribute of the modal. Then you can get it from there when the modal opens.
In the function:
//calculate the url
var url = .....
//store the url in the modal
$('#ratingModal").data('table-url', url);

In the modal event handler:
$("#ratingModal").on("show.bs.modal", function(e) {
    //retrieve the url from the modal
    var url = $(this).data('table-url');
    //use the url
    $.ajax({ url: url, .... }):
});


text:
Q: Uncaught TypeError: layer.onAdd is not a function First attempt at working with Leaflet to display and work with a dynamic map, and I'm running into an error when I attempt to add a new layer of markers to a LayerGroup.
Here is my Map object, encapsulating the functionality of leaflet:
function Map() {
  //properties/fields
  var map;
  var layers = [];

  return {
    setMap: function(aMap) {map=aMap;},
    setView: function(aView) {map.setView(aView);},
    addLayer: function(aLayer, name) {layers[name] = aLayer; map.addLayer(aLayer);},
    addListings: function(anArr, name) {
        var mLayer = [];
        for (var i = 0; i < anArr.length; i++) {
            var aMarker = L.marker([anArr[i][0], anArr[i][1]]);
            mLayer.push(aMarker);
        };
        layers[name] = L.layerGroup(mLayer);
        layers[name].addTo(map);
    },
    updateListings: function(anArr, name) {
        var mLayer = [];
        for (var i = 0; i < anArr.length; i++) {
            console.log(anArr[i].entity.locations[0].lat, anArr[i].entity.locations[0].lng);
            var aMarker = L.marker(anArr[i].entity.locations[0].lat, anArr[i].entity.locations[0].lng);
            mLayer.push(aMarker);
        }
        layers[name].addLayer(mLayer);
    },
    clearLayer: function(name) { layers[name].clearLayers(); },
  };
}

When I load the map initially, everything's fine:
                myMap.setMap(L.map('tikit-map').setView([{{ $result['lat'] }}, {{ $result['lng'] }}], 12));
                var listLocation = [];
                @foreach ($result['company'] as $facility)
                    listLocation.push([{{ $facility['entity']['locations'][0]['lat'] }}, {{ $facility['entity']['locations'][0]['lng'] }}]);
                @endforeach
                myMap.addListings(listLocation, 'listings');

Then, when I need to refresh the screen (and the map) via an ajax call (with data coming back via the variable companies, I get the error:
myMap.clearLayer('listings');
myMap.updateListings(companies, 'listings');

The error specifically occurs in the line:
layers[name].addLayer(mLayer);
of updateListings
Anyone with some experience with leaflet that can offer some advice? Thanks

UPDATE: The issue I'm having revolves about why I can't "reuse" the
  LayerGroup after I've cleared it, and how I would go about doing that. I've
  struggled through the first half of this day for a solution and was
  about to post the code as a demo on jsfiddle when I came across this:
  https://github.com/Leaflet/Leaflet/blob/master/FAQ.md You can add the
  Google Maps API as a Leaflet layer with a plugin. But note that the
  map experience will not be perfect, because Leaflet will just act as a
  proxy to the Google Maps JS engine, so you won't get all the
  performance and usability benefits of using Leaflet when the Google
  layer is on.
Because the requirement of the project is to use Google maps, I am
  abandoning my efforts, perhaps someone needing to do this will benefit
  from any future answers.

A: You are creating a plain vanilla javascript array with var mLayer = [];, when you really need to be using the Leaflet construct for arrays of layers, which is either L.layerGroup or L.featureGroup - depending on the amount of interactivity. It sounds like for your usecase, var mLayer = L.layerGroup would be fine.


text:
Q: How to read data stored in a DataReaderDest in an SSIS package I am new to SSIS, I want to create a package that query data from CRM (Dynamics 365), manipulate them with a script (code c#) then update back queried data.
My problem is that I searched the whole internet but I did not find how to read data from 'DataReaderDest' using Script component, here is a screenshot of my package


text:
Q: How do I redirect a URL with special (%C2%A0) characters in Nginx I found out that I have link to one of URLs with some garbage behind that would generate some traffic, however whoever it placed it did it wrong:
/domain/sub-directory/%C2%A0

Therefore, I would like to redirect this URL to the one it was intended. However, I could not figure out how to do this properly.
I tried already:
location ^~ /sub-directory/(.*) { return 301 https://example.com/sub-directory/; }

and also
rewrite ^https://example.com/sub-directory/%C2%A0$ https://example.com/sub-directory/ permanent;

but none of them works. Any idea, how to fix this?

A: You can represent it as a hex value in a regular expression.
For example:
rewrite ^(/sub-directory/)\xC2\xA0$ $1 permanent;


text:
Q: Compare strings in templates I have the following template:
{{if . eq "login failed"}}
Incorrect username or password
{{else if . eq "login success"}}
You have successfully logged in!
{{end}}

I am passing a string when I execute the template.
However, I get the following error:
executing "login.html" at <.>: can't give argument to non-function .

How do I compare the strings within the template?

A: eq is function, not an operator. It is called with the form: eq <x> <y> (not <x> eq <y>).
You can fix your template by moving the operands from the the sides of eq to after it:
{{if eq . "login failed"}}
Incorrect username or password
{{else if eq . "login success"}}
You have successfully logged in!
{{end}}

A: To compare if two strings equal :
{{ if eq .Status "Approved" }}
       ...Do something
{{ else }}
       ...Do something else
{{ end }}

To compare if two strings not equal :
  {{ if ne .Status "" }}  // If status is not empty
           ...Do something
  {{ else }}
           ...Do something else
  {{ end }}

There are more golang HTML template directives here at : https://pkg.go.dev/text/template#hdr-Actions


text:
Q: Pass filename as variable in python during reading a file I have an image file in the following location.
'D:\\projects\\Aielectric\\Bird\train_images\\BIRD_v200_1_1/IMG_2012-09-26T09-00-07.jpg'

While I am trying to read by directly giving the filename it reads the image properly.
Working Code
mm = cv2.imread( r'D:\\projects\\Aielectric\\Bird\train_images\\BIRD_v200_1_1/IMG_2012-09-26T09-00-07.jpg' )

But when I pass the path as variable, it is showing NoneType Object and is not reading the actual contents of file.
Not working code
tt = 'D:\\projects\\Aielectric\\Bird\train_images\\BIRD_v200_1_1/IMG_2012-09-26T09-00-07.jpg'

mm = cv2.imread( tt )

My requirement is to pass the name as a variable as it is not static. How to achieve this ?


text:
Q: Running CGI application in window 7 IIS I have create a application in C/C++ that has the extension .cgi followed the instruction in gSoap specification, now i want to deploy my application in IIS, how can i do it?
Thanks for reading.

A: Probably you should go through the following tutorials first.
http://blogs.iis.net/thomad/how-to-run-a-cgi-program-under-iis-7-0-or-iis-7-5
http://community.microfocus.com/microfocus/cobol/net_express__server_express/w/knowledge_base/23805.deploying-cgi-web-application-on-iis-7.aspx


text:
Q: Dynamic Column Copy/Paste based off of Data Validation List At the end of every month, we copy/paste forecast sales (where the formulas are) as a hardcode into other columns for reference and reconciliation purposes.
For example, copy Column D (January) through Column F (march) into column Q (Jan hardcoded) through S (March hardcoded)
I'm trying to modify my code so the user can select from two data validation dropdowns which month range (e.g. Jan - Mar) on each of the forecast tabs to copy/paste as values.
For example, below is something I've added to copy/paste based on the # rows for a formula.
Dim LastRow As Long
With ActiveSheet
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
Range("T1") = "PPU"
Range("T2") = "=S2/R2"
Range("T2").Copy
Range("T2:T" & LastRow).Select `dynamic row
Selection.PasteSpecial xlFormulas
Range("T:T").Copy
Range("T:T").PasteSpecial xlPasteValues

With my code above, is it possible to alter this so, instead of " & Lastrow", I keep the rows static but make the columns to copy variable, so for lack of a better term firstMonth & secondMonth.
The columns to select would be based off two named ranges where the user chooses from two data validation lists (firstMonth & secondMonth) with each column being assigned a column "letter" (e.g. Jan is column D, Feb Column E, etc.)
Without being dynamic, it would be something like:
Range("D12:F19").Copy
Range("Q12").PasteSpecial xlValues

But I'd like to have the user select with months, via a data validation list, to have hardcoded by choosing a beginning month (firstMonth) and ending month (secondMonth)
Something along the lines of:
Range(firstMonth &"12": secondMonth & "19").Copy `firstMonth in theory is the column letter so, "D12" and secondMonth is the second column letter (F12)

Range("pasteFirstMonth &"12").PasteSpecial xlValues `the firstMonth will be paired with the column letter, say "Q" where it will paste those values.  A second column range isn't needed here since only the copied range will paste, not overlapping anything else.  This is the "hardcoded" area.

Update:  Slightly reconfigured Tim's answer below.
Sub copyColumns()

Dim months, m1, m2, sht

    months = Split("Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec", ",")
    Set sht = ActiveSheet

    m1 = Application.Match(sht.Range("Month1").Value, months, 0)
    m2 = Application.Match(sht.Range("Month2").Value, months, 0)

    sht.Range(sht.Cells(8, 3 + m1), sht.Cells(16, 3 + m2)).Copy
    sht.Range(sht.Cells(8, 16 + m1), sht.Cells(16, 16 + m2)).PasteSpecial xlValues

End Sub

A: Something like this should work:
Sub DoCopy()

    Dim months, m1, m2, sht

    months = Split("Jan,Feb,Mar,Apr,May,June,July,Aug,Sept,Oct,Nov,Dec", ",")
    Set sht = ActiveSheet

    m1 = Application.Match(sht.Range("Month1").Value, months, 0)
    m2 = Application.Match(sht.Range("Month2").Value, months, 0)

    If Not IsError(m1) And Not IsError(m2) Then
        'copy range - use offset (3 here) depending on where months begin
        sht.Range(sht.Cells(12, 3 + m1), sht.Cells(19, 3 + m2)).Copy
        'etc
    End If

End Sub

A: You can prompt the user for selecting the desired months and you can use the Selection object, like
Set rng=Selection
Cells(rng.row, rng.column) gives you the top left cell of the selection,
rng.Columns.Count gives you the number of columns, etc.

From a users perpective it is much easier to select an area on the screen and press a button than entering values or selecting them from list.


text:
Q: Cannot configure the publishing extension for gradle I am using gradle v3.4 with the following build.gradle file.  However, I get the error copied below with any tasks.  Any thoughts on what might be misconfigured in the build.gradle file?
error
What went wrong:
A problem occurred evaluating root project 'some-test'.
> Cannot configure the 'publishing' extension after it has been accessed.

The error points to where the publishing task begins.
build.gradle
group 'some.group'
version '0.0.1' //-SNAPSHOT'

apply plugin: 'java'
apply plugin: 'application'
apply plugin: 'idea'
apply plugin: 'com.google.protobuf'
apply plugin: 'maven'
apply plugin: 'maven-publish'
apply plugin:'com.github.johnrengelman.shadow'

buildscript {
    repositories {
        mavenLocal()
        mavenCentral()
        maven {
            credentials {
                username project.properties['nexusUsername']
                password project.properties['nexusPassword']
            }
            url project.properties['nexus.url.snapshot']
        }
        jcenter()
    }
    dependencies {
        classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.0'
        classpath 'com.github.jengelman.gradle.plugins:shadow:1.2.4'
    }
}

if (!JavaVersion.current().java8Compatible) {
    throw new IllegalStateException("Must be built with Java 8 or higher")
}

mainClassName = "com.some.project.some.class"

defaultTasks 'clean', 'build', 'shadowJar', 'install'

compileJava {
    sourceCompatibility = '1.8'
    targetCompatibility = '1.8'
}

[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'

repositories {
    maven {
        credentials {
            username project.properties['nexusUsername']
            password project.properties['nexusPassword']
        }
        url project.properties['nexus.url.snapshot']
    }
    mavenLocal()
    mavenCentral()
    jcenter()
}

def grpcVersion = '1.1.2'
def log4j2Version = '2.8.1'
def configVersion = '1.3.1'
def jacksonVersion = '2.8.7'

dependencies {
    compile "io.grpc:grpc-netty:${grpcVersion}"
    compile "io.grpc:grpc-protobuf:${grpcVersion}"
    compile "io.grpc:grpc-stub:${grpcVersion}"
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: jacksonVersion
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: jacksonVersion
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: jacksonVersion

    compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: log4j2Version
    compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: log4j2Version
    compile 'io.netty:netty-tcnative-boringssl-static:1.1.33.Fork26'
    compile group: 'org.bouncycastle', name: 'bcprov-jdk16', version: '1.46'
    compile "com.typesafe:config:${configVersion}"

    testCompile group: 'junit', name: 'junit', version: '4.11'
    testCompile "org.mockito:mockito-core:1.9.5"
    compile 'commons-lang:commons-lang:2.3'
}

sourceSets {
    main {
        proto {
            srcDir '../../proto' // In addition to the default 'src/main/proto'
        }
        java {
        }
    }
    test {
        proto {
            srcDir '../../proto' // In addition to the default 'src/test/proto'
        }
    }
}

protobuf {
    protoc {
        artifact = 'com.google.protobuf:protoc:3.2.0'
    }
    plugins {
        grpc {
            artifact = "io.grpc:protoc-gen-grpc-java:${grpcVersion}"
        }
    }
    generateProtoTasks {
        all()*.plugins {
            grpc {
                // To generate deprecated interfaces and static bindService method,
                // turn the enable_deprecated option to true below:
                option 'enable_deprecated=false'
            }
        }
    }
}

idea {
    module {
        sourceDirs += file("${projectDir}/build/generated/source/proto/main/java");
        sourceDirs += file("${projectDir}/build/generated/source/proto/main/grpc");
    }
}

jar {
    manifest {
           attributes(
                'Class-Path': configurations.compile.collect { it.getName() }.join(' '),
                'Main-Class': 'com.some.project.some.class'
        )
    }
}

shadowJar {
    baseName = 'commons-java'
    classifier = null
    version = null
}

artifacts {
    archives shadowJar
}

publishing {
    publications {
        shadow(MavenPublication) {
            from components.shadow
        }
    }
    repositories {
        maven {
            credentials {
                username "someuser"
                password "somepassword"
            }
            url "http://nexus.somewhere.com/repository/some-test-snapshots/"
        }
    }
}

tasks.publish.dependsOn 'shadowJar'

startScripts.enabled = false

A: The issue was how I was reading the properties - also, I no longer use both maven and maven-publish plugins (I am using maven-publish only).  I am currently able to publish to nexus successfully.


text:
Q: C++ typedef WORD Каким образом можно определить тип WORD.
Необходимо, чтобы размер этого типа не зависел от архитектуры(32 или 64 бит)
Использование windows.h невозможно, так как пишется все под UNIX.
A: #include <stdint.h>

typedef int16_t WORD;

A: Боюсь, что вопрос, поставленный таким образом не имеет ответа.
Далее моя "компиляция" (выдержки) из книги "Ядро Linux. Описание процесса разработки" (просто недавно прочел, и думаю, цитаты будут к месту).
==
Машинное слово (word) - это количество данных, которые процессор может обработать за одну операцию. Когда говорят о n-разрядной машине, то чаще всего имеют в виду размер машинного слова. Например, когда говорят, что Intel Core i7 является 64-разрядным, то имеется в виду размер машинного слова, равный 64 разрядам, или 8 байтам.
Размер регистров вобщего назначения процессора соответствует размеру машинного слова этого процессора.
В ОС Linux размер виртуального адресного пространства соответствует размеру машинного слова, следовательно размер указателя равен ему.
Размер типа long языка C также равен машинному слову, тогда как размер типа int может быть меньше.
==
Т.е. по мнению писателей ядра Linux надо написать
typedef long WORD;

или
typedef unsigned long WORD;

Далее просто цитата из книги:
Слова, двойные слова и путаница в терминологии

В некоторых операционных системах и процессорах стандартную порцию данных
не называют машинным словам. Вместо этого словом называется фиксированная
порция данных, название которой выбрано случайным образом случайным образом
или имеет исторические корни. Например, в некоторых системах данные могут
разбиваться на байты (byte - 8 бит), слова (word - 16 бит), двойные слова
(double word - 32 бит) и учетверенные слова (quad word - 64 бит), несмотря
на то, что на самом деле система является 32-разрядной. Подобная система
наименований была принята в системах на основе Windows NT, а также в современной
Windows 7.

Таким образом, @Чистяков Владислав, без уточнения для решения каких задач Вам нужен тип WORD, корректно ответить не получится.
A: Например, так:
#include <cstdint>

#define WORD uint32_t

Если ваш компилятор старый и не поддерживает C++11, используйте boost: #include <boost/cstdint.hpp> вместо #include <cstdint>.


text:
Q: Why json.Marshal and json.Unmarshal have different signature func Marshal(v interface{}) ([]byte, error)
func Unmarshal(data []byte, v interface{}) error

notice that Marshal accept an interface and return a []byte as output, while Unmarshal accept an []byte and write output directly to the input parameter data
what make the difference in design
an associate question:
I think use input parameter could save in-memory copy once(function return need a copy), every assignment in golang is a copy op, so it looks like Unmarshal can save a copy, but Marshal not.
so I'm confused...

A: The potential functions in symmetric pairs are:
func Marshal(v interface{}) ([]byte, error)         // 1
func Unmarshal(data []byte) (interface{}, error)    // 2

func Marshal(v interface{}, data *[]byte) error     // 3
func Unmarshal(data []byte, v interface{}) error    // 4

Functions #3 and #4 might not look symmetric because the data argument to #3 is a pointer type and the v argument to #4 is not declared to be a pointer type. They are in fact symmetric because the actual value passed to the v argument of #4 must be a pointer. The function returns an error if it is not a pointer.
Function #2 is not viable because the function does not have access to the application's result type. The function cannot unmarshal the JSON to a type if the type is not known to the function. Further, the application will need to type assert the result to use it. The standard library avoids type assertions when possible.
Function #3 is not idiomatic. Pointers to slices are rarely used in Go. I don't recall the use of any in the standard library, but I am sure someone will leave a comment here if there is a one.
We are left with the unsymmetric pair of #1 and #4:
func Marshal(v interface{}) ([]byte, error)         // 1
func Unmarshal(data []byte, interface{}) error      // 4

A: By having Marshal  return a byte array, you can easily pass that to functions like bufio.Writer.Write() which takes a byte array as an argument. You might have one of those when you're writing a web service that serves JSON.
If you're using Unmarshal, then you're likely reading from JSON. By having Unmarshal take the same first argument as Marshal returns, you can get any JSON that has been output by Marshal, and pass it straight to Unmarshal.


text:
Q: IE8 vertical scrollbar problem i have a problem in ie8, my site is http://www.2sinfotech.com/demo/guitar//
when i click on join now or other link like faq. i didn't get vertical scrollbar in my site.
some time i get scroll or some time not.

A: I ran your HTML through the W3C validator and it's complaining about <div class="wrapper"> not being closed before the closing </body>.  I would start with trying to get that fixed.


text:
Q: Flutter Error: The operator '[]' isn't defined for the class 'Object?' I have an error like this :
 - 'Object' is from 'dart:core'.
Try correcting the operator to an existing operator, or defining a '[]' operator.
                    itemCount: snapshot.data['data'].length,

                                            ^
: Error: The operator '[]' isn't defined for the class 'Object?'.
lib/screens/homepage.dart:33
 - 'Object' is from 'dart:core'.
Try correcting the operator to an existing operator, or defining a '[]' operator.
                      return Text(snapshot.data['data'][index]['name']);
                                               ^

This is my code homepage.dart:
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class HomePage extends StatelessWidget {
  const HomePage({
    Key? key,
  }) : super(key: key);

  final String url = 'http://10.0.2.2:8000/api/products';
  //android emulator http://10.0.2.2 mac http://127.0.0.1

  Future getProducts() async {
    var response = await http.get(Uri.parse(url));
    print(json.decode(response.body));
    return json.decode(response.body);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Botang Store'),
        ),
        body: FutureBuilder(
            future: getProducts(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return ListView.builder(
                    itemCount: snapshot.data['data'].length,
                    itemBuilder: (context, index) {
                      return Text(snapshot.data['data'][index]['name']);
                    });
              } else {
                return Text('Data Error');
              }
            }));
  }
}

This is my main.dart:
import 'package:flutter/material.dart';
import 'package:toko_online/screens/homepage.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Botang Store',
      home: HomePage(),
    );
  }
}

This is my pubspec.yaml
name: toko_online
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: "none" # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.13.0 <3.0.0"

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  http: ^0.13.0

dev_dependencies:
  flutter_test:
    sdk: flutter

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^1.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:
  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

Can anyone solve it? I search for it but I don't find it. I'm new in flutter so I hope everyone can give me the answer for my code. I just follow the tutorial, but when I try it I have an error like this.
Thanks before.

A: The analyzer is complaining because there is it doesn't know what type  snapshot.data['data'] is you need to assign it to a variable and cast it as a List or whatever type it actually is (based on the code it looks like a List<Map<String,dynamic>>.
                                \/ it's complaining about this.
return Text(snapshot.data['data'][index]['name']);

Something like:
              if (snapshot.hasData) {
                final data = snapshot.data['data'] as List<Map<String, dynamic>>;
                return ListView.builder(
                    itemCount: data.length,
                    itemBuilder: (context, index) {
                      return Text(data[index]['name']);
                    });
              } else {
                return Text('Data Error');
              }

You might consider decoding this into meaningful Model classes instead of using raw Maps and Lists.


text:
Q: String 999999999.9999999999 is rounded to 1,000,000,000 BigDecimal I have a problem where my 999999999.9999999999 String is being rounded to 1,000,000,000 BigDecimal when I parse it.
Code:
NumberFormat format = new DecimalFormat("#.0000000000######");
format.setParseIntegerOnly(false);
Number number = format.parse(text);

Result:
number = 1.0E9
If I use the same format to parse the result BigDecimal back to String:
format.format(number) results in 1,000,000,000

Why does this happen and how I can force the original format.parse(text) call not to round?

A: Unless there's some code you've omitted, parse is returning a Double, not a BigDecimal.  (Try System.out.println(number.getClass()) to check this.)
If you want a BigDecimal, you have to use setParseBigDecimal to tell it to return a BigDecimal.  (And to do that, format has to be declared as DecimalFormat.)
DecimalFormat format = new DecimalFormat("#.0000000000######");
format.setParseBigDecimal(true);
Number number = format.parse(text);


text:
Q: UILabel Animated Letter I am trying to make an animation as seen in the picture. In the example code I give, the characters after the click are overlaid. How can I make an animation like in the picture.
Thank you.

func letterTapAction(sender: UITapGestureRecognizer) {
    for label in lettesLabel {
        if sender.view == label {
            copyLabelAndAnimate(fromLabel: label)
        }
    }
}

func copyLabelAndAnimate(fromLabel: UILabel) {
    let copiedLabel = UILabel.init(frame: CGRect(x: fromLabel.frame.minX, y: fromLabel.frame.minY ,width: fromLabel.bounds.width, height: fromLabel.bounds.height))
    copiedLabel.text = fromLabel.text!
    copiedLabelsTagCounter += 1
    copiedLabel.tag = copiedLabelsTagCounter
    copiedLabel.font = UIFont.init(name: "Noteworthy-Bold", size: 28.0)
    view.addSubview(copiedLabel)

    //UIView.removeFromSuperview(view.viewWithTag(101)!)

    UIView.animate(withDuration: 0.2, animations: {
        copiedLabel.frame.origin = CGPoint.init(x: self.view.frame.size.width / 2 + CGFloat(self.spaceForCopiedLabels), y: self.view.frame.minY + CGFloat(15))
    })

    if lettersThatNeedLessSpace.characters.contains(copiedLabel.text!.characters.first!) {
        spaceForCopiedLabels -= 8
    }

    spaceForCopiedLabels += 25

}

A: In general:

*

*Have 1 letter per label (so 10 of them in your example) and manage them from a class for the bottom area.

*Don't copy the labels but simply move them from bottom to the line, while also changing backgroundColor and textColor.

*Create a class that manages the line. Create a method in the line class that calculates the center coordinate of the next letter, when one would be added.

When user taps a letter at bottom:

*

*Ask the line object the coordinate of the next letter.

*Convert that line coordinate to the coordinate space of the bottom area.

*Do a simple UIView animation from the bottom area to the new coordinate.

*When the animation is initiated, tell the line that a new letter is coming. This will allow the line object to move its existing letters a bit to the left.

*When the animation completes, you could move the tapped UILabel from the view hierarchy of the bottom area to the line.