text:
Q: Providing source code as public domain One question was so interesting that I worked out a solution as program.
While I would like to share it, I am not happy with the Creative Commons License.
I have read the already existing posts and I find the legal problems as much too
unspecified and problematic (When it is code, when a snippet, does other laws
apply to me etc. etc.)
I would prefer to offer it as Public Domain. No restrictions at all, no enforced
copyleft, no need to tag me as author. The opportunity to get rich by exploiting
me, you name it. ;-)
As the idea of the Creative Commons is that content will be available on SO even
if the author later disagrees, I see no conflict with this goal because releasing
all rights would automatically give SO the right to retain and modify the code.
So, is it possible to post this code under Public Domain ? Or use less restrictive
licenses in general ? I think (hopefully) that many people here would like to share
their code and snippets as Public Domain, too.

A: There's no problem at all with you posting your own code somewhere else and explicitly placing it into the public domain. Such dual licenses are quite common. There's no mechanism for licensing different bits as posted on the SE network, but if you distribute the code through your own channel, you may do it however you wish.

A: Anything you produce, you own the copyright to. You can release that to the public under whichever license(s) you wish. (Note the potential plural.) By posting it on SO, you release it under the CC-BY-SA 3.0 license. There's nothing stopping you also releasing it under CC0 or WTFPL (or both).
Or you can "release it to the public domain" (possibly). As the FAQ for the WTFPL says,

Unfortunately, the definition of public domain varies with the jurisdictions, and it is in some places debatable whether someone who has not been dead for the last seventy years is entitled to put their own work in the public domain.

Wikipedia has a template for that: PD-Self:

I, the copyright holder of this work, release this work into the public domain. This applies worldwide.
In some countries this may not be legally possible; if so:
I grant anyone the right to use this work for any purpose, without any conditions, unless such conditions are required by law.

This seems reasonable. And I don't see why you'd need to host it elsewhere to put such a license on it. There's nothing stopping you putting some code here with a comment at the top:
// License: WTFPL (http://www.wtfpl.net)

That'd be sufficient.
Alternatively, you could put a note in your profile to the effect that all your code snippets on this site are available under such-and-such a licence.
(This answer is licensed under both CC0 and WTFPL.)


text:
Q: Get webkit version in cocoa I'm working on OSX application that needs a CSS preview.
I need to find a way to differentiate users with safari 5.0 from users with safari 5.1 because webkit preview has many differences in this 2 versions.
For example, the gradient radial interpretation is totally different!
Is there a way to intercept the webkit version ?

A: You can get the user-agent string for the current WebKit version using JavaScript. Just do something like this:
NSString* userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];

which will produce something like this:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/534.51.14 (KHTML, like Gecko)

You can then parse the user-agent string to get the version of WebKit in use.

A: This helps you getting the WebKit version before loading the request so you could probably put together your own user agent. So this solution is better:
NSBundle *webKit = [NSBundle bundleWithIdentifier:@"com.apple.WebKit"];
NSString *version = [[webKit infoDictionary] objectForKey:@"CFBundleVersion"];

if (webKit && [webKit load]) {
    NSLog(@"%@", [webKit infoDictionary]);
}

[webKit unload]; // you might also unload the bundle, if you don't need it later

redpajama_set_name: RedPajamaStackExchange


text:
Q: Filter all columns in timeseries to keep only top 1/3 I have a timeseries with about 100 dates, 50 entities per date (so 5,000 rows) and 50 columns (all are different variables). How can I filter each column in the data frame, per unique date, to keep the top 1/3 of values for each column on each date. Then get the average Return for that group for that date. Thank you.
My data is organized as follows but the numbers in each column are random and vary like they do in column "a" (this is a sample, the real data has many more columns and many more rows):
Date      Identity       Return   a     b     c    d     e      f... ...z
2/1/19        X                5      75   43     67   85    72     56     92
2/1/19        Y                4      27   43     67   85    72     56     92
2/1/19        Z                7      88   43     67   85    72     56     92
2/1/19        W               2      55   43     67   85    72     56     92
2/2/19         X               7      69   43     67   85    72     56     92
2/2/19         Y               8      23   43     67   85    72     56     92
2/3/19         X                2      34   43     67   85    72     56     92
2/3/19         Y                3      56   43     67   85    72     56     92
2/3/19         Z                4      62   43     67   85    72     56     92
2/3/19         W               4      43   43     67   85    72     56     92
2/3/19         U                4      26   43     67   85    72     56     92
2/4/19         X                6      67   43     67   85    72     56     92
2/4/19         Y                1      78   43     67   85    72     56     92
2/5/19         X                4      75   43     67   85    72     56     92
2/7/19         X                5      99   43     67   85    72     56     92
2/7/19         Y                 4      72   43     67   85    72     56     92
2/7/19         Z                  4      45   43     67   85    72     56     92

I am trying to filter data into quantiles. I have a code that works for filtering into quantiles for one measure. However I want filtered results for many measures individually (i.e. I want a "high" group for a ton of columns).
The code that I have that works for one measure is as follows.
Columns are date, identity, and a a is the indicator I want to sort on
High = df[!is.na(df$a),] %>%
    group_by(df.date) %>%
    filter(a > quantile(a, .666)) %>%
    summarise(high_return = sum(df.return) / length(df.identity)

Now I want to loop this for when I have many indicators to sort on individually (I.e. I do not want to sort within one another, I want each sorted separately and the results to be broken out by indicator)
I want the output of the loop to be a new data frame with the following format (where a_Return is the average return of the top 1/3 of the original a's on a given date):
Date       a_Return    b_Return    c_Return
2/1/19       6.            7           3
2/3/19       4.            2           5
2/4/19       2.            4           6

I have tried the code below without it working:
Indicators <- c("a", "b", "c")

for(i in 1:length(Indicators)){
     High = df %>%
        group_by(df.date) %>%
        filter(High[[I]] > quantile(High[[i]], .666)) %>%
        summarise(g = sum(df.return) / length(df.identity)}

With this attempt I get the error: "Error in filter_impl(.data, quo) : Result must have length 20, not 4719.
I also tried:
High %>%
    group_by(date) %>%
    filter_at(vars(Indicators[i]), any_vars(. > quantile (., .666)))%>%
    summarise(!!Indicators[I] := sum(Return) / n())

but with that code I get the error "Strings must match column names. Unknown Columns: NA"
I want High to turn up with a date column and then a column for each a, b, and c.

A: If you combine the filtering and calculations into a single function, then you can put that into summarize_at to apply it easily to each column. Since you're example data isn't fully reproducible, I'll use the iris dataset. In your case, you'd replace Species with Date, and Petal.Width with Return:
library(dplyr)
top_iris <- iris %>%
    group_by(Species) %>%
    summarize_at(vars(one_of('Sepal.Length', 'Sepal.Width', 'Petal.Length')),
                 funs(return = sum(Petal.Width[. > quantile(., .666)]) / length(Petal.Width[. > quantile(., .666)])))

top_iris

# A tibble: 3 x 4
  Species    Sepal.Length_return Sepal.Width_return Petal.Length_return
  <fct>                    <dbl>              <dbl>               <dbl>
1 setosa                   0.257              0.262               0.308
2 versicolor               1.44               1.49                1.49
3 virginica                2.1                2.22                2.09

The problem with using filter is that each function in the pipe runs in order, so any criteria you give to filter_* will have to be applied to the whole data.frame before the result is piped into summarize_at. Instead, we just use a single summarize_at statement, and filter each column as the summarization function is applied to it.

To explain this in more detail, summarize_at takes 2 arguments:
The first argument is one or more of the variable selector functions described in ?select_helpers, enclosed in the vars function. Here we use one_of which just takes a vector of column names, but we could also use matches to select using a regular expession, or starts_with to choose based on a prefix, for example.
The second argument is a list of one or more function calls to be run on each selected column, enclosed in the funs function. Here we have 1 function call, to which we've given the name return.
Like with any tidyverse function, this is evaluated in a local environment constructed from the data piped in. So bare variable names like Petal.Width function as data$Petal.Width. In *_at functions, the . represents the variable passed in, so when the Sepal.Length column is being summarized:
Petal.Width[. > quantile(., .666)]

means:
data$Petal.Width[data$Sepal.Length > quantile(data$Sepal.Length, .666)]

Finally, since the function in funs is named (that's the return =), then the resulting summary columns have the function's name (return) appended to the original column names.

If you want to remove missing data before running these calculations, you can use na.omit to strip out NA values.
To remove all rows containing NA, just pipe your data through na.omit before grouping:
iris2 <- iris
iris2[c(143:149), c(1:2)] <- NA

iris2 %>%
    na.omit() %>%
    group_by(Species) %>%
    summarize_at(vars(one_of('Sepal.Length', 'Sepal.Width', 'Petal.Length')),
                 funs(return = sum(Petal.Width[. > quantile(., .666)]) / length(Petal.Width[. > quantile(., .666)])))

  Species    Sepal.Length_return Sepal.Width_return Petal.Length_return
  <fct>                    <dbl>              <dbl>               <dbl>
1 setosa                   0.257              0.262               0.308
2 versicolor               1.44               1.49                1.49
3 virginica                2.09               2.19                2.07

To strip NA values from each column as it's being summarized, you need to move na.omit inside the summarize function:
iris2 %>%
    group_by(Species) %>%
    summarize_at(vars(one_of('Sepal.Length', 'Sepal.Width', 'Petal.Length')),
                 funs(return = {
                     var <- na.omit(.)
                     length(Petal.Width[var > quantile(var, .666)])
                 }))
# A tibble: 3 x 4
  Species    Sepal.Length_return Sepal.Width_return Petal.Length_return
  <fct>                    <dbl>              <dbl>               <dbl>
1 setosa                   0.257              0.262               0.308
2 versicolor               1.44               1.49                1.49
3 virginica                2.11               2.2                 2.09

Here we use curly braces to extend the function we run in summarize_at to multiple expressions. First, we strip out NA values, then we calculate the return values. Since this function is in summarize_at it gets applied to each variable based on the grouping established by group_by.


text:
Q: FileStream Object throws Exception when Accessing the WebSite from Client Machine in the Same Nework When I try to run the WebApplication From Visual Stuido 2010 and Hosted WebService in the same Machine It works fine.
But when I access the same WebSite from different Machine..
I got this Exception
Could not find file 'c:\windows\system32\inetsrv\98280INFO000001TIF1.tif'. ErrorSource:mscorlibStackTrace:   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
   at Create_Page.butt_ok_Click(Object sender, EventArgs e)

The Piece of Code throws Exception in this Line.
 FileStream fstream = new FileStream(imgFile, FileMode.Open,FileAccess.ReadWrite);

Please help we got this Error on Deployment.

A: c:\windows\system32\inetsrv\98280INFO000001TIF1.tif
Is an unusual location for storing image files.  Perhaps you need to specify the full path.


text:
Q: what are the dangers of Thread.Sleep in Multi-Threaded code in production environment I am dealing with Multi-Threaded code  written by my predecessor within C# WinForm application that handles large volumes of data concurrently in production environment. I have identified that at some points within the code Thread.Sleep(20) is used. I am not very expert in multithreading and have basic knowledge of threading and synchronisation primitives. I need to know whether there are any dangers associated with Thread.Sleep

A: It's not going to be explicitly or directly dangerous.  It's almost certainly wasting effort, as explicitly forcing your program to not do work when it has work to do is almost never sensible.
It's also a pretty significant red flag that there's a race condition in the code and, rather than actually figure out what it is or how to fix it, the programmer simply added in Sleep calls until he stopped seeing it.  If true, it would mean that the program is still unstable and could potentially break at any time if enough other variables change, and that the issue should be actually fixed using proper synchronization techniques.


text:
Q: cant find my image file [Errno 2] No such file or directory: 'F:/cc/train/1(1).png' Python 3.5.2 |Anaconda 4.2.0 (64-bit)|
I want to do character identification,I wrote program to randomly generate 26*2(capital and Minuscule)and put it in F:/cc ,and also generate a csv file to store the labels.
I named the images as 1(1),1(2).......1(2038),all .png files

 train_size = 2038
 test_size = 785
 for i in range(train_size):
     buf = 'F:/cc/train/1({}).png'.format(i+1)
     buf1 = 'F:/cc/train_small/1({}).png'.format(i+1)
     image = io.imread(buf)
     image = numpy.invert(image)
     misc.imsave(buf1, image)

 for i in range(test_size):
     buf = 'F:/cc/test/1({}).png'.format(i+1)
     buf1 = 'F:/cc/test_small/1({}).png'.format(i+1)
     image = io.imread(buf)
     image = numpy.invert(image)
     misc.imsave(buf1, image)
</blink>

then have this error:
[Errno 2] No such file or directory: 'F:/cc/train/1(1).png'
I'm new to python, thanks for helping


text:
Q: C# SerialPort datareceived and WPF UI freezing My goal is to spy a gsm module RX/TX communication on a custom system.
For this, I use 2 serial ports on my computer and a WPF c# app.
On specific commands, the comunnication between the gsm module and the system is able to change for 9600bds, 57600bds or 125000bds.
With 9600 and 57600, no problem.
But when the com speed is 125000, my UI freeze.
I have read a lot of posts about UI freezing with Action, Delegate, dispatcher but it doesn't work and I don't understand how to solve my issue.
Here, what I'm doing for now:

*

*I have 2 serial ports from System.IO.Ports;

*the 2 serial ports use the same SerialDataReceivedEventHandler

*inside the SerialDataReceivedEventHandler, I build a custom class instance of "QueueElement" with serialPort name, the bytes received and the hour when the event occurs. This QueueElement is push in a Queue from

*every 100ms, a timer tick event read the Queue to display all item from it to the UI ListBox.

Here some code to explain how I proceed:
// queue to store data read on serial port before display
Queue<QueueElement> queueList;

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    initPorts();
    queueList = new Queue<QueueElement>();
    QueueConsumerProcessRunning = false;
    queueConsumer();
}

private void initPorts()
{
    mySerialPort1.DataReceived += new SerialDataReceivedEventHandler(SerialPort_DataReceived);
    mySerialPort2.DataReceived += new SerialDataReceivedEventHandler(SerialPort_DataReceived);
    // ...
}

// data on serial port
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    Monitor.Enter(queueList);
    try
    {
        // create a queue element and add it to the queue
        // ...
        queueList.Enqueue(queueSingleElement);
    }
    finally
    {
        Monitor.Exit(queueList);
    }
}

private void queueConsumer()
{
    Thread backgroundThread = new Thread(
        new ThreadStart(() =>
        {
            while (true) // always alive
            {
                if ((QueueConsumerProcessRunning == false) && (queueList.Count > 0))
                {

                    Dispatcher.Invoke(() => { QueueCount.Text = queueList.Count.ToString(); });

                    QueueConsumerProcessRunning = true;
                    QueueElement Qelem;// = new QueueElement();

                    Monitor.Enter(queueList);
                    try
                    {
                        // get alodest element
                        Qelem = queueList.Peek();

                        // remove oldest element
                        queueList.Dequeue();
                    }
                    finally
                    {
                        Monitor.Exit(queueList);
                    }

                    // call method to display data
                    AddDataMethod(buildSerialElement(Qelem.SerialPortName, Qelem.ReadBytes, Qelem.EventHour));

                    QueueConsumerProcessRunning = false;
                }
                Thread.Sleep(100);
            }
        }
    )); // backgroundThread
    backgroundThread.IsBackground = true;
    backgroundThread.Start();
}

// display received data
// when incoming data is from the same serial port of last received data: add data on last written row except if it's a carriage return
private void AddDataMethod(SerialElement elem)
{
    if (!Dispatcher.CheckAccess()) // CheckAccess returns true if you're on the dispatcher thread       this.ListBoxSpy.Disp...
   {
        Dispatcher.Invoke(new AddDataDelegate(AddDataMethod), elem);
        return;
    }

    // update List<SerialElement>
    // ...
    // and call the function to update item displayed on UI
    refreshDisplay();
}

// refresh display
private void refreshDisplay()
{
    // create a list of ListBoxRowItem
    // ...
    // and display the list on ListBox UI

    ListBoxSpy.ItemsSource = myListBoxRows;
}

And the xaml part for the ListBox:
<ListBox Name="ListBoxSpy" HorizontalAlignment="Stretch" Margin="0,100,0,0" VerticalAlignment="Stretch" FontFamily="Courier New" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Message}" Foreground="{Binding MessageColor}" VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

I use Visual Studio Community 2017.

A: I think you've got a race condition with the Queue. I assume QueueConsumerTimedEvent is running on the UI thread. The while loop may be running forever because it is checking if queueList.Count > 0 but while processing the top item the DataReceived thread is adding more items to the queue. So it never reaches zero and thus holds up the UI thread.
You should at least move the Monitor.Enter to accomodate but then you run the risk of missing or delaying incoming data. Probably should dequeue first so you can release the Monitor quickly then process the dequeued item.


text:
Q: Expand div with both variable height and width I'm trying to create a div that will expand to the bottom of its container. The layout consists of two columns within a parent container. The width of both columns is a percentage, and the height of the parent container and the left column expands based on a slideshow in the left column. I'd like the height of the right column to match the left, so I can position something at the bottom. I've tried many different things, but to no avail. Here is the page:
http://whub30.webhostinghub.com/~scottl9/testindex2.html
The html is

         Left-column content

         Right-column content

and the corresponding CSS is
 #content_section { position:relative; min-height:400px; min-width:600px; max-height: 1000px; max-width:2000px;}
.imgwrap {position:relative; width:100%; height:auto; min-width:409px; min-height:230px; border-style:solid; border-width:medium; display: inline-block;}
.imgwrap2 {position:relative; float:left; width:70%; height:auto;}
.playersection {border-style:solid; width:30%; position: relative; float: right; border-width:medium;}
.clearall {clear:both;}`

(I added borders so I could see the divs.)
Any help would be greatly appreciated!

A: Try changing the height of Right Column to 100%.
.imgwrap2 {position:relative; float:left; width:70%; height:100%;}


text:
Q: Running mongod.exe from webstorm It's an extremely simple question but can anyone kindly tell me how can I start mongod.exe from Webstorm instead of from Command Prompt?
Thanks in advance.

A: It looks like there's a nice Webstorm plugin for this here.


text:
Q: How to zip two 1d numpy array to 2d numpy array I have two numpy 1d arrays, e.g:
a = np.array([1,2,3,4,5])
b = np.array([6,7,8,9,10])

Then how can I get one 2d array [[1,6], [2,7], [3,8], [4,9], [5, 10]]?

A: The answer lies in your question:
np.array(list(zip(a,b)))

Edit:
Although my post gives the answer as requested by the OP, the conversion to list and back to NumPy array takes some overhead (noticeable for large arrays).
Hence, dstack would be a computationally efficient alternative  (ref. @zipa's answer).  I was unaware of dstack at the time of posting this answer so credits to @zipa for introducing it to this post.
Edit 2:
As can be seen in the duplicate question, np.c_ is even shorter than np.dstack.
>>> import numpy as np
>>> a = np.arange(1, 6)
>>> b = np.arange(6, 11)
>>>
>>> a
array([1, 2, 3, 4, 5])
>>> b
array([ 6,  7,  8,  9, 10])
>>> np.c_[a, b]
array([[ 1,  6],
       [ 2,  7],
       [ 3,  8],
       [ 4,  9],
       [ 5, 10]])

A: You can use zip
np.array(list(zip(a,b)))
array([[ 1,  6],
   [ 2,  7],
   [ 3,  8],
   [ 4,  9],
   [ 5, 10]])

A: If you have numpy arrays you can use dstack():
import numpy as np

a = np.array([1,2,3,4,5])
b = np.array([6,7,8,9,10])

c = np.dstack((a,b))
#or
d = np.column_stack((a,b))

>>> c
array([[[ 1,  6],
        [ 2,  7],
        [ 3,  8],
        [ 4,  9],
        [ 5, 10]]])
>>> d
array([[ 1,  6],
       [ 2,  7],
       [ 3,  8],
       [ 4,  9],
       [ 5, 10]])

>>> c.shape
(1, 5, 2)
>>> d.shape
(5, 2)


text:
Q: How to write HTTP response using java socket I'm trying to write the standard response message to my brower when the browser connects, but the results do not display on my browser.
Here is the code
Socket sock;

PrintWriter writeSock;

BufferedReader readSock;
writeSock = new PrintWriter(sock.getOutputStream(),true);
writeSock.print("HTTP/1.1 200 OK\r\n" + "Hello world");

do I print to the writeSock to get it to show on the browser? I'm confused at how to put a standard HTTP response in java.

A: You need a blank line between the headers and the body of the response. Something like
writeSock.print("HTTP/1.1 200 OK\r\n\r\nHello world");

However, you'll want to read the HTTP specification to understand additional headers that should be sent with the response, like content-type.


text:
Q: How can we assume a bool Property on a Generic class , where T is a auto generated LINQ2SQL class I am doing a CRUD operation on Database generated class(using LINQ2SQL) in my WPF application. All of my DB tables have IsDelete property exists. So I want to define an abstract/interface class to do the SoftDelete(). My question here is, how can I define my Generic class in such a way as to access T.IsDelete = true ? or in code I want to do something like below
public abstract class CRUDOperations <T> : where T is????
{
  .......
  protected virtual SoftDelete()
  {
     T.IsDeleted = true;
  }
}

Where T is DB generated Table classes by LINQ To SQL (DBML), which I cant impose an Interface or base class on top of it?. Or is there a technique in DB to have a base table which has the same Base/Derive concepts of C#

A: 1) Define ISoftDelete
public interface ISoftDelete
{
  bool IsDeleted { get; set; }
}

2) Create partial classes for all your entities
public partial class MyLinqEntity : ISoftDelete { }
public partial class MyOtherLinqEntity : ISoftDelete { }
public partial class MyFurtherLinqEntity : ISoftDelete { }

3) Add your interface to the generic type restriction
public abstract class CRUDOperations <T> : where T is ISoftDelete

A: You can declare this on an interface:
public interface ICanDelete {
    bool IsDeleted {get;set;}
}

and let implicit interface implementation work its magic. Then the question becomes: "how to let it know that my entities implement this interface?". Two options:

*

*add a partial class per entity (in a different file):
partial class Customer : ICanDelete {}
partial class Order : ICanDelete {}

*edit the dbml to specify this interface as the base class:
<Database EntityBase="Some.NameSpace.ICanDelete" ... >

(this makes LINQ-to-SQL's code-generation add the : Some.NameSpace.ICanDelete for you)
Then just use this interface in the generic clause:
where T : ICanDelete

A: Aren't the Database generated classes derived from Entity?


text:
Q: Bibliography style unsrt not working I am writing a text (whose content I can't fully disclose here) and I am experiencing some issues with citation order, using unsrt as bibliography style. Until a certain point citations are ordered correctly, but since I have added some .tex files, this isn't happening anymore. Any suggestions?
\documentclass[a4paper,12pt,oneside,english,american]{book}
\usepackage[utf8]{inputenc}
\usepackage{listings}
\usepackage{subcaption}
\usepackage[toc,acronym,nonumberlist,acronym,shortcuts]{glossaries}

\usepackage{hyperref}
\usepackage{fancyhdr}
\usepackage{geometry}
\usepackage{pdfpages}
\usepackage{amsthm}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{pgfplots}
\usepackage{makecell}
\usepackage{lscape}
\usepackage{eurosym}

\usepackage[linesnumbered,ruled]{algorithm2e}

\usepackage{tcolorbox}

\tcbuselibrary{theorems}

\newtcbtheorem[number within=section]{mytheo}{Definition}%
{colback=green!5,colframe=green!35!black,fonttitle=\bfseries}{th}

\usepackage{url}

\hypersetup{pdftex,colorlinks=true,allcolors=black}

\makeatletter% Set distance from top of page to first float
\setlength{\@fptop}{5pt}
\makeatother
\sloppy

\pagestyle{fancy}
\fancyhead{}
\fancyfoot{}
\renewcommand{\headrulewidth}{0.5pt}
\renewcommand{\footrulewidth}{0pt}
\setlength{\headheight}{14.5pt}
\cfoot{\thepage}
\chead{\includegraphics[width=\textwidth]    {folder1/document1.pdf}}

\usepackage{eso-pic,graphicx}
\makeatletter
\newcommand\BackgroundPicture[2]{
\setlength{\unitlength}{1pt}
\put(0,\strip@pt\paperheight){
\parbox[t][\paperheight]{\paperwidth}{
\vfill
\centering\includegraphics[angle=#2]{#1}
\vfill
}
}
}
\makeatother

\geometry{verbose,tmargin=3cm,bmargin=3cm,lmargin=3.5cm,rmargin=2.5cm,headheight=2cm,headsep=0.5cm}
\linespread{1.5}

\lstset{belowcaptionskip=1\baselineskip,
breaklines=true,
frame=single,
xleftmargin=\parindent,
showstringspaces=false
}

\lstdefinestyle{ccode}{
basicstyle=\footnotesize\ttfamily,
language=C,
morekeywords={uint32_t},
identifierstyle=\color{green!40!black}
}

\lstdefinestyle{pseudocode}{
language=C,
basicstyle=\footnotesize\ttfamily,
morekeywords={uint32_t,not},
escapechar=@,
%keywordstyle=\bfseries\color{green!40!black},
%commentstyle=\itshape\color{purple!40!black},
%stringstyle=\color{orange},
}

\AtBeginDocument{
\renewcommand{\subsectionautorefname}{\sectionautorefname}
\renewcommand{\subsubsectionautorefname}{\sectionautorefname}
\renewcommand{\itemautorefname}{step}
}

\newcommand{\var}{\emph}

\makeglossaries

\title{Text Title}
\author{Text Author}
\vspace{3cm}

\begin{document}

\frontmatter

\includepdf[pages=-]{./folder1/document.pdf}

\AddToShipoutPicture{\BackgroundPicture{folder1/picture.png}{0}}
\setcounter{page}{1}

\nocite{*}

\phantomsection
\addcontentsline{toc}{chapter}{Contents}
\tableofcontents

    \cleardoublepage
\phantomsection
\addcontentsline{toc}{chapter}{List of Figures}
\listoffigures

\cleardoublepage
\phantomsection
\addcontentsline{toc}{chapter}{List of Tables}
\listoftables

%\cleardoublepage
\phantomsection
\printglossaries
\cleardoublepage

\graphicspath{{./figures/}{./measurements/}}

\mainmatter

\input{chapter1/1/chapter.tex}

\input{chapter/2/chapter.tex}

\bibliographystyle{unsrt}
\bibliography{references}

\end{document}


text:
Q: Why won't this python script input into a MySQL table I set up? I'm trying to pull data from the YouTube API into a local MySQL table. I went through a bunch of debugging until I landed on the below script, but I get no errors from this script, so I'm a bit lost. Anyone have any suggestions where to begin?
#!/usr/bin/python
# -- coding: utf-8 --

import MySQLdb
import os
import requests
import json
import sys
import re
import requests
import datetime

sql_conn = MySQLdb.connect(host="localhost", user="root", passwd="PSWD", db="researchyoutube")
sql_conn.autocommit(True)
sql_db = sql_conn.cursor(MySQLdb.cursors.DictCursor)

resp = requests.get("https://gdata.youtube.com/feeds/api/videos?q=kitten&orderby=published&start-index=11&max-results=50&v=2&alt=jsonc")

if(resp.status_code == 200):
    data = json.loads(resp.content)
    for item in data['data']['items']:

        title = item['title']
        uploaded_on = item['uploaded']
        description = item['description']
        video_length = item['duration']
        user = item['uploader']
        video_id = item['id']
        video_url = item['player']['default']

        sql = "INSERT IGNORE into NCII (title, uploaded_on, description, video_length, user, video_id, video_url) VALUES (title, uploaded_on, description, video_length, user, video_id, video_url)"

        sql_db.execute(sql)

A: Looks like  your VALUES() list contains the variable names rather than the appropriate %s placeholders
sql = "INSERT IGNORE into NCII (title, uploaded_on, description, video_length, user, video_id, video_url) VALUES (%s, %s, %s, %s, %s, %s, %s)"

# execute with the vars in a tuple
sql_db.execute(sql, (title, uploaded_on, description, video_length, user, video_id, video_url))


text:
Q: Set a 45° angle as a 0° angle for the accellerometer Hello everybody I'm developping a game that use the accellerometer to move a sprite in the Y-axis. Everything works well but the problem is that the angle at which the sprite doesn't move is 0°, but this means that when I want to move upwards the sprite I have to turn my hands in an unusual way ... So I thought I could set the base angle to 45 ° so all movements were easier. How can I do that?

A: I'm not sure about setting a base angle, but you could subtract 45° from your measurements of the accelerometer in your program, which would have the same effect.

A: Just define base vector,  and calculate difference between it and data received from accelerometer.   I would define base vector on startup,  or average over some time to
reduce noise ( yes, accelerometers used in mobile devices are pretty low quality )


text:
Q: Deciphering this regex in ruby octet = /\d{,2}|1\d{2}|2[0-4]\d|25[0-5]/
ip_regex = /^#{octet}\.#{octet}\.#{octet}\.#{octet}/

The regex above is used to match an IP address. I understand that \d is used to match a digit, and I also understand the ip_regex part, but after looking at some tutorials I'm still not able to completely understand the octet part.
Could someone enlighten me? What does {,2}|1 mean for example?

A:
What does {,2}|1 mean for example?

You should be looking at the parts separated by | – \d{,2} is a pattern, 1\d{2} is a pattern, etc. Here's what they mean:

*

*\d{,2} – up to 2 digit characters, i.e. numbers from 0 to 99

*1\d{2} – the digit 1 followed by 2 digits, i.e. numbers from 100 to 199

*2[0-4]\d – 2, then a digit from 0 to 4, then a digit, i.e. numbers from 200 to 249

*25[0-5] – 2, 5, and a digit from 0 to 5, i.e. numbers from 250 to 255

When you join them together with |, it's the pattern matching any of those patterns, i.e. numbers from 0 to 255.
The \d{,2} pattern is a bit wrong because it also matches the empty string and allows a leading zero, which is inconsistent with the other patterns.
If you wanted to check whether an entire string matched the pattern, a correct version would probably be this:
octet = /\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5]/
ip_regex = /\A#{octet}\.#{octet}\.#{octet}\.#{octet}\z/

A: One octet in an IP address (in dotted-octet notation) may not exceed 255.
So given /\d{,2}|1\d{2}|2[0-4]\d|25[0-5]/, break it apart like this: / \d{,2} | 1\d{2} | 2[0-4]\d | 25[0-5] /x
The first snip, \d{,2}, matches a 1 or 2 digit number. The second snip, 1\d{2}, matches any number between 100 and 199. The third snip, 2[0-4]\d, matches any number between 200 and 249. The last snip, 25[0-5], matches any number between 250 and 255. Put them all together, and an octet may be any number between 1 and 255.

A: There is a really cool tool to help understanding regular expressions: https://regexper.com It gives you the finite-state automaton, which is more visual and easy to understand that the regular expression.
For example, for octet you get:

Although with the {,2} is still not very clear. a{,2} means maximum 2, so it is equivalent to {0,2} (between 0 and 2). Changing this in the regular expresion regexper makes it a bit better:

And now I think it is easy to read.
Another good tool to try your regular expression is Rubular.


text:
Q: Telegram Bot privacy mode enabled but the BOT still reads all the messages in the group Possibly if there is any workaround to keep bot as admin at the same time?
I have my Bot with Privacy Mode Enabled. I wanted it to read messages starting with /.

This is from Telegram Documentation. It will still reply to messages which neither start with / or have username of bot in it.
MY CODE:
import * as functions from 'firebase-functions';
import * as express from 'express'
import * as cors from 'cors'

const bot = express()

bot.use(cors({ origin: true}))

bot.post('/', async (req, res) => {

    const telegramText = req.body
    && req.body.message
    && req.body.message.chat
    && req.body.message.chat.id
    && req.body.message.from
    && req.body.message.from.first_name

    if (telegramText) {
        const chat_id = req.body.message.chat.id
        const first_name = req.body.message.from.first_name
        const receivedMessage = req.body.message.text
      if (typeof userInput !== 'undefined') {

        return res.status(200).send({
            method: 'sendMessage',
            chat_id,
            text: `Here\'s your reply`
        })
    }
    }
    return res.status(200).send({status: 'An error occurred'})

})

export const router = functions.https.onRequest(bot)

See it is replying all the messages.
Though I don't want to verify it here if the message is starting with / or not. It will just consume my Firebase Cloud Functions Invocations. Why is the bot reading all messages?
I just don't want my Cloud Function to get triggered on each message so I want to prevent the bot to read all messages.
EDIT: I've tried:
(1) Waiting for a while
(2) Deleting and creating another bot.
(3) Removing Bot as Admin does help but then my bot won't be able to do most of the tasks.

A: Question is old, but I'm answering to help anyone who reads later:
Answer:
According to official doc:

Privacy mode is enabled by default for all bots, except bots that were
added to the group as admins (bot admins always receive all messages).

Possible alternative way:
So, seems there is no solution for this yet; but in case you writing a group manager bot or some sort of bots those need to have admin rights but no need to read messages directly (another bot can reads message and call this bot via it's script's URL to do something on specific message) and also load off the server, you may consider allowed_updates field of setWebhook method:

A JSON-serialized list of the update types you want your bot to
receive. For example, specify ["message", "edited_channel_post", "callback_query"] to only receive updates of these types. See Update
for a complete list of available update types. Specify an empty list
to receive all update types except chat_member (default). If not
specified, the previous setting will be used. Please note that this
parameter doesn't affect updates created before the call to the
setWebhook, so unwanted updates may be received for a short period of
time.


text:
Q: Upgrading Eclipse from Studio 2 to 3 gets all kinds of dependency errors related to Studio 2 Upgrading Eclipse from Studio 2 to 3 gets all kinds of dependency errors related to Studio 2 (bunch of gibberish for me to decipher in the details:
Cannot complete the install because of a conflicting dependency.
  Software being installed: Aptana Studio 3 Plugin 3.0.9.201202140953-7E777Q7HFGVBKBSEW7S_Iz0JktqM (com.aptana.feature.studio.feature.group 3.0.9.201202140953-7E777Q7HFGVBKBSEW7S_Iz0JktqM)
  Software currently installed: Aptana Studio 2.0.4.1268158907-5-7757FJ5398991HN1HIHtdfxN7r (com.aptana.ide.feature.studio.feature.group 2.0.4.1268158907-5-7757FJ5398991HN1HIHtdfxN7r)
  Only one of the following can be installed at once:
    Aptana SecureFTP Library 2.0.2.1317770565-3-12428881676 (com.aptana.ide.feature.libraries.subscription.feature.jar 2.0.2.1317770565-3-12428881676)
    Aptana Subscription Libraries 2.0.2.1257900677-3-12368A11788 (com.aptana.ide.feature.libraries.subscription.feature.jar 2.0.2.1257900677-3-12368A11788)
  Cannot satisfy dependency:
    From: Aptana Studio 3 Core 3.0.9.1329151902-BJ7F8NBTEBQakdyRh1DC34EVnIM5 (com.aptana.feature.feature.group 3.0.9.1329151902-BJ7F8NBTEBQakdyRh1DC34EVnIM5)
    To: com.aptana.ide.feature.libraries.subscription.feature.group [2.0.2.1317770565-3-12428881676]
  Cannot satisfy dependency:
    From: Aptana Studio 3 Plugin 3.0.9.201202140953-7E777Q7HFGVBKBSEW7S_Iz0JktqM (com.aptana.feature.studio.feature.group 3.0.9.201202140953-7E777Q7HFGVBKBSEW7S_Iz0JktqM)
    To: com.aptana.feature.feature.group [3.0.9.1329151902-BJ7F8NBTEBQakdyRh1DC34EVnIM5]
  Cannot satisfy dependency:
    From: Aptana Subscription Libraries 2.0.2.1257900677-3-12368A11788 (com.aptana.ide.feature.libraries.subscription.feature.group 2.0.2.1257900677-3-12368A11788)
    To: com.aptana.ide.feature.libraries.subscription.feature.jar [2.0.2.1257900677-3-12368A11788]
  Cannot satisfy dependency:
    From: Aptana SecureFTP Library 2.0.2.1317770565-3-12428881676 (com.aptana.ide.feature.libraries.subscription.feature.group 2.0.2.1317770565-3-12428881676)
    To: com.aptana.ide.feature.libraries.subscription.feature.jar [2.0.2.1317770565-3-12428881676]
  Cannot satisfy dependency:
    From: Aptana SecureFTP Support 2.0.4.1268103313-77-7878BMSG5BHEI04023479B228 (com.aptana.ide.feature.secureftp.feature.group 2.0.4.1268103313-77-7878BMSG5BHEI04023479B228)
    To: com.aptana.ide.feature.libraries.subscription.feature.group [2.0.2.1257900677-3-12368A11788]
  Cannot satisfy dependency:
    From: Aptana Studio 2.0.4.1268158907-5-7757FJ5398991HN1HIHtdfxN7r (com.aptana.ide.feature.studio.feature.group 2.0.4.1268158907-5-7757FJ5398991HN1HIHtdfxN7r)
    To: com.aptana.ide.feature.secureftp.feature.group [2.0.4.1268103313-77-7878BMSG5BHEI04023479B228]

A: Studio 3 is a major release with quite difficult underlying code from Studio 2, and you would need to uninstall Studio 2 first and then install Studio 3 instead of updating.


text:
Q: Numpy array Indexing with other arrays yields broadcasting error I have two indexing arrays.
elim=range(130,240)
tlim=range(0,610)

The array to be indexed, I,  has originally shape of (299, 3800)
When I try to index it as follow
I[elim,tlim]

I got the following error message.

shape mismatch: indexing arrays could not be broadcast together with shapes (110,) (610,)

I didn't expect such errors. Could someone explain what is happening here?
Thanks!

A: Let's reproduce the example with a random array of the specified shape:
elim=range(0,610)
tlim=range(130,240)
a = np.random.rand(299, 3800)

a[tlim, elim]

IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (110,) (610,)

This raises an error because you're using arrays of integer indexes to index the array, and hence advanced indexing rules will apply.
You should use slices for this example
a[130:240,0:610].shape
# (110, 610)

See Understanding slice notation (NumPy indexing, is just an extension of the same concept up to ndimensional arrays.
For the cases in which you have a list of indices, not necessarily expressable as slices, you have np.ix_. For more on numpy indexing, this might help
a[np.ix_(tlim, elim)].shape
# (110, 610)


text:
Q: jfrog cli error "wrong number of arguments" when running jfrog rt config I'm using the following command in a CI pipeline that builds a Docker container:
RUN curl -fL https://getcli.jfrog.io | sh \
    && mv jfrog /usr/local/bin/jfrog \
    && jfrog rt config --interactive false --url https://artifactory.myorg.com/artifactory

which is failing with error: [Error] Wrong number of arguments.:
Step 8/11 : RUN curl -fL https://getcli.jfrog.io | sh     && mv jfrog /usr/local/bin/jfrog     && jfrog rt config --interactive false --url https://artifactory.myorg.com/artifactory
 ---> Running in 975540bce561
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
100   178  100   178    0     0    329      0 --:--:-- --:--:-- --:--:--   330

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
100   985  100   985    0     0    782      0  0:00:01  0:00:01 --:--:--  3634
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0

 83 19.2M   83 16.0M    0     0  10.6M      0  0:00:01  0:00:01 --:--:-- 10.6M
100 19.2M  100 19.2M    0     0  11.4M      0  0:00:01  0:00:01 --:--:-- 19.9M
[Error] Wrong number of arguments. You can read the documentation at https://www.jfrog.com/confluence/display/CLI/JFrog+CLI

I've run the same commands on my local machine and gotten the same behaviour.
This is a command that we run in a CI pipeline and the last time that that CI pipeline ran was on 2018-04-19 (about 3 weeks ago) and I can see that on that occasion it succeeded:
Step 8/11 : RUN curl -fL https://getcli.jfrog.io | sh     && mv jfrog /usr/local/bin/jfrog     && jfrog rt config --interactive false --url https://artifactory.myorg.com/artifactory
 ---> Using cache
 ---> 1b0de0d85655
Step 9/11 : etc...

I can only infer that something in the jfrog CLI has changed in the interim. According to the documentation the command we're issuing:
jfrog rt config --interactive false --url https://artifactory.myorg.com/artifactory

is ok.
Hoping someone here can tell me what is wrong with this command,

A: Turns out this is a breaking change in the latest version of the CLI. Details here: https://github.com/JFrogDev/jfrog-cli-go/issues/165


text:
Q: To Develop LMS and Scorm Sequesncing Engine We want a LMS(coded in ASP.NET/vb.net) which is able to import SCORM packages & display it to learner for viewing content. I am totally new to SCORM and have been shifted to this project. I want to know how can I access SCORM Assessment object's (Test) result, like Learner ID, passed/fail, time.
Can you please guide me what will I need to implement in ASP.NET code to accomplish my goal ?
Task that I have done so far is,
Reading a manifest zip file, unzipping the file and get all information from the file(content name,description,items and launching page) and when user clicks on a particular course a pop up window is launching the page.
I eagerly want to know what I can do next to communicate with the LMS with the APIs. Shall I need to develop my own LMS to get the result,If there is a quiz which is running, all I need to know is the no of questions attempted by the user, whether the user is pass or fail and I need to store all information in the database for individual user so that I can review the result afterwards.
So the task remaining.

*

*Tracking mechanism to deliver the content.

*SCORM/LMS sequencing engine that controls the navigation between parts of SCORM conformant course.

Please help.

A: SLK at codeplex provides a good starting point. However, if you are truly wanting to provide an in-house written SCORM play that is fully compliant, you have a major task ahead of you. In essence there are three party you need to fully develop:
CAM - the unzipping process, which it sounds like you have already achieved.
RTE - the javascript host for SCORM, providing the 8 specified methods. Behind this you also need to implement the SCORM object model, which SLC does help with. If you have implemented all of this, then there should be data entries on the data model that indicate completion etc.
SN - the sequencing and navigation processing. This is significantly the most complex part. I am still in the process of trying to implement this, using SLC, and it is hard. It is the completion of this that will potentially give you more information that will enable you to know what has been done.
it is also worth looking at scorm.com, who are a consultancy, but provide a lot of useful information about the scorm standard.

A: That is true. SCORM is one of these stadarts where you can implement as little as possible. But you will need some of Javascript with a Backend-Script (JSON to the rescue) so you can track the scorm data, and save it your database.
But let me tell you this: This is the easiest task! Making your own course-creator is a whole other beast.


text:
Q: Multi-steps WordPress registration : in 4 steps how to? I saw in several WordPress sites up on registration that the registration process is in 3 or 4 steps.
how can i implement such process to my theme?  ie:

*

*choose your role + fill in register form----> if its ok submit then go to step 2

*profile details : user pic , some usermeta form ----< if its ok submit then go step 3

*Preview profile before confirm ---< go to step 4 or back to step 3 to make changes.

*registration complete success

UPDATE

hi guys i have figured it out little bit,(i am using jobroller theme which has a normal a one step registration form, but it has a multiple step forms for submting jobs listing)
  submit job form.
  what i wanted is to use the same (submit job multi-steps forms) for registration form so users are obliged to fill in profile details or whatever within the same process. registration.
  so i hacked the original registration of jobroller theme (includes/theme-login.php) and here what it gives.
theme-login.php

here is the function registration  steps that replace the original jr_register_form()
function jr_registration_steps() {

// Show registration steps forms

### Prevent Caching
nocache_headers();

jr_load_form_scripts();

//global $post, $posted;
global  $posted;
$submitID = $post->ID;

$posted = array();
$errors = new WP_Error();

if (!is_user_logged_in()) :
    $step = 1;
else :
    $step = 2;
    if (!current_user_can('can_submit_job')) : //can_submit_listing redirect to my listing
        redirect_myjobs();
    endif;
endif;

if (isset($_POST['register']) && $_POST['register']) {

    $result = jr_process_register_form( get_permalink($submitID) );

    $errors = $result['errors'];
    $posted = $result['posted'];

//}
//elseif (isset($_POST['login']) && $_POST['login']) {

    //$errors = jr_process_login_form();

}
elseif (isset($_POST['job_submit']) && $_POST['job_submit']) {

    $result = jr_process_submit_job_form();//jr_process_submit_user_registration_form

    $errors = $result['errors'];
    $posted = $result['posted'];

    if ($errors && sizeof($errors)>0 && $errors->get_error_code()) $step = 2; else $step = 3;

}
elseif (isset($_POST['preview_submit']) && $_POST['preview_submit']) {

    $step = 4;

    $posted = json_decode($_POST['posted']);

}
elseif (isset($_POST['confirm']) && $_POST['confirm']) {

    $step = 4;

    jr_process_confirm_job_form();//jr_process_confirm_user_registration_form

}
elseif (isset($_POST['goback']) && $_POST['goback']) {
    $posted = json_decode(stripslashes($_POST['posted']), true);
}

if( isset($_GET['checkemail']) && 'newpass' == $_GET['checkemail'] )
    $message = __('Thank you for registering! An email has been sent to you containing your password.','appthemes');

   get_template_part('header'); ?>

<?php _e('create an Account', 'appthemes'); ?>

        <?php
            echo '
';
            for ($i = 1; $i <= 4; $i++) :
                echo '<li class="';
                if ($step==$i) echo 'current ';
                if (($step-1)==$i) echo 'previous ';
                if ($i<$step) echo 'done';
                echo '">';
                switch ($i) :
                    case 1 : _e('Create account', 'appthemes'); break;
                    case 2 : _e('Enter Profile Details', 'appthemes'); break;
                    case 3 : _e('Preview/Profile Options', 'appthemes'); break;
                    case 4 : _e('Confirm', 'appthemes'); break;
                endswitch;
                echo '
';
            endfor;
            echo '

';

            // show the success message usually because a password has been emailed to new user
            if (isset($message) && !empty($message)) echo '
'.$message.'
';

            jr_show_errors( $errors );

            switch ($step) :

                case 1 :
                    jr_before_step_one(); // do_action hook
                    ?>

<?php _e('You must login or create an account in order to post a job — this will enable you to view, remove, or relist your listing in the future.', 'appthemes'); ?>

                        <?php jr_register_form( get_permalink($submitID), 'job_lister' ); ?>

                        <?php jr_login_form( get_permalink($submitID), get_permalink($submitID) ); ?>

                    <?php
                    jr_after_step_one(); // do_action hook
                    break;
                case 2 :
                    jr_before_step_two(); // do_action hook
                    jr_submit_job_form(); //*****jr_submit_user_registration_form();
                    jr_after_step_two(); // do_action hook
                    break;
                case 3 :
                    jr_before_step_three(); // do_action hook
                    jr_preview_job_form();  //*****jr_preview_user_registration_form();
                    jr_after_step_three(); // do_action hook
                    break;
                case 4 :
                    jr_before_step_four(); // do_action hook
                    jr_confirm_job_form();  //*****jr_confirm_user_registration_form();
                    jr_after_step_four(); // do_action hook
                    break;

            endswitch;
        ?>

 <?php if (get_option('jr_show_sidebar')!=='no') get_sidebar('submit'); ?>

 <?php

   get_template_part('footer');

  }

here what i have in  my includes/forms/register/ register-process.php

register-process.php
please note that i have modified this at the bottom :
// redirect
                                wp_redirect($success_redirect);
wp_redirect($success_redirect);// redirect user to dashbord when registred
exit();

to this code :

$redirect_to = !empty( $_POST['redirect_to'] ) ? $_POST['redirect_to'] : '?action=register&step=2';
                            wp_safe_redirect( $redirect_to );

                            exit;

in order to add &step=2 to the url, i think you can add similar code to the other form to redirect and show correct step in url after ?action=register

i didn't finish yet hacking the code to suit it to my needs but what i suggested is a beginin and others can help modifyin or presenting better.
hope its helps you :)

A: The easiest method of doing this would be to use the Gravity Forms plugin, it costs money, but it's well worth the investment, and quickly pays for itself in saved development time


text:
Q: Ansible: variable registered on one server gets forgotten when running on another remote server My tasks:
  - name: Init a new swarm with default parameters
    docker_swarm:
      state: present
      advertise_addr: "{{ manager_ip }}:2377"
    register: rezult
    when: "ansible_default_ipv4.address == '{{ manager_ip }}'"

  - debug:
      msg: '{{ rezult.swarm_facts.JoinTokens.Worker }}'
    when: "ansible_default_ipv4.address == '{{ manager_ip }}'"

Now this works fine, but if I want to run it on another server (!=) with:
  - debug:
      msg: '{{ rezult.swarm_facts.JoinTokens.Worker }}'
    when: "ansible_default_ipv4.address != '{{ manager_ip }}'"

I get:
FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'swarm_facts'\n\nThe error appears to be in '/home/ansible/docker-ansible/docker.yml': line 42, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n  - debug:\n    ^ here\n"}

I do not get it. It is like ansible forgets the value of registered variable called "rezult" when running on another server even though I registered it and it should have a fixed value.

A: Yes, variables are always host specific, including ones declared by set_fact:; if you want that variable to appear on all your hosts, you'll have to have a special "propagation" action that reaches "over" to the one host that does have the value, and assign it to all the hosts:
- set_fact:
    hello: I am a manager
  when: ansible_default_ipv4.address == '{{ manager_ip }}'
- set_fact:
    hello: '{{ hostvars[manager_host].hello }}'
  when: hello is not defined
  vars:
     # you may have access to some less convoluted logic than this
     # to know which inventory_hostname ran that "set_fact:"
     manager_host: '{{ hostvars | dict2items
        | selectattr("value.ansible_default_ipv4.address", "eq", manager_ip)
        | map(attribute="key") | first }}'


text:
Q: Hidden files on NAS system (Synology DiskStation DS413j). How to recover space? We have had our Synology replaced with a newer, larger capacity one. I would like to re-purpose this one : Synology DiskStation DS413j for another purpose.  However, I cant see to clean the backups off from it. I dont see anything. Is there some setting that might hide it?

*

*Volume 1 (Normal) - 6.25 TB

*Used Capacity: 5.22 TB

*Available Capacity" 1.03 TB

storage pool 1 = 4 drives
It has no shared folders.  Yet, I cant see anything on the volume/drives. What am i missing? How do I recover the space on this DiskStation?
see attached screenshots

A: Did you try to just reformat the drives?  Re-create the volume?
Or perhaps all you need to do is empty the recycle bin?  If the option is turned on and you simply deleted files, they will end up there.  Look for stuff in the #recycle folder of you shares, or follow this link to clear it out via the DSM.

A: Never did figure out where the files were, but I figured out how to do a factory reset and it erased all data and Now after setting up from scratch, i have all the capacity back.

A: if you ssh into the NAS you will see a bunch of hidden files and directories starting with @ sign.
Some of these are to support cloudstation (worst backup solution ever) etc.


text:
Q: How do I make my search bar search for my other pages Made a search bar for my website but I don't actually know how to make it search for other pages.
Here is the code:

            <input class="search-txt" type="text" name="input" placeholder="Search..">

A: The code to perform search is not implemented in the code you had pasted. Ideally the below line in your HTML markup

should point to a search action with parameters to search picked from the input field you had specified as below, probably through a javascript.
<input class="search-txt" type="text" name="input" placeholder="Search..">

Or else, the input field itself should be within a form, whose action should point to a server method/function that takes what is typed in the input field either through a GET or POST, based on form action method you would have specified like something below.
<form id='searchbox' action='search' method='GET'>
       <input class="search-txt" type="text" name="input" placeholder="Search..">
        <button class="search-btn" type='submit'>

        </button>
</form>

If you do not have any such thing in place, you can try adding a Google custom search to your page, which is described in the below article.This can be used if your search is only in the page content and not anything in your database.
Wikihow - How to add a google search bar

A: Just adding a search bar to the website is not going to do it.
You will have to send the search query for some server side processing (Example PHP) and that script will be the one doing the searching and outputting search results dynamically based on the search query.
Therefore you need:

*

*Form data to be submitted.

*Server side handling/processing of that submitted data.

*Take user to the output page of that search results.


text:
Q: ios swift datepicker done button, wrong date with interval I have set up a date picker as input view of a textfield. Date picker has a minimum date and interval minute of 15. Now it gives proper date on changing the spin in value changed delegate. But if I don't spin the picker and tap done button with default first selected, it gives only current date. I would expect it to give me the date which is displayed by default in picker. Here is the code:
class ViewController: UIViewController {

    @IBOutlet weak var timeField: UITextField!

    var datePicker:UIDatePicker!

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func CallPicker(sender: UITextField) {

        let datePickerView:UIDatePicker = UIDatePicker()
        datePickerView.datePickerMode = UIDatePickerMode.DateAndTime
        datePickerView.minuteInterval = 15
        datePickerView.minimumDate = NSDate()
        datePicker = datePickerView

        let toolBar = UIToolbar()
        toolBar.sizeToFit()
        let spaceButton = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
        let doneButton = UIBarButtonItem(title: "Done", style: .Plain, target: self, action: "doneTapped")
        toolBar.setItems([spaceButton, doneButton], animated: false)
        toolBar.userInteractionEnabled = true

        sender.inputView = datePickerView
        sender.inputAccessoryView = toolBar
        datePickerView.addTarget(self, action: Selector("datePickerValueChanged:"), forControlEvents: UIControlEvents.ValueChanged)
    }

    func doneTapped() {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateStyle = .MediumStyle
        dateFormatter.timeStyle = .MediumStyle
        timeField.text = dateFormatter.stringFromDate(datePicker.date)
        timeField.resignFirstResponder()
    }

    func datePickerValueChanged(sender: UIDatePicker) {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateStyle = .MediumStyle
        dateFormatter.timeStyle = .MediumStyle
        timeField.text = dateFormatter.stringFromDate(sender.date)
    }

}

Scenario: suppose its 8:42 now. Date picker will show 8:30 as first entry but when I tap on done button, it will only give current time which is 8:42. However it works well if I roll spin and get back to first entry.

A: Try using following code when date is selected
    let userDateFormate = NSDateFormatter()
    userDateFormate.dateFormat = "MMMM dd, yyyy"
    let dateString = userDateFormate.stringFromDate(date)

    dateFormate.dateFormat = "MMMM dd, yyyy"
    dateFormate.timeZone = NSTimeZone.init(forSecondsFromGMT: 0)
    let dateValue = dateFormate.dateFromString(dateString)

A: I also face the same issue and what I do for the workaround is to set a later time to my UIDatePicker with the help of Calender.current.dateComponents
func patchTime(){
    var components = Calendar.current.dateComponents([.hour, .minute], from: self.timePicker.date);
    components.hour = (components.hour ?? 0) + 1
    components.minute = 0

    let calendar = Calendar.current
    let date = calendar.date(from: components)
    self.timePicker.date = date!;

}

Currently I am using for timepicker but if needed for date also, the pattern will be same

A: you just need to set the date property of this datePicker from current date to custom and then it will work.


text:
Q: Free Products - representation of 1 by empty word is unique I am studying Free Products of Groups from Munkres' Topology book. The definition of free products is:
Let $G$ group, $\{G_a\}_{a \in J}$ family of groups that generates $G$ and $G_a \cap G_b$ consists of the idenity element alone whenever $a \neq b$.
We say that $G$ is the free product of $G_a$, if for each $x \in G$ there is only one reduced word that represents $x$.
After that it says and proves, that it suffices to know that the representation of $1$ by the empty word is unique.
What does exactly the latter means?
Isn't the empty word unique and doesn't always represents $1$?
By the previous argument it looks to me like the condition of the uniqueness of the reduced word to be redundant.

A: Munkres defines a word as finite sequence $s = (x_1,\dots,x_n)$ of elements $x_i \in G_{\alpha_i}$  and says that such a sequence represents $x \in G$ if $x = \prod_{i=1}^n x_i = x_1\dots x_n$. As an adhoc notation let us write $\prod s = \prod_{i=1}^n x_i$.  Then he defines two reduction operations shortening sequences $s$ of length $n$ to sequences $s'$ of length $n-1$ such that $\prod s = \prod s'$. One of these operations is the omission of $x_i$ if $x_i = 1$.
At the beginning he does not say anything about $n$ and thus one might think that we only deal with sequences of length $n \ge 1$. However, after he defined the reduction operations he explicitly makes the convention that the sequence $\emptyset$ of length $0$ (i.e. the empty word) is regarded as a reduced word which represents $1$. This is common practice; for example in elementary calculus one frequently defines the empty sum as $0$ and the empty product as $1$ (i.e. as the neutral elements with respect to additon and multiplication).
Let us come to your question. The empty word always represents $1$. But there may be other reduced words $s$ representing $1$ and then the representation of $1$ as a reduced word is not unique. This is what Munkres means. But admittedly the formulation "the representation of $1$ by the empty word is unique" may be misleading. He should better have said "the representation of $1$ by a reduced word is unique, and this is the representation by the empty word".
Here is an example. Let $G = \mathbb Z \oplus \mathbb Z$. Let $G_1$ be the subgroup of all pairs $(a,0)$ and $G_2$ the subgroup of all pairs $(0,b)$. Their intersection only contains the additive identity element $(0,0)$. Clearly each element $(a,b)$ of $G$ is represented by the word $((a,0),(0,b))$. But all words $((a,0),(0,b),(-a,0),(0,-b))$ with $a,b \ne 0$ are reduced and represent $(0,0)$.

A: Let me reword that sufficient condition in order to make it more explicit:

... it suffices to know that the representation of $1$ by the empty word is the unique representation of $1$ by a reduced word.


text:
Q: Pass a select tag value to a route url on laravel framework How do I do this in laravel while passing it to a route
<select id="selectUser" name="selectUser" class="form-control text-md-right" onchange="alert(Getfield());">
  <option value="" disabled selected>Please Select Service</option>
  @foreach($ListServices as $lst)
     <option value="{{$lst->ServiceName}}">{{ $lst->ServiceName }}</option>
  @endforeach
</select>

<?php

if(isset(!empty($_GET['selectUser'])) {
       Route + $_GET['selectUser']
}
?>

This is without a form method just using link route while passing the value of select tag?

A: why not pass it as query string
{{ route(Route::currentRouteName(),array('somevariable' => 'value'))

If you want to redirect back to self with option select value use javascript class and jquery do something like
('#selectuser').change(function (e) {
    $.redirect('{{ route(Route::currentRouteName()}}',
    {
        user: e.val(),
    });
});

and then use $request->get('user') to access.


text:
Q: Google apps script target text between two tags I am trying to write a script to do something relatively straight forward with Google app script (google documents scripts - i think they are a version of javascript if that helps):
I want to search from the tag: {start} up to the tag {end} and then make any pre-defined keywords bold. Then, once completed I want to delete the tags {start} and {end}.
For the following:
{start}this, is, some text, in here{end}
this is, some text, in here

I wrote (mish-mashed) this code together, it searches paragraphs for words and makes them bold if they are found - that works, however my main issue is that it will also then replace words outside of the block (start->end) with bold when found; I do not want the script to affect other blocks or paragraphs in the document(s).
function emboldenText(docID, textToHighlight) {

  var doc  = DocumentApp.openById(docID);

  var paras = doc.getParagraphs();
  var textLocation = {};
  var i;
  var startLocation;

  for (i=0; i<paras.length; ++i) {

    textLocation = paras[i].findText(textToHighlight);
    if (textLocation != null && textLocation.getStartOffset() != -1) {

      Logger.log("hit, making text bold at: "+ textLocation.getStartOffset());

      /* Make it bold! */
      textLocation.getElement().setBold(textLocation.getStartOffset(),textLocation.getEndOffsetInclusive(), true);

    }
  }
}

I simply call that function for each word I'd like highlighted (emboldened):
i.e:
emboldenText(fileId,'Mustard');
    emboldenText(fileId,'Egg');
    emboldenText(fileId,'Wheat');

My thoughts on where to go from here are: Search the document for the word {start} and then some how grab it's element position, also grab the end position and then only replace the word with bold if it's in that section - how to actually achieve that is evading me at the moment.
Any help much appreciated!

A: This should do it:
function BoldBetweenTags() {
  var startTag = '{start}';
  var endTag = '{end}'
  var body = DocumentApp.getActiveDocument().getBody();
  var para = body.getParagraphs();
  for(var i in para){
    var from = para[i].findText(startTag);
    var to =  para[i].findText(endTag,from);
    if((to != null && from != null) && ((to.getStartOffset()-1) - (from.getStartOffset()+startTag.length) > 0) ){
      para[i].editAsText().setBold(from.getStartOffset()+startTag.length, to.getStartOffset()-1, true);
    }
  }
}


text:
Q: SDK Location not found in android studio I have just imported my eclipse project in android studio. it keeps my saying that
Error:SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable.

I have seen some tutorials of editing local.properties files but it didnt work. here is my project.properties file:
sdk.dir=E:\\Mod Eclipse\\adt-bundle-windows-x86_64-20130219\\sdk

Actual directory of my folder is :
E:\Mod Eclipse\adt-bundle-windows-x86_64-20130219\sdk

A: You can add a local.properties with to set the sdk.dir like sdk.dir=/Users/roofe/Library/Android/sdk.
But please note below, which is very important,
add the local.properties to the uppermost path of the project. Here the uppermost have some difference with root path of a project.
For example in the below project, I just use the ijkplayer-example, but this module also used other module with different cpu architecture.
If I only add local.properties to ijkplayer-example will not work. Here will get sdk  location issue for other module.
While I can add the local.properties to the ijkplayer directory, then when I try to open the ijkplayer-example project, there will auto create a local.properties for ijkplayer-example, and everything works well.

A: A quick note about this if trying to run a Facebook sample and this error pops up, make sure you select the build.gradle file in the root of Facebook sdk, for all the samples when 'opening an existing project'. I got this error when I tried to open the gradle for just the Scrumptious sample from the 3.22 SDK

A: In my case, it was a fresh install with checkout from github.

*

*Just close the checkout window.

*Create a new project (not from git, just a fresh one).

*exit the project.

*checkout whatever you like

Its just the fastest way that I found.

A: If you are sure that you have assigned correct SDK path in project settings,
and you can see it in local.properties as well, but still getting this error then there are chances that you are missing something in you project.
I was getting the same error after looking in to my project I found settings.gradle was missing.

and then add following script to your apps build.gradle

You will not face this error any more. It worked for me may be gradle set up was the blocking issue

A: My problem was:

*

*I cloned a project from github

*I clicked open existing Android Studio project

*I chose the path of the inner sample app instead of the containing folder.

So what you should do is:

*

*close the project.

*click open existing Android Studio project

*select the parent folder instead of the sample app.

A: You should also change it on Project Structure.

*

*Close the current project and you'll see pop up with dialog which will then proceed to Configure option.
Configure -> Project Defaults -> Project Structure -> SDKs on left column -> Android SDK Home Path -> give the exact path as you did on local.properties and select Valid Target.
There you go.

A: The simplest solution sometimes is just do the File -> Invalidate Cache / Restart.
If it does not help then go for the more complicated stuff, as suggested in other answers

A: So I had the same issue, and none of the answers given previously helped me. What I did was check for new API updates (in my case, I updated to API level 23) and the problem was fixed.

A: Sync project with Gradle files, It will modify the project's local.properties file.

A: In Android Studio, I just clicked on File and then Choose Project Structure or Ctrl-Alt-Shift+S. This'll clearly show you the Android SDK location and an input box where you can browse to the correct one if it is not correct.

A: I add just local.properties file where my project is located. In local.properties:
sdk.dir=C\:\\Users\\dglig\\AppData\\Local\\Android\\Sdk

such kind of path is there which is our Sdk path.
So just create local.properties file manually and inside this just copy the Sdk file location.

A: Probably local.properties file missing.
Copy a local.properties from an existing file and add it to your current project. That worked for me.

A: I installed the SDK again (from here for example :
https://www.mediafire.com/file/azbsqg6dmg7z7np/Sdk+tools+for+android+studio.rar/file
& it created the directory & the packages, after installation.
Now I open android studio & everything is normal.

A: Everything posted so far was helpful in an overall learning capacity. However, most of the time, fixing one problem created others. What ended up working for me was completely deleting the GitHub project .zip file and any unzipped files. Then I made sure the correct .zip file was re-downloaded and unzipped. When it came time to open it in Android studio, I noticed there were 2 folders with identical project file names, one being contained in the other. The first (or upper) one is actually the .zip file. Open the other one!


text:
Q: CSS force page to be a minimum of 100% This is driving my crazy and I just cant get it to work how I want (I have tried searching forums but can't find a way to fix my code). I want the layout of my page to be 100% of the window height.
The JSFiddle is here: http://jsfiddle.net/JvPc2/3/embedded/result/ to display the issue
Update: The JSFiddle is here: http://jsfiddle.net/JvPc2/4/embedded/result/ to display the issue
The HTML for one page is as follows:

                    Bringing Them Home

                    Tagline to go here?

                    HomeThe 30Memorial HallResearch Page

                    AboutVirtual TourSchool WorkLinks

                    On this page you will find some relevant links to find out more information:

                    Bringing Them Home site

                    Bringing Them Home site

                    Bringing Them Home site

                    Bringing Them Home site

                    Bringing Them Home site

                    Bringing Them Home site

                    Bringing Them Home site

                    Bringing Them Home site

                    Bringing Them Home site

                    Bringing Them Home site

                    Bringing Them Home site

                    Bringing Them Home site

                    ©Stefan Wright Web Design 2014

                    Contact the webmaster here.

The CSS is below:
html{min-height:100%;position:relative}
body{background-image:url('../images/bg_leather.png');margin:0px;height:100%}
#wrapper{height:100%;width:100%;position:absolute;top:0;bottom:0;left:0;right:0;}
#adminoverlay{z-index:10;width:100%;background:whitesmoke;position:relative;top:0;}
#adminoverlay p{margin:0px}
#headcontainer{width:100%;min-width:697px;height:20%;font-family:'MyUnderwood'}
#headerleft,#headerright{margin-bottom: 0px;text-align: center;background-image: url('../images/bg_content_rep.png');background-size: cover;width:48%;height:50%;min-height:62px;float:left;margin-left:1%}
#headerright h2{line-height: 2em;-webkit-margin-before: 0.80em;-webkit-margin-after: 0.80em;}
#navleft,#navright{width:48%;min-width:320px;height:40%;min-height:50px;margin-left:1%;float:left;font-family:'MyUnderwood';background-image: url('../images/bg_content_rep.png');background-size: cover;}
#navleft a,#navright a{float: left;text-align: center;width: 21%;padding-left:2%;padding-right:2%;max-width: 131px;height:100%;font-size: 19px;color: black;}
#splitbar{background-image: url('../images/bg_content_top.png');background-size: cover;background-position: center top;height: 10%;width:100%;float: left;min-width:320px}
#maincontainer{width:100%;min-width:697px;min-height:68%;min-height:250px;clear:both}
#maincontentleft,#maincontentright{width:42%;min-width:320px;height:100%;margin-left: 1%;padding-left: 3%;padding-right:3%;float: left;font-size: 14px;font-family: 'MyUnderwood';background-image: url('../images/bg_content_rep.png');background-repeat: repeat-y;background-position: left top;background-size: 100%;}
#footercontainer{width:100%;min-width:697px;height:10%;min-height:50px;clear:both}
#footerleft,#footerright{width:42%;min-width:320px;height:90%;margin-left:1%;float:left;font-family:'MyUnderwood';background-image: url('../images/bg_content_rep.png');background-size: cover;padding-left:3%;padding-right: 3%;}

Edit: Removed the site URL's and included the JSFiddle.

A: Lazy solution
Not to loose your precious time i would suggest to go for a JS solution, which would be simply fetch parent's height and substract all containers except content.
Other solutions

*

*Consider changing the element which holds the background

*Use flex boxing model (when targeting newest browsers)

*When you don't care about keeping exact footer and header heights you could go for percentage height for all elements.

A: After some more tinkering I got this working by moving the maincontentleft and maincontentright divs out of a container div. Thanks for helping out


text:
Q: ABAP method call within a for-loop Pretty new to ABAP. I've got a class "Truck" ("vrachtwagen") which has a table attribute it_pakket (packages in the truck). I've written a method to write the contents of this table to the screen (DisplayLading). I want to do this for each truck, so I call this method in a for-loop. The program runs without errors, but the output doesn't show up on the screen.
REPORT ZPR412_OO_OEF1.

CLASS CPakket DEFINITION.
    PUBLIC SECTION.
      DATA: Id TYPE I READ-ONLY,
            aantal TYPE I,
            bestemmeling TYPE STRING.
      METHODS: SetID IMPORTING ID TYPE I.
ENDCLASS.

CLASS CPakket IMPLEMENTATION.
  METHOD SetID.
    me->Id = ID.
  ENDMETHOD.
ENDCLASS.

CLASS CVrachtwagen DEFINITION.
  PUBLIC SECTION.
    DATA: Id TYPE I READ-ONLY.
    METHODS: SetID IMPORTING ID TYPE I,
             LaadPakket IMPORTING Pakket TYPE REF TO CPakket,
             LosPakket IMPORTING Pakket TYPE REF TO CPakket,
             DisplayLading.
  PRIVATE SECTION.
    DATA: it_pakket TYPE STANDARD TABLE OF REF TO CPakket,
          pakket TYPE REF TO CPakket.
ENDCLASS.

CLASS CVrachtwagen IMPLEMENTATION.
  METHOD SetID.
    me->Id = ID.
  ENDMETHOD.
  METHOD LaadPakket.
    APPEND Pakket TO it_pakket.
  ENDMETHOD.
  METHOD LosPakket.
  ENDMETHOD.
  METHOD DisplayLading.
    LOOP AT me->it_pakket into pakket.
      WRITE:/ pakket->Id, pakket->aantal, pakket->bestemmeling.
    ENDLOOP.
  ENDMETHOD.
ENDCLASS.

DATA:
  vrachtwagen TYPE REF TO CVrachtwagen,
  it_vrachtwagens TYPE STANDARD TABLE OF REF TO CVrachtwagen,
  pakket TYPE REF TO CPakket,
  it_pakket TYPE STANDARD TABLE OF REF TO CPakket,
  s TYPE string.

start-of-selection.
DO 2 TIMES.
  CREATE OBJECT vrachtwagen.
  CALL METHOD vrachtwagen->SetId EXPORTING Id = sy-index.
  APPEND vrachtwagen TO it_vrachtwagens.
ENDDO.

CREATE OBJECT pakket.
CALL METHOD pakket->SetId EXPORTING Id = 1.
pakket->aantal = 5.
pakket->bestemmeling = 'Bob'.
APPEND pakket TO it_pakket.

CREATE OBJECT pakket.
CALL METHOD pakket->SetId EXPORTING Id = 2.
pakket->aantal = 2.
pakket->bestemmeling = 'Jan'.
APPEND pakket TO it_pakket.

CREATE OBJECT pakket.
CALL METHOD pakket->SetId EXPORTING Id = 3.
pakket->aantal = 1.
pakket->bestemmeling = 'Piet'.
APPEND pakket TO it_pakket.

LOOP AT it_vrachtwagens INTO vrachtwagen.
  CASE sy-index.
    WHEN 1.
      loop at it_pakket into pakket.
        if sy-index lt 3.
          vrachtwagen->LaadPakket( pakket ).
        endif.
      endloop.
    WHEN 2.
      read table it_pakket into pakket index 3.
      vrachtwagen->LaadPakket( pakket ).
  ENDCASE.
ENDLOOP.
LOOP AT it_vrachtwagens INTO vrachtwagen.
  vrachtwagen->DisplayLading( ).
ENDLOOP.

I've written code to fill the trucks with packages and added the trucks to the internal table over which I loop. My guess is that the write method in the CVrachtwagen class implementation can't write to the screen, because the program is still running the loop?

A: The system variable SY-INDEX is not set inside a LOOP AT loop, you need to replace it with SY-TABIX inside your loops over it_vrachtwagens and it_pakket.
From SAP's documentation (not too helpful):
sy-index - Loop index. In DO and WHILE loops, contains the number of previous loop passes, including the current pass.
sy-tabix - Row number in the table index of an internal table. Contains the last row accessed using a primary or secondary table index. Is set to 0 when accessed using a hash algorithm.


text:
Q: Why does the cached entities suddenly jump? I have :
var c = cboCustomer.SelectedItem as Customer;
var t = cboTrailer.SelectedItem as Trailer;
using (var db = new CAPSContainer())
{
   db.Attach(c); --> Tracker has now 1 entity
   db.Attach(t); --> Tracker has now 2 entities
   c.Trailers.Remove(t); --> Tracker has now 29! entities loaded
   db.DeleteObject(t);
   db.SaveChanges();
}

I am trying to understand how this loading / caching is working because I am having some other issues related to it, any ideas why the cached amount suddenly jumps?
I am using EF 5.0.

A: Your default configuration probably had LazyLoadingEnabled set.  So child lists won't get loaded until they are accessed, see this article for a more detailed explanation:
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/reading-related-data-with-the-entity-framework-in-an-asp-net-mvc-application
By the way, if you just want to remove one without loading the lot, then you can use DeleteObject as Boomer said.


text:
Q: SFML Memory leaks So I started playing around with the SFML library and I get lots of memory leaks just by creating a simple program that draws a window. Any solution to this?
int main()
{

sf::RenderWindow window(sf::VideoMode(SCREEN_X, SCREEN_Y), APP_TITLE);

while (window.isOpen())
{
    sf::Event event;
    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::MouseButtonPressed)
        {
            if (event.mouseButton.button == sf::Mouse::Left)
            {

            }
        }
        if (event.type == sf::Event::Closed)
            window.close();
    }

    window.clear(sf::Color::Black);

    window.display();
}

_CrtDumpMemoryLeaks();
return 0;
}

A: Okay, so it turns out that CRT falsely reports memory leaks. Actually there are no leaks whatsoever. I installed a plugin for VS and now everything is fine.


text:
Q: cross domain jsonp callback is undefined I must be missing something here, because this seems like a very simple problem, but I've tried most of the solutions and haven't had any luck.
I am simply trying to create an ajax request cross-domain and store the result into a javascrip variable.  I'm getting valid javascript, my callback is being fired, but my success never is.
I've tried:
 Setting jsonp: false with jsonpCallback: myCallback (as it stands now, below)
 Remobing jsonp: false and jsonpCallback: mcCallback and setting the url url?callback=?
 A few other things... point being, I'm doing something wrong and it's pretty basic
For the example below, I do get the alert('hello') but then I get parsererror in the console (coming from the error function)
Edit to add how it is now after reading a comment.  Same issue, though.  Sucess is not called
    $.ajax({
        url: 'http://localhost/faqservice/questions',
        type: 'GET',
        dataType: 'jsonp',
        error: function (x, t, r) { alert(x + t + r); },
        success: function (data) {
            alert('success');
        }
    });

How the question was originally
    $(document).ready(function () {
        $.ajax({
            type: "GET",
            url: "http://localhost/faqservice/questions",
            dataType: 'jsonp',
            jsonp: false,
            jsonpCallback: myCallback,
            error: function (httpReq, status, exception) {
                console.log(status);
            },
            success: function(data) {
                alert('success');
            }
        });
    });

    myCallback = function (data) {
        alert('hello');
    }

A: As the notes said, your server must respond like
 'myCallback({"some":"data"})'
not just the raw json:
 '{"some":"data"}'
jsonp is a bit strange, it's requested by inserting a script tag, cuz script tags CAN transfer cross-domain.  Your server must supply JS code that'll do something when the response comes.
jQuery does most of the browser side for you.  When it sends the request, it'll add on an argument like callback=jQuery17209078477467410266_1426708743857
Then it sets up a function of that name that'll take care of the response when it comes.
Your server must take this string and construct the code like this:
 jQuery17209078477467410266_1426708743857({"data": "the"});
If you just pass the json, it'll execute like a big expression and be forgotten.


text:
Q: download python library to create deployment package I am trying to download a python library (requests) into a folder in order to create a deployment package.
from terminal (I am on mac)
i use
pip3 install requests -t .

I get the following error.
Collecting requests
  Using cached https://files.pythonhosted.org/packages/51/bd/23c926cd341ea6b7dd0b2a00aba99ae0f828be89d72b2190f27c11d4b7fb/requests-2.22.0-py2.py3-none-any.whl
Collecting chardet<3.1.0,>=3.0.2 (from requests)
  Using cached https://files.pythonhosted.org/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-any.whl
Collecting urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 (from requests)
  Using cached https://files.pythonhosted.org/packages/e0/da/55f51ea951e1b7c63a579c09dd7db825bb730ec1fe9c0180fc77bfb31448/urllib3-1.25.6-py2.py3-none-any.whl
Collecting idna<2.9,>=2.5 (from requests)
  Using cached https://files.pythonhosted.org/packages/14/2c/cd551d81dbe15200be1cf41cd03869a46fe7226e7450af7a6545bfc474c9/idna-2.8-py2.py3-none-any.wh
➜  AWS apt-get install python3-pip
zsh: command not found: apt-get
➜  AWS ln -s /Library/Frameworks/Python.framework/Versions/3.6/bin/pip /usr/bin/pip3
ln: /usr/bin/pip3: Operation not permitted
➜  AWS ln -s /Library/Frameworks/Python.framework/Versions/3.6/bin/pip /usr/local/bin/pip3
ln: /usr/local/bin/pip3: File exists
➜  AWS pip3 install requests -t .
Collecting requests
  Using cached https://files.pythonhosted.org/packages/51/bd/23c926cd341ea6b7dd0b2a00aba99ae0f828be89d72b2190f27c11d4b7fb/requests-2.22.0-py2.py3-none
-any.whl
Collecting chardet<3.1.0,>=3.0.2 (from requests)
  Using cached https://files.pythonhosted.org/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-a
ny.whl
Collecting idna<2.9,>=2.5 (from requests)
  Using cached https://files.pythonhosted.org/packages/14/2c/cd551d81dbe15200be1cf41cd03869a46fe7226e7450af7a6545bfc474c9/idna-2.8-py2.py3-none-any.wh
l
Collecting urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 (from requests)
  Using cached https://files.pythonhosted.org/packages/e0/da/55f51ea951e1b7c63a579c09dd7db825bb730ec1fe9c0180fc77bfb31448/urllib3-1.25.6-py2.py3-none-
any.whl
Collecting certifi>=2017.4.17 (from requests)
  Using cached https://files.pythonhosted.org/packages/18/b0/8146a4f8dd402f60744fa380bc73ca47303cccf8b9190fd16a827281eac2/certifi-2019.9.11-py2.py3-no
ne-any.whl
Installing collected packages: chardet, idna, urllib3, certifi, requests
Exception:
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/pip/_internal/cli/base_command.py", line 179, in main
    status = self.run(options, args)
  File "/usr/local/lib/python3.7/site-packages/pip/_internal/commands/install.py", line 393, in run
    use_user_site=options.use_user_site,
  File "/usr/local/lib/python3.7/site-packages/pip/_internal/req/__init__.py", line 57, in install_given_reqs
    **kwargs
  File "/usr/local/lib/python3.7/site-packages/pip/_internal/req/req_install.py", line 913, in install
    use_user_site=use_user_site, pycompile=pycompile,
  File "/usr/local/lib/python3.7/site-packages/pip/_internal/req/req_install.py", line 445, in move_wheel_files
    warn_script_location=warn_script_location,
  File "/usr/local/lib/python3.7/site-packages/pip/_internal/wheel.py", line 313, in move_wheel_files
    prefix=prefix,
  File "/usr/local/lib/python3.7/site-packages/pip/_internal/locations.py", line 180, in distutils_scheme
    i.finalize_options()
  File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/distutils/command/install.py", line 248, in finalize_options
    "must supply either home or prefix/exec-prefix -- not both")
distutils.errors.DistutilsOptionError: must supply either home or prefix/exec-prefix -- not both

any idea how to fix this?
the requests packages in already installed and I have made a test script that uses it and it works.
I just would like to understand what's wrong.

A: I solved by running
pip3 install -U pip
and then re-runnig
pip3 install requests -t .


text:
Q: How to create a fake Symfony\Component\HttpFoundation\File\UploadedFile in a PHPUnit test? I'm unable to create a fake UploadedFile in my PHPUnit test.
I found a solution for Laravel but I couldn't find one for Symfony.
This is my code:
$path = '/tmp';
$originalName = 'MANA-BULL 12-2018 Ali.pdf';
$mimeType = "application/pdf";
$size = 4455;
$error = 0;
$fileRaw = new UploadedFile(
  $path,
  $originalName,
  $mimeType,
  $size,
  $error,
  $test = false
);

return $fileRaw;

I get the following exception:

Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException:
  The file "/tmp" does not exist

How can I solve this issue?

A: In your tests directory, create a folder called fixtures. In that folder, place your test PDF file. From your test, you can now create an upload file like so:
<?php

namespace App\Tests\Functional;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class UploadTest extends WebTestCase
{
    public function test_uploadFile()
    {
        $uploadedFile = new UploadedFile(
            __DIR__.'../fixtures/foo.pdf',
            'foo.pdf'
        );
    }
}


text:
Q: What is a "Field" associated with a class and how does it differ from methods in Python? Both field and method take arguments in same way and have similar syntax for calling them. How does one differ from the other?
from tkinter import *

# Window() is a blueprint for making object in tkinter library.
main_window = Window()

# minsize() is shown as "Field" with yellow color and capital "f" in PyCharm.
window.minsize(width=400, height=100)

# mainloop() is a method and shown with magenta-Ish color and "m" in PyCharm.
main_window.mainloop()

A: Fields and method parameters are not the same at all.
If they are named similarly, that's only a coincidence, not a requirement.
Here's an example of different ways Python allows you to use method parameters.
class Foo:
    def __init__(self):
        self.field = None

    def method(self, parameter=None):
        self.field = parameter
        print(self.field)

f = Foo()
f.method()  # default parameter
f.method(1)  # implied parameter
f.method(parameter=2)  # named parameter

Class constructors are methods can be used to initialize fields
Regarding Pycharm, a function-field could be defined as
def __init__(self):
    def __minsize(width, height):
        ...
    self.minsize = __minsize

Whereas a method would be defined like bar above


text:
Q: Как вставит строку внутрь другой строки при нахождении определенного символа Есть символ С и строки S1, S2. Перед каждым входжением символа С в строку S1 нужно вставить строку S2.
Как это сделать?

A: Вот демонстрационная программа, которая показывает, как это можно сделать.
#include <iostream>
#include <string>

int main()
{
    std::string s( "one two three" );
    std::string t( "," );
    char c = ' ';

    std::cout << s << std::endl;

    for ( std::string::size_type pos = 0;
          ( pos = s.find( c, pos ) ) != std::string::npos;
          pos += t.size() + sizeof( c ) )
    {
        s.insert( pos, t );
    }

    std::cout << s << std::endl;

    return 0;
}

Вывод программы на консоль
one two three
one, two, three

Можно предварительно подсчитать, сколько в строке встречается символ в c, чтобы заранее зарезервировать память в строке s, а затем выполнить указанный в программе цикл.
Например
#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    std::string s( "one two three" );
    std::string t( "," );
    char c = ' ';

    std::cout << s << std::endl;

    auto n = std::count( s.begin(), s.end(), c );

    s.reserve( s.size() + n * t.size() );

    for ( std::string::size_type pos = 0;
          ( pos = s.find( c, pos ) ) != std::string::npos;
          pos += t.size() + sizeof( c ) )
    {
        s.insert( pos, t );
    }

    std::cout << s << std::endl;

    return 0;
}


text:
Q: Problemas com Migration Estou desenvolvendo uma aplicação utilizando arquitetura DDD. Em minha camada de Infra, tenho os meus modelos de dados, todos baseados em Code First. Estou tentando utilizar o MySql como banco de dados. Já instalei tudo que foi necessário (EF, MySqlConnector) e outros mais que são necessários.
Acontece que quando tento aplicar o Migration obtenho o erro:
Caso 1: Quando aplico o Add-Migration
PM> Add-Migration
cmdlet Add-Migration na posição de comando 1 do pipeline
Forneça valores para os seguintes parâmetros:
Name:

O que deve ser fornecido para esse "Name":
Caso 2: Quando forneço o nome do banco de dados que consta na ConnectionString
OBS: Forneço tal valor, porque não sei o que deve ser passado conforme explicado acima.
The specified framework version '2.0' could not be parsed
The specified framework 'Microsoft.NETCore.App', version '2.0' was not found.
  - Check application dependencies and target a framework version installed at:
      C:\Program Files\dotnet\
  - Installing .NET Core prerequisites might help resolve this problem:
      http://go.microsoft.com/fwlink/?LinkID=798306&clcid=0x409
  - The .NET Core framework and SDK can be installed from:
      https://aka.ms/dotnet-download
  - The following versions are installed:
      1.0.11 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
      1.0.12 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
      1.1.8 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
      1.1.9 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
      2.0.3 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
      2.0.7 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
      2.0.9 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
      2.1.2 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
      2.1.4 at [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]

Como resolver tal problema?
Desde já agradeço a atenção.

A: No uso de migration tu terá de se habituar com alguns comandos:
Add-Migration <nome-da-migration>

Para voltar a uma versão específica:
update-database –target "<nome-da-migration>" -Script -Force

Atualizar a sua base com as alterações do domínio:
update-database -script

O parâmetro -Script: serve para te devolver o script a ser executado em banco, caso não coloque o parâmetro, será submetido automaticamente em banco.
O parâmetro -Force é necessário quando houver algum tipo de conflito ou modificação de estrutura que com script simples não seja possível de se modificar. Com o uso do -Force ele cria um script da quebra do possível relacionamento. Essa ação, caso você esteja usando um banco de produção, irá apagar os dados contidos no banco. Sempre bom ter cautela no uso do Migrations e aconselho a não usar em base de produção. Somente para desenvolvimento.
Existem outros parâmetros ainda como o -Verbose: Serve apenas para exibir um log do que o migrations está executando durante a execução do update-database.


text:
Q: How do I select tables in a SQL Server that have a field Shape that is an INT type? I've got some tables where Shape is a geometry, and some where its an int. I want to find those with int type Shape fields and fix them. I'm a bit of a dummy with T-SQL.

A: You can use information_schema.columns to find columns (fields) that have a data type of int and a name of Shape. For Example:
SELECT
    TABLE_NAME,
    COLUMN_NAME,
    DATA_TYPE
FROM information_schema.columns
WHERE
(DATA_TYPE = 'int') AND
(COLUMN_NAME LIKE '%Shape%')


text:
Q: Minimum and maximum number of elements in intersection of sets. In a battle 70% of the combatants lost one eye, 80% an ear, 85%  a leg, 75% an arm, x% lost all four limbs.Then

*

*What is the minimum value of x?

*What is the maximum value of x?

*From van diagram I figured that the minimum value of x is 10%. But I am not satisfied with my version of explanation.
`

A: You're right about max, because it's $\min(70\%,75\%,80\%,85\%)=70%$.
For the next question (which you were right as well) I find it easier to explain with numbers, say out of $100$.
The minimum intersection of $70$ and $75$ is $70-(100-75)=70-25=45$
The minimum intersection of $80$ and $85$ is $80-(100-85)=80-15=65$
The minimum intersection of $45$ and $65$ is... (hint: same way as the previous two) $10$.

A: I believe the general algorithm to determine the minimum is as follows (in Python)
def get_min_intersection (slices,total = 100):
    if sum(slices)- (len(slices)-1) * total >= 0:
        return sum(slices)- (len(slices)-1) * total
    else:
        return 0

# The minimum intersection of [70,80,75,85] out of 100 is 10
assert get_min_intersection([70,80,75,85]) == 10

# The minimum intersection of [90,60,80] out of 100 is 10 according to https://youtu.be/GcT4ExbSYRI?t=34
assert get_min_intersection([90,60,80]) == 30

# The minimum intersection of [30,35,32] out of 50 is 0 according to https://youtu.be/GcT4ExbSYRI?t=251
assert get_min_intersection( [30,35,32], 50) == 0

# The minimum intersection of [40,50,60] out of 100 is 0 according to https://www.handakafunda.com/set-theory-maximum-and-minimum-values/
assert(get_min_intersection( [40,50,60]) ==  0)

As @Joao said, the maximum intersection is the minimum of the elements in the set.


text:
Q: Why is the new row not being renamed in MySQL? This is my code
SELECT *,
-- Add the status of the student depending on the CourseCode
(CASE
    WHEN CourseCode = 907 THEN 'Already in the course'
    WHEN CourseCode <> 907 THEN 'Upgraded to the course'
    Else NULL
END AS Status)
FROM ecestudents;

Unfortunately for some reason, it is throwing an error. But if I remove AS Status it is running properly, but I want to rename the new row I am creating using the case statement.

A: "AS status" should be outside the bracket. You don't need the bracket as it is

A: Try removing the brackets and run
SELECT *,
CASE
    WHEN CourseCode = 907 THEN 'Already in the course'
    WHEN CourseCode <> 907 THEN 'Upgraded to the course'
    Else NULL
END AS Status
FROM ecestudents;