text:
Q: Passing array's element values to lowest or highest functions in pine script I am trying to pass dynamic values to lowest and highest built-in functions in pine script from arrays. Below is the code
int[] pArray = array.new_int(0)

pArray is populated with int elements. Here is the code below that works.
fromInd         =   array.min(pArray)
lowest          =   ta.lowest(MACDHist,array.get(pArray,0))
Debug = label.new(bar_index+1, close, 'pArray: ' + str.tostring(pArray) + str.tostring(fromInd))

The output of above code on the chart is
pArray: [2, 15, 40]2

2 is the 0th index value of pArray that is printed outside of the array in the end. However when I change the label to output 'lowest' value (shown below) nothing prints to chart but everything compiles well with no errors or warnings.
Debug = label.new(bar_index+1, close, 'pArray: ' + str.tostring(pArray) + str.tostring(lowest))

The output of 'array.get(id, index)' is series int because pArray is initialized to int. I also typecasted the 'array.get(id, index)' argument by enclosing it with 'int()' but nothing is working for the last line code except when hard coded.
'ta.lowest(source, length)' accepts series int arguments for length and it can also accept dynamic lengths as shown by tradingview https://www.tradingview.com/blog/en/pine-functions-support-dynamic-length-arguments-20554/
What am I doing wrong here? Thanks in advance.
I tried a variation of a solution posted by first user below with code
//@version=5
indicator("Dynamic INT array length", overlay = false, max_bars_back = 5000)

[a, b, hist] = ta.macd(close, 26, 12, 9)

int[] lengths = array.new_int()
int[] nlengths = array.new_int()

for i = 0 to 10
    if hist[i] > 0
        array.unshift(lengths, i)
    else
        array.unshift(nlengths,i)

lowest = ta.lowest(hist, array.get(lengths,0))

plot(lowest)
plot(hist, color = color.red)

debug = label.new(x = bar_index, y = 0, style = label.style_label_left, text = str.tostring(lowest) + "   " + str.tostring(lengths) + "   " + str.tostring(array.get(lengths,0)))
label.delete(debug[1])

and Im getting an error when using 'ta.lowest(hist, array.min(lengths))' where it says
Invalid value of the 'length' argument (0.0) in the "lowest" function. It must be > 0.

I tried all variations of the condition hist[i] > 0 within the for loop but nothing is printing and it has the same error. Let me know if there is an easy fix for this. Thanks.

A: It should be working, at a guess, normally I'd say there must be something going on with how the array is populated, but it doesn't seem to be the case here given the array output. It's unlikely, but possible you've found a bug, or an even possibly an exception that isn't being picked up by the compiler.
//@version=5
indicator("Dynamic INT array length", overlay = false, max_bars_back = 5000)

int[] lengths = array.new_int()

for i = 0 to 10
    array.unshift(lengths, int(math.random(30, 50)))

[a, b, hist] = ta.macd(close, 26, 12, 9)

lowest = ta.lowest(hist, array.min(lengths))

plot(lowest)
plot(hist, color = color.red)

debug = label.new(x = bar_index, y = 0, style = label.style_label_left, text = str.tostring(lowest) + "   " + str.tostring(lengths) + "   " + str.tostring(array.min(lengths)))
label.delete(debug[1])

Follow up answer :
There's actually two things you need to take care of. If you consider when hist has been < 0 for a while (ie at least 10 bars). The first time hist crosses the zero line, your lengths array will only have one value : zero, and it can't be used in ta.lowest(). The second issue you will have is, if hist has been under zero the entire 10 bar window, the lengths array will be empty and array.get(lengths, 0) will give you the out of bounds indexing error.
You'll have to decide how to handle these specific circumstances, but the following of how you could account for it. For example using a length of 5 when the array has only one value of 0 and populating the arrays with na values to avoid the empty array problem.
//@version=5
indicator("Dynamic INT array length", overlay = false, max_bars_back = 5000)

[a, b, hist] = ta.macd(close, 26, 12, 9)

int[] lengths = array.new_int()
int[] nlengths = array.new_int()

for i = 0 to 10
    if hist[i] > 0
        array.unshift(lengths, i)
        array.unshift(nlengths, na)
    else
        array.unshift(nlengths,i)
        array.unshift(lengths, na)

int len = na
if array.get(lengths, 0) > 0
    len := array.get(lengths, 0)
else
    len := 5

lowest = ta.lowest(hist, len)

plot(lowest)
plot(hist, color = color.red)

debug = label.new(x = bar_index, y = 0, style = label.style_label_left, text = str.tostring(lowest) + "   " + str.tostring(lengths) + "   " + str.tostring(array.get(lengths,0)))
label.delete(debug[1])


text:
Q: python :zlib.error: Error -3 while decompressing data: incorrect data check [Emergent!]
when I use pip3 to install scipy, I get this error:
Exception:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 209, in main
    status = self.run(options, args)
  File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 328, in run
    wb.build(autobuilding=True)
  File "/usr/lib/python3/dist-packages/pip/wheel.py", line 748, in build
    self.requirement_set.prepare_files(self.finder)
  File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 360, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 577, in _prepare_file
    session=self.session, hashes=hashes)
  File "/usr/lib/python3/dist-packages/pip/download.py", line 810, in unpack_url
    hashes=hashes
  File "/usr/lib/python3/dist-packages/pip/download.py", line 649, in unpack_http_url
    hashes)
  File "/usr/lib/python3/dist-packages/pip/download.py", line 842, in _download_http_url
    stream=True,
  File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 480, in get
    return self.request('GET', url, **kwargs)
  File "/usr/lib/python3/dist-packages/pip/download.py", line 378, in request
    return super(PipSession, self).request(method, url, *args, **kwargs)
  File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 468, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 576, in send
    r = adapter.send(request, **kwargs)
  File "/usr/share/python-wheels/CacheControl-0.11.5-py2.py3-none-any.whl/cachecontrol/adapter.py", line 36, in send
    cached_response = self.controller.cached_request(request)
  File "/usr/share/python-wheels/CacheControl-0.11.5-py2.py3-none-any.whl/cachecontrol/controller.py", line 102, in cached_request
    resp = self.serializer.loads(request, self.cache.get(cache_url))
  File "/usr/share/python-wheels/CacheControl-0.11.5-py2.py3-none-any.whl/cachecontrol/serialize.py", line 108, in loads
    return getattr(self, "_loads_v{0}".format(ver))(request, data)
  File "/usr/share/python-wheels/CacheControl-0.11.5-py2.py3-none-any.whl/cachecontrol/serialize.py", line 164, in _loads_v2
    cached = json.loads(zlib.decompress(data).decode("utf8"))
zlib.error: Error -3 while decompressing data: incorrect data check

I was use scipy.io.loadmat to load data,but it is also error with ' zlib.error: Error -3 while decompressing data: incorrect data check'.
And I uninstall scipy,and use 'pip3 install scipy' to re-install scipy,but also get this error.
Does somebody help me ?

A: According to this github issue the problem you are facing is due to a bug in the cachecontrol upstream library vendored by pip and not by pip itself. This should be fixed if you upgrade cachecontrol.

redpajama_set_name: RedPajamaStackExchange


text:
Q: windows phone 8 emulator auto shutdown white booting I turn on Emulator to debug app, it show following text (no dialog) and shutdown

i've tried to reinstall SDK 8.0 but it still that error. Anyone can help me?

A: Open Hyper-V Manager and check the Windows Phone Emulator Internal Switch from Virtual Switch Manager. Remove all the emulator switch and start a new instance of the emulator.


text:
Q: WPF Binding between pages / Transfer data between view models I need to transfer data between pages and do "binding" on it.
On the first page i have textbox bound to "Username" property.
Every page has its own viewmodel, after clicking a button in the first page i've done something like this
SecondPageViewModel.Username = this.Username;

In second page i have textblock bound to Username property, but after page changes, the second page show no text.
<TextBlock Text="{Binding Username}" />

The only way i found and works is to in the second page viewmodel in the constructor make a task which updates the username.
Task.Run(async () =>
{
    while(true)
    {
        await Task.Delay(200);
        this.Username = FirstPageViewModel.Username;
    }
});

Is there any other way to do that? By making task here, it isn't always working, sometimes if i change page too fast, it won't show username anyway.
Every viewmodel implements INotifyPropertyChanged + FodyWeaver.

A: Following my comment, here's some simple implementations using events.

*

*A first implementation is FirstPageViewModel is parent of SecondPageViewModel. You can see the event subscription in the SecondPageViewModel constructor.

*A second implementation is FirstPageViewModel is on the same level of SecondPageViewModel. This uses a Mediator between the two ViewModels. It is basically removing the dependency of FirstPageViewModel from SecondPageViewModel

*A third one would be to create your own delegate on FirstPageViewModel for SecondPageViewModel to subscribe on. It's basically the same thing as PropertyChanged, but you can configure what event arguments you are ready to pass.

Here's a demo:
public delegate void UsernameChangedEventHandler(string username);

public class FirstPageViewModel : INotifyPropertyChanged
{
    // 3) Third implementation
    public event UsernameChangedEventHandler UsernameChanged;

    private string _username;
    public string UserName
    {
        get { return _username; }
        set
        {
            _username = value;

            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("UserName"));

            if (UsernameChanged != null)
                UsernameChanged(this.UserName);
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

public class SecondPageViewModel : INotifyPropertyChanged
{

    private string _username;
    public string UserName
    {
        get { return _username; }
        set
        {
            _username = value;

            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("UserName"));
        }
    }

    public SecondPageViewModel()
    {
    }

    public SecondPageViewModel(FirstPageViewModel parent)
    {
        // 1) First implementation
        parent.PropertyChanged += FirstPageViewModel_OnPropertyChanged;

        // 3) Third Implementation
        parent.UsernameChanged += Parent_UsernameChanged;
    }

    private void Parent_UsernameChanged(string username)
    {
        this.UserName = username;
    }

    private void FirstPageViewModel_OnPropertyChanged(object sender, PropertyChangedEventArgs args)
    {
        FirstPageViewModel parent = (FirstPageViewModel) sender;
        if(args.PropertyName.Equals("username", StringComparison.InvariantCultureIgnoreCase))
        {
            this.UserName = parent.UserName;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

public class ParentViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private FirstPageViewModel _firstPageViewModel;
    private SecondPageViewModel _secondPageViewModel;

    public ParentViewModel()
    {
        // 2) Second implementation
        _firstPageViewModel = new FirstPageViewModel();
        _secondPageViewModel = new SecondPageViewModel();

        _firstPageViewModel.PropertyChanged += FirstPageViewModel_PropertyChanged;

        // 3) Third Implementation
        _firstPageViewModel.UsernameChanged += FirstPageViewModel_UsernameChanged;
    }

    private void FirstPageViewModel_UsernameChanged(string username)
    {
        _secondPageViewModel.UserName = username;
    }

    private void FirstPageViewModel_PropertyChanged(object sender, PropertyChangedEventArgs args)
    {
        FirstPageViewModel firstPageViewModel = (FirstPageViewModel)sender;
        if (args.PropertyName.Equals("username", StringComparison.InvariantCultureIgnoreCase))
        {
            _secondPageViewModel.UserName = firstPageViewModel.UserName;
        }
    }
}


text:
Q: loading a responsestream into an XDocument, root element is missing I have read that setting the position of the stream to 0 resolves this, but this fails as the stream "does not support seek operations".
It fails on this:
XDocument doc = XDocument.Load(resp.GetResponseStream());

Reading the stream:
string t = new StreamReader(resp.GetResponseStream(), Encoding.Default).ReadToEnd();

...reveals that my xml could not be any simpler:
<xml version="1.0">
  <ActiveStorms>
  </ActiveStorms>
</xml>

Is this somehow malformed?
Thanks for any help,
Mike

A: XML documents do not end with a </xml> closing tag so delete that.  The initial <xml version="1.0"> should be: <?xml version="1.0"> (note the question mark).
So a valid version would look like:
<?xml version="1.0">
<ActiveStorms>
</ActiveStorms>

A: The right XML declaration is
<?xml version="1.0" encoding="utf-8" ?>

and after that add your root node <ActiveStorms>
so,
<?xml version="1.0" encoding="utf-8" ?>
<ActiveStorms>
</ActiveStorms>


text:
Q: How to switch between branches without bringing along file changes? I'm trying to understand how I'm supposed to work on multiple different features in my project using git branching.  The problem I'm running into now is, I created a branch
git checkout -b my-first-feature
At this point I've changed a controller file in my application.  But, I've realized that I need to make a change in another stop of the project that is unrelated to my-first-feature, so I create another branch.
git checkout -b hotfix-issue-#1105 master
At this point I expected the controller file that was edited under my-first-feature to revert back to the contents of what was in the master branch, but it wasn't.  Did I forget a step? Or am I just doing this incorrectly?

A: Assuming you don't want to discard the changes in progress on your first branch, stash those changes before you switch branches:
git stash save "Stashing changes for later"

Then later you can switch back to that branch and retrieve your (stashed) changes:
git stash pop

http://git-scm.com/book/en/v1/Git-Tools-Stashing


text:
Q: Why is there a discrepancy in the size shown by df and du for a mounted google drive storage account? I am using cp to copy directories from a mounted google drive storage account to disk.
I need to find out the total size of all directories to be copied from google drive to disk to know the amount of disk space needed.
The google drive storage account was mounted using google-drive-ocamlfuse. I ran both df and du commands as shown below.
df shows that the total size of the mounted google drive storage account is 15G and 11G is used. However, du shows that the total size of the .shared folder (which I assume is the "Shared with me" folder in my google drive account) is 93G.
Why is there a discrepancy in the size shown by df and du for a mounted google drive storage account?
And why is the size of the .shared (i.e. "Shared with me") folder much larger than the size of the google drive storage account shown by df and in the browser, when the google drive account contains the "Shared with me" folder?
$ df -h
Filesystem               Size  Used Avail Use% Mounted on
google-drive-ocamlfuse    15G   11G  4.7G  69% /home/user/cloud_storage

$ du -h --max-depth=1 cloud_storage
93G     cloud_storage/.shared
4.0K    cloud_storage/.Trash
98G     cloud_storage

$ du -h --max-depth=1 cloud_storage/.shared/
5G    cloud_storage/.shared/FolderA
1G    cloud_storage/.shared/FolderB
3G    cloud_storage/.shared/FolderC
1G    cloud_storage/.shared/FolderD
1G    cloud_storage/.shared/FolderE
2G    cloud_storage/.shared/FolderF
1G    cloud_storage/.shared/FolderG
20G     cloud_storage/.shared/FolderH
30G     cloud_storage/.shared/FolderI
28G     cloud_storage/.shared/FolderJ
1G     cloud_storage/.shared/FolderK
93G     cloud_storage/.shared/


text:
Q: AFIncrementalStore to sync Core Data with REST API I was wondering if you have ever used AFIncrementalStore to sync between Core Data and a REST API? And if you so, it is a good approach to  use it without the Heroku Core Data Buildpack? I don't like dark magic :P
My Core Data model might not match exactly the REST API.

A: AFIncrementalStore works fine with a simple REST API.
You may have to override the representationForResponse method for a fine match with your models but it should be all that is needed (except from the init part of course)
My advice: make an exact match between the API and your CoreData models and then use categories to generate the data the way you want them.
I'm currently doing an e-commerce app and my API send me products with an expiration_date which is a unix timestamp. I save as it is in CoreData and then I have a category on my NSManagedObject Product methods like hoursRemaining, weeksFromNow and so on for an easier display in the UI.
For the relationships, I'm not use those for automatic fetching with AFIncrementalStore so I can't say much.


text:
Q: Jupyter Notebook looks weird on github I am pushing code from an AWS SageMaker instance to my GitHub. The Jupyter Notebooks are looking very weird on GitHub after I pushed. Example below:

There are these huge spaces at the top and bottom. For each cell it  insert one empty line at the top of each cell and four empty lines at the bottom. This is obviously not the case when I wrote the code in the notebook. Only after I pushed to GitHub. It's make the notebooks look very bad on GitHub.
Has anyone an idea why that is the case and/or has seen this before?

A: I found out about this github issue about Ipython.
The browser version would causes to create empty spaces. https://github.com/ipython/ipython/issues/5612


text:
Q: Working with repos When working with repos (I have github in mind), should we also commit third party libraries? For example, boost and poco compile to 5G with samples. Should we upload all that to github? If not, then how do we keep the libraries in sync with other people?
Sorry about lack of capitalization and grammar. I am on my phone and it is difficult to type.

A: First rule of version control: never commit generated assets to your repository. So you should definitely not commit build products of Boost and Poco to your repository. Whether to include dependencies in your repository as source is really up to you; it kind of depends on your project, how many dependencies you need, how much of the public for your software is likely to have easy access to those dependencies, etc. Packagers and distributions generally prefer that you don't bundle your dependencies, but instead carefully mention them in a README or INSTALL file.
If you want to make it easy to get the dependencies for people who check your code from a VCS, try to use svn externals, git submodules or hg subrepos, making it easy to exclude the dependencies and establish a clear link to the dependency's upstream repository.

A: First, it doesn't matter if you're using Maven or not. It doesn't matter.
Now, that I have that out of the way, I suggest you use a Maven repository manager like Nexus or Artifactory.
What Artifactory and Nexus do is create a network wide repository structure for third party libraries.
You can easily download any artifact in your release repository with the standard wget or curl commands. If you use Ant, you can use Ivy to manage your artifacts. If you use Maven, well, you're all set. That means you can script the download of the required third party libraries right in your build scripts.
A release repository can also be used for your third party libraries. Do you produce a base library that other projects of yours use? You can use the same release and download mechanism to make your compiled objects available to your system.
Checking in your third party libraries in causes the following issues:

*

*The commits are usually done on a project-by-project basis. That means if you have more than one project that depends upon the third party foo library, chances are you'll have foo located in two different places in your repository.

*You will lose information about foo. You won't remember which version of foo it was. I've been a build engineer for java projects for the last decade, and in every project we have some foo.jar from the Foo project, and none of the developers know whether it is verison 1.3, 2.5, or 4.5. We have no idea if the Foo project even supports this older version or if we got the buggy 1.3 and should have upgraded to version 1.4 back in the Hoover administration.

*Binaries take up lots of room in your source repository. Every time you commit a new version, it's even more room. And, what does it get you in return? Not much. You can't diff it to see what was changed in the previous version. Checkouts can take forever with no benefit in return.

*Many source repositories won't allow you to remove obsolete versions of your third party programs. I won't mention any names (cough! Subversion! cough!), but I've seen repositories that are 100 to 200 gigabytes in size, and it's almost nothing but obsolete versions of third party libraries.

By the way, you never mentioned your programming platform. If you are using Ruby, Php, or Perl, you can use their built in repository system (Gem, Pear, and CPAN respectively) and you won't need to worry about configuring release repositories.

A: I like it when those third party libraries are available via git, and I can include them in my project as submodules. I like that a lot. Makes pulling in updates a total piece of cake.
When that's not possible, then yeah, I include their code right in my repo. Ultimately, I'm going to turn my production branch over to my operations people to push to the production server, so it needs to have all the goods needed to run. That may be a different workflow than yours, but that's how mine works.


text:
Q: Call setState method in Constructor Error I want to call method from another class which contains setState. I got some error in page 2like this
This happens when you call setState() on a State object for a widget that hasn't been inserted into the widget tree yet. It is not necessary to call setState() in the constructor, since the state is already assumed to be dirty when it is initially created.

I've read this answer, but I didnt get it on my case. Any Ideas? Thank you
class Page1 extends StatefulWidget {
  @override
  _Page1State createState() => _Page1State();
}
class _Page1State extends State<Page1> {

  @override
  void initState(){
    Page2().method();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
      ),
    );
  }
}
class Page2 extends StatefulWidget {
  method() => createState().methodInPage2();
  @override
  _Page2State createState() => _Page2State();
}
class _Page2State extends State<Page2> {
  Future<List<String>> methodInPage2() async{

//error here
    setState(){
      //setState here,
    }
  }
  @override
  Widget build(BuildContext context) => Container();
}


text:
Q: Manually numbering an equation in Beamer Similar to an old 2011 posting here, I would like to manually tag a particular line of equation with number in Beamer. I tried using \tag{} command but it does not work, putting in \usepackage{amsmath} also does not help. I am working under these environments:
\documentclass{beamer}
\mode {
\usetheme{Ilmenau}
\usecolortheme{beaver}}

And here is a compilable example from my slides:
$x = r \cos \theta \tag{1}$.
Here, ShareLatex ignores \tag{1} but compiles the rest of the equation correctly.
Please advise and thanks for your time.
PS.: I do not have any need to reference the tagged equation later.

A: After a small correction of (first version of) your code:
\documentclass{beamer}

\usetheme{Ilmenau}
\usecolortheme{beaver}

\begin{document}

\begin{equation}
1+1=2
\end{equation}

\begin{equation}
1+1=2 \tag{mytag}
\end{equation}

\end{document}

The source of your problem seems to be inline formula, i.e. between dollar signs, not inside, say, equation environment.


text:
Q: what does a three-up mean in below contents? Print proofing with a three-up: The two sides show the lightest and darkest prints that are within tolerance. The one in the middle is juust right.
I can guess what it means by reading the whole content, but I don't know why it can be expressed in this way, is it a kind of fixed usage?

A: In printing, two-up, four-up etc mean "two (four) pages printed at one time" (nowadays, usually reduced to fit on one page).  I've never met three-up, but the meaning is clear.
The OED doesn't appear to list this meaning of -up, but it does list two-up, one of whose meanings is given as "Two at a time, two together", with a citation relevant to this question, from 1967: "Master output for photo-litho reproduction 'two-up'"


text:
Q: Making a string of 0's and 1's into an int, into a character from that ascii val Here's my procedure:
static void undo_bitstring(std::string& str) {
    for (unsigned i = 0; i < str.length(); i += charbits) {
        int ascii_val = 0;
        for (unsigned j = 0; j < charbits; j++) {
            if (str[i+j] == '1') ascii_val += (int)exp2(charbits-j-1);
        }
        str[i/charbits] = (char)ascii_val;
    }
    str.erase(str.begin()+str.size()/charbits,str.end());
}

where, just so you know,
charbits

was defined by
static const size_t charbits = 8 * sizeof(char);

What is supposed to happen is, for example,
std::string str = "01010111";
undo_bitsring(str);

should change str to
"W"

since
0x2^7 + 1x2^6 + 0x2^5 + 1x2^4 + 0x2^3 + 1x2^2 + 1x2^1 + 1x2^0
= 64 + 16 + 4 + 2 + 1
= 87

and
(int)'W' = 87

And of course this procedure is supposed to work for any string of 0's and 1's with a length that is a multiple of charbits. For instance,
std::string str = "010101110101011101010111";
undo_bitsring(str);

should change str to
"WWW"

On the tests I've run, the output just looks like a bunch of boxes with question marks inside them, indicating some sort of error.
Any ideas?
Am I totally going about this wrong in the first place? This is part of some encryption/decryption algorithm I'm trying to make.

A: Do you know about the >> and << operators.  These operators, when applied to an int will shift the bit 1 position right or left.  It would probably be more reliable than using (int)exp2(charbits-j-1);


text:
Q: Incrementing in foreach loop in SSIS package I want to collect data from a table for the past 3 years and was asked to create a new CSV file for each month data.I started creating a SSIS package for that using for each loop Container(with item enumerator) and I also created some variables like startdate, enddate, folderpath.
In FOREachloop I created data flow task there I want to fetch each months data which satisfies my startdate and Enddate condition and create a new CSV file for each month.
ASK:
I am not able to figure it out where I can increment my startdate and end date values. Please help me with this.

A: Without knowing more detail about your package than the somewhat hard to follow narrative, it is somewhat hard to answer specifically.
Anyway it sounds like you need a loop counter which you can add another variable then use an Execute SQL Task to increment it.  You can then either modify your startdate and enddate by the same Execute SQL Task and/or modify yet another variable for for month and use it in your SELECT statement in your dataflow.
If you post more detail of your package concerning the foreach loop, variables, and dataflow I and others will be able to provide more detail.


text:
Q: Encode and decode text into binary and vice versa I'm trying to convert text into binary and then decode it back to the original text.
When I encode my encoded binary bits are too small. At the decode side I got only the last character of my text string.  My code is given below. Can anyone correct it, if there is any mistake? I want to decode the same text which I encode.
public static String enc(String s) {
///first layer of encoding

        String initializer="11111111";
        int ct=0;
        int a[]=new int[11111111];
        for (int i = 0; i <s.length(); i++){

            a[i]=(int)s.charAt(i);//charAAT retrun value in geven index
            ct++;
        }

        String res ="";
        int bin[] =new int[111];
        int idx=0;
        for(int i1=0; i1 < ct; i1++) {
            int temp =a[i1];
            for(int j = 0; j < ct; j++) bin[j]=0;
            idx = 0;

            while(temp>0) {
                  bin[idx++]=temp%2;
                  temp = temp/2;
            }
            String dig = "";
            String temps;
            for (int j = 0; j < 7; j++) {
                 temps = Integer.toString(bin[j]);

                 dig = dig.concat(temps);

            }
            String rev = "";
            for (int j =dig.length()-1; j>= 0; j--) {
                 char ca = dig.charAt(j);
                 rev = rev.concat(String.valueOf(ca));

            }

            res = rev.concat(rev);

        }
        res = initializer.concat(res);
        return res;
        }
}

When encoded, the output for text hi is 1111111111010011101001
The decode part returns only i as output:
String invalid = "Invalid Code";

        // create the same initial
        // string as in encode class
        //
        String initailizer = "11111111";
        Boolean flag = true;

        // run a loop of size 8
        for (int i = 0; i < 8; i++) {
            // check if the initial value is same
            if (initailizer.charAt(i) != res.charAt(i)) {
                flag = false;
                break;
            }
        }
        String data = "";
        for (int i = 8; i < res.length(); i++) {
            char temp = res.charAt(i);
            data = data.concat(String.valueOf(temp));
        }
        int asc[][] = new int[11101][8];
        int idx = -1;
        int idx2 = 0;
        for (int i = 0; i < data.length(); i++) {
            if (i%7==0) {
                idx++;
                idx2 =0;
                char temp = data.charAt(i);
                asc[idx][idx2] = temp-'0';
                idx2++;

            } else
                {
                 char temp = data.charAt(i);
                 asc[idx][idx2] = temp -'0';
                 idx2++;

            }
        }

        int num[] = new int[11111];
        int nidx = 0;
        int temp = 0;
        int ct = 0;
        for (int i = 0; i < idx; i++) {
            ct = 0;
            temp = 0;
            for (int j=6; j>=0;j--) {

                int temp1 = (int) pow(2, ct);
                temp += (asc[i][j]*temp1);
                ct++;
            }
            num[nidx++] = temp;
        }
        String rv = "";
        char ch;
        for (int i =0; i<nidx; i++) {
            ch = (char) num[i];
            rv = rv.concat(String.valueOf(ch));

        }
        if (data.length()%7 == 0 && flag == true) {
            //return rv;

        }
        return rv;

    }


text:
Q: whysiyg save in php file I am currently developing somthing like a CMS, but without using any database. A really big problem for me is how can you change (and later format content via tinymce (or similar) ) and then save it into a php file?
My configuration file for each page looks like this:
<?php
$title = 'Title of the page';

$contenttitle = <<<HTML
Something like a short summary, displayed at the top
HTML;

$content = <<

Now, I want to be able to open a script in the browser where I can select the file I want to edit and see text boxes with content of $title, $contenttitle and $content.
So, in fact we open a file, look for these 3 variables, display their content and change them (overwrite the file).
How can this be solved?

A: This is just an example approach that may help you:

*

*Write a php/html file which will print out a form for you:
<form method="post">
<input type="text" name="title" value=""/>
<input type="text" name="contenttitle" value=""/>
<textarea name="content">">
<input type="submit" value="save"/>
</form>

*Handle your form in the php file:
if (!empty($_POST)) {
$result = array(
'title' => htmlspecialchars($_POST['title']),
'contenttitle' => htmlspecialchars($_POST['contenttitle']),
'content' => htmlspecialchars($_POST['content'])
);
// save it to a file by serialiing
$filename = uniqid().'.text'; // you may play around with file names, rewrite this line so it will suit your convention - you may use counter of the files
file_put_content($filename, serialize($result));
}

*To retrieve file and print it use something like this:
$file = $_GET['name'];
$file = str_replace(array('/', '.', '\'), '', $file); // for security reasons
$content = file_get_contents($file.'.text'); // note this is an example extension
$data = unserialize($content);
echo '
'.$data['title'].'
';
echo '
'.$data['contenttitle'].'
';
echo '
'.$data['content'].'
';


text:
Q: OutOfMemoryError when loading ~200mb file from assets fodler Android fails to allocate enough memory when I run application and want to load
java.lang.OutOfMemoryError: Failed to allocate a 202728962 byte allocation with 14422192 free bytes and 171MB until OOM

Also I previously described an error here: https://github.com/tensorflow/tensorflow/issues/9343
I guess I have enough free memory (usually 1.0-1.5 gb are free):

And so is it just java android limitation? Can I somehow solve it with java? Or is it possible only with NDK?
full error code:
04-21 09:40:52.731 31597-31597/org.tensorflow.demo E/AndroidRuntime: FATAL EXCEPTION: main
    Process: org.tensorflow.demo, PID: 31597
    java.lang.OutOfMemoryError: Failed to allocate a 202728962 byte allocation with 14422192 free bytes and 171MB until OOM
        at org.tensorflow.contrib.android.TensorFlowInferenceInterface.loadGraph(TensorFlowInferenceInterface.java:377)
        at org.tensorflow.contrib.android.TensorFlowInferenceInterface.<init>(TensorFlowInferenceInterface.java:96)
        at org.tensorflow.demo.TensorFlowYoloDetector.create(TensorFlowYoloDetector.java:111)
        at org.tensorflow.demo.DetectorActivity.onPreviewSizeChosen(DetectorActivity.java:131)
        at org.tensorflow.demo.CameraActivity$1.onPreviewSizeChosen(CameraActivity.java:159)
        at org.tensorflow.demo.CameraConnectionFragment.setUpCameraOutputs(CameraConnectionFragment.java:421)
        at org.tensorflow.demo.CameraConnectionFragment.openCamera(CameraConnectionFragment.java:428)
        at org.tensorflow.demo.CameraConnectionFragment.access$000(CameraConnectionFragment.java:64)
        at org.tensorflow.demo.CameraConnectionFragment$1.onSurfaceTextureAvailable(CameraConnectionFragment.java:95)
        at android.view.TextureView.getHardwareLayer(TextureView.java:368)
        at android.view.View.updateDisplayListIfDirty(View.java:15175)
        at android.view.View.draw(View.java:15971)
        at android.view.ViewGroup.drawChild(ViewGroup.java:3610)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3400)
        at android.view.View.updateDisplayListIfDirty(View.java:15193)
        at android.view.View.draw(View.java:15971)
        at android.view.ViewGroup.drawChild(ViewGroup.java:3610)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3400)
        at android.view.View.draw(View.java:16204)
        at android.view.View.updateDisplayListIfDirty(View.java:15198)
        at android.view.View.draw(View.java:15971)
        at android.view.ViewGroup.drawChild(ViewGroup.java:3610)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3400)
        at android.view.View.updateDisplayListIfDirty(View.java:15193)
        at android.view.View.draw(View.java:15971)
        at android.view.ViewGroup.drawChild(ViewGroup.java:3610)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3400)
        at android.view.View.updateDisplayListIfDirty(View.java:15193)
        at android.view.View.draw(View.java:15971)
        at android.view.ViewGroup.drawChild(ViewGroup.java:3610)
        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3400)
        at android.view.View.draw(View.java:16204)
        at com.android.internal.policy.PhoneWindow$DecorView.draw(PhoneWindow.java:2690)
        at android.view.View.updateDisplayListIfDirty(View.java:15198)
        at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:282)
        at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:288)
        at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:323)
        at android.view.ViewRootImpl.draw(ViewRootImpl.java:2642)
        at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2461)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2094)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1134)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6045)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:860)
        at android.view.Choreographer.doCallbacks(Choreographer.java:672)
        at android.view.Choreographer.doFrame(Choreographer.java:608)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:846)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5441)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
04-21 09:40:52.740 1501-2367/? E/ActivityManager: Invalid thumbnail dimensions: 0x0

loadGraph method of TensorFlowInferenceInterface class:
private void loadGraph(InputStream var1, Graph var2) throws IOException {
        long var3 = System.currentTimeMillis();
        Trace.beginSection("initializeTensorFlow");
        Trace.beginSection("readGraphDef");
        byte[] var5 = new byte[var1.available()];
        int var6 = var1.read(var5);
        if(var6 != var5.length) {
            throw new IOException("read error: read only " + var6 + " of the graph, expected to read " + var5.length);
        } else {
            Trace.endSection();
            Trace.beginSection("importGraphDef");

            try {
                var2.importGraphDef(var5);
            } catch (IllegalArgumentException var9) {
                throw new IOException("Not a valid TensorFlow Graph serialization: " + var9.getMessage());
            }

            Trace.endSection();
            Trace.endSection();
            long var7 = System.currentTimeMillis();
            Log.i("TensorFlowInferenceInterface", "Model load took " + (var7 - var3) + "ms, TensorFlow version: " + TensorFlow.version());
        }
    }

p.s. demo app link: github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/android
Also I have been offered to try native codepath for loading files: graphsgithub.com/tensorflow/tensorflow/issues/9343#issuecomment-295959477
but I'm not that good with C++/NDK (I just don't work with it)
So there is .cc file available for loading files. I would be grateful if someone helped me to integrate it to TensorFlow example Android project.
But I still hope there is solution without NDK, because is 200mb really such big size for Android 2016-2017 devices?

A:
I guess I have enough free memory (usually 1.0-1.5 gb are free)

That is for the device. It is not for your app.

And so is it just java android limitation?

It is a an Android runtime limitation. You have a heap limit, and your heap is likely to be fragmented.

Can I somehow solve it with java?

Probably not. You can use android:largeHeap to request a larger-than-average heap, but:

*

*That may be no bigger than what you have now, on low-end devices (e.g., Android One)

*The large heap may not be over 200MB

*Even if the large heap is over 200MB, you may not have a single contiguous block of free heap space that is 200MB

*Your process will be terminated rapidly when it moves into the background, if you are consuming lots of memory

Or is it possible only with NDK?

I have no idea if TensorFlow works with the NDK, as I haven't used TensorFlow. You can allocate system RAM via the NDK. Whether you can allocate 200MB of system RAM is dependent upon the amount of system RAM on the device.

because is 200mb really such big size for Android 2016-2017 devices?

200MB, as in individual block of contiguous memory, is a very big size for Android 2016-2017 devices. The age of the device has little to do with its available system RAM. There are plenty of devices manufactured today with 1GB or less system RAM installed, let alone what is free after the OS processes are running. Android One devices may ship with 512MB of system RAM, for example.


text:
Q: How to read row wise column value using javascript I have to validate a table column using javascript.But I am not able to get row wise column value.I am generating this table using java script function like add row and add column. I have to submit data to insert into database .Before submission I have to check quantity and perunit price should be numeric value.
          But I am not able to apply appropriate javascript API to get particular row wise column value.
please check this image
I am posting the code for what i did

                                        Select
                                        Sl.no
                                        Description of Services/Goods
                                        Quantity
                                        Price/Unit
                                        CST %
                                        VAT5.5%
                                        VAT14.5%
                                        ServiceTax%

                        <bgcolor ="red"/>
                        <input type="button" value="Add row"  name="add" onClick="addRow()"/>
                        <input type="button" value="Delete selected rows" name="delete_all" onClick="deleteSelectedRows()" />
                        <input type="button" value="Delete all rows" name="delete" onClick="deleteAllRows()" />

                            <input type="submit" value="Save" onclick="generate1()" />
                            <input type="submit" value="View PO" onclick="generate()"/>

                    </form>

Help me as soon as possible.


text:
Q: NHibernate -- duplicate results when using collection cache I am getting very strange behavior from NHibernate when using the second level cache with multiple layers of bi-directonal parent-child(-grandchild) one-to-many relationships:
int id;

using(var session = sessionFactory.OpenSession())
{
    var parent = new Parent();
    var child1 = parent.AddChild();
    child1.AddGrandChild();
    var child2 = parent.AddChild();
    child2.AddGrandChild();
    session.Save(parent);
    session.Flush(); // force id generation
    id = parent.Id;
}

using(var session = sessionFactory.OpenSession())
{
    var parent = session.Get<Parent>(id);
    parent.Children.Should().HaveCount(2); // but is actually 3; second child duplicated
}

The second child, which has two grandchildren, gets duplicated in the collection, but with the same object id (ReferenceEquals() is true). When I disable caching for the Parent.Children collection, or set the fetching strategy to Join, the problem goes away. Any ideas how to find out what is happening here?
Entities:
class Parent
{
    public virtual int Id { get; protected set; }
    public virtual List<Child> children = new List<Child>();
    public virtual IEnumerable<Child> Children
    {
        get { return children.ToList(); }
    }

    public virtual Child AddChild()
    {
        var child = new Child(this);
        this.children.Add(child);
        return child;
    }
}

class Child
{
    public Child(Parent parent)
    {
        this.Parent = parent;
    }

    public virtual int Id { get; protected set; }
    public virtual List<GrandChild> grandChildren = new List<GrandChild>();
    public virtual IEnumerable<GrandChild> GrandChildren
    {
        get { return grandChildren.ToList(); }
    }

    public virtual Parent Parent { get; protected set; }

    public virtual GrandChild AddGrandChild()
    {
        var grandChild = new GrandChild(this);
        this.grandChildren.Add(grandChild);
        return grandChild;
    }

}

class GrandChild
{
    public virtual int Id { get; protected set; }
    public virtual Child Parent { get; protected set; }

    public GrandChild(Child parent)
    {
        this.Parent = parent;
    }

}

Mappings:
public class ParentMap : ClassMap<Parent>
{
    public ParentMap()
    {
        Id(p => p.Id).GeneratedBy.Identity();
        HasMany(p => p.Children)
            .Access.CamelCaseField()
            .Inverse()
            .Cascade.AllDeleteOrphan()
            .Cache.ReadWrite();
        Cache.ReadWrite();
    }
}

public class ChildMap : ClassMap<Child>
{
    public ChildMap()
    {
        Id(c => c.Id).GeneratedBy.Identity();
        HasMany(c => c.GrandChildren)
            .Access.CamelCaseField()
            .Inverse()
            .Cascade.AllDeleteOrphan()
            .Cache.ReadWrite();
        References(c => c.Parent);
        Cache.ReadWrite();
    }
}

public class GrandChildMap : ClassMap<GrandChild>
{
    public GrandChildMap()
    {
        Id(c => c.Id).GeneratedBy.Identity();
        References(c => c.Parent);
        Cache.ReadWrite();
    }
}

[EDIT]
I worked around this issue by not enabling the cache for the child collections. Since I did it in the first place in order to avoid N+1 select issues with fetch join queries on children of cached entities, I did the following instead:
    public ChildMap()
    {
       // ...
        HasMany(c => c.GrandChildren) // removed Cache.ReadWrite() here
            /* ... */;

        // added IncludeAll() to make sure lazily fetched collections get cached
        Cache.ReadWrite().IncludeAll();
    }

I still don't understand what's going on here though, so any insight into this matter would still be welcome :-).

A: Have you tried using transactions instead of seassion flushing? Like
using(var session = sessionFactory.OpenSession())
using(var transaction = session.BeginTransaction())
{
    var parent = new Parent();
    [...]
    parent.Save();
    transaction.Commit();
    id = parent.Id;
}

Maybe that helps. I once had a similar problem that I could solve with using transactions.


text:
Q: TAP 9.21.2 Driver - An error occurred installing the tap device I have Windows 8.1 64-bit and I tried to install Betternet, but it gave me an error when trying to install the TAP driver, so I tried to install the TAP driver by itself and it gave me the same error. I even tried disabling driver signatures and it still gave me the same error. I also tried installing the driver in Device Manager itself using the INF file but it didn't work. Any idea why this is happening?

A: Same problem ODYS wintab 10 windows 10 32 bit with Kaspersky internet security.
I paused protection but didn't help. I then removed all parts of Kaspersky and TAP installation worked. Kaspersky had added it's own Network Adaptor, Security Data Escort Adaptor, I suspect this was the problem. Removing all parts of Kaspersky removed this adaptor.


text:
Q: How to take multiple photos before dismissing camera intent? I am trying to take multiple photos using the default device camera application launched through an intent (MediaStore.ACTION_IMAGE_CAPTURE). With the devices I am testing with, the camera launches, takes a picture, asks for confirmation, then returns to my activity where I process the result.
I've considered using broadcast receiver callbacks or a content observer; however, I cannot find a way to launch the camera and keep it active until the user is finished. If possible, I wish to avoid developing a custom camera application.
The reason I must do this is because users commonly need to take multiple photos in succession, and on some devices the camera start-up time is upwards of 5 seconds, and the users using the software take 10 - 30 photos consecutively; not only that, but they need control over various camera parameters.
Is there a way to launch the camera intent and only return to my activity once the user exits the camera application?

A: I discovered through the SDK documentation that there's an alternative intent action for the device camera that launches the camera in still image mode and does not exit until the user is finished with the activity:
Intent intent = new Intent(
    MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
this.startActivity(intent);

Coupled with a ContentObserver this was exactly what I needed to accomplish.


text:
Q: SQL Error Msg 8120 Fix I'm having some troubles figuring out where my error is here. This is the question:
Write a SELECT statement that returns the following columns
a. ShipmentOrderDate
b. Clients Email Address
c. Column that calculates the Total Order called OrderTotal
d. A Column that uses the Rank() function to return a column named OrderTotalRank that
ranks the Order Total in Desc Order.
e. A column that uses the DenseRank() function to return a column called DenseRank that
ranks the Order Total in Desc Order.

And this is what I have coded:
SELECT ShipmentOrderDate, EmailAddress,
    SUM(sh.ShipItemPrice * sh.Quantity) AS OrderTotalRank,
    RANK() OVER (ORDER BY SUM(sh.ShipItemPrice * sh.Quantity) DESC) AS OrderTotalRank,
    DENSE_RANK() OVER (ORDER BY SUM(sh.ShipItemPrice * sh.Quantity) DESC) AS DenseRank
FROM Clients AS c JOIN Shipments AS s
    ON c.ClientID = s.ClientID
    JOIN ShipItems AS sh
    ON s.ShipmentID = sh.ShipmentID

When I run the code I get this error:

Column 'Shipments.ShipmentOrderDate' is invalid in the select list
  because it is not contained in either an aggregate function or the
  GROUP BY clause.

A: You need a GROUP BY because you have aggregation functions in the SELECT.  These are separate from the window functions that you are also using:
SELECT ShipmentOrderDate, EmailAddress,
       SUM(sh.ShipItemPrice * sh.Quantity) AS OrderTotalRank,
       RANK() OVER (ORDER BY SUM(sh.ShipItemPrice * sh.Quantity) DESC) AS OrderTotalRank,
       DENSE_RANK() OVER (ORDER BY SUM(sh.ShipItemPrice * sh.Quantity) DESC) AS DenseRank
FROM Clients c JOIN
     Shipments s
     ON c.ClientID = s.ClientID JOIN
     ShipItems sh
     ON s.ShipmentID = sh.ShipmentID
GROUP BY ShipmentOrderDate, EmailAddress;


text:
Q: GET variable is &string(1) => "1" I have a URL formatted like this:
https://chipperyman.com/commander/codes/check.php?type=check&group=w&cpu=63_char_string&version=27&group=1

However, when I use var_dump($_GET);, the w variable is set to &string(1) => 1. This is the full array:
array(4) { ["type"]=> string(5) "check" ["group"]=> &string(1) "1" ["cpu"]=> string(63) "63_char_string" ["version"]=> string(2) "27" }

Why is $_GET['group'] not outputting correctly? When I try to echo it or use it in anything else (.=, etc) it is not treated as a w.

A: group=1 overrides group=w since it comes last and you can't have 2 variables with the same name.
It doesn't seem like you want this, but it is possible to have a group array using:
group[]=w&group[]=1


text:
Q: How to recover a modified file in Linux I wanted to make a copy of my file and I generally use
cat file1> file2

This time, I typed mistakenly
cat file1> file1

Because of which the the contents of my original file are lost. Is there any way to recover it?

A: No, there is no practical* way to recover this file.
*In principle, that actual data are still located on the storage medium, but locating and recovering these data (before some other data is written over all or part of the file) is practically impossible.

A: It is not practical, unless the data is worth a lot, and you stop the machine immediately, take it to an expert, pay them lots of money, and get lucky.
For the future.
What you need is a revision control system. It won't help this time, but will in the future.
A revision control system, keeps a history of your files. Here is an example session.
hg init
hg add file1
hg commit -m "add initial file1"
change file1
hg commit -m "add/change …"
cat file1> file1
hg revert file1

You can even go back farther.
hg update -r 1 #goes to initial version

svn is an easy one for beginners, and still powerful. Mercurial (hg), has more features, so a bit harder to learn. svn is also better for some document types (un-mergable: Office documents).


text:
Q: Docker daemon can't import tar with duplicate files I've been following this tutorial to create a docker image from a buildroot environment:  https://blog.docker.com/2013/06/create-light-weight-docker-containers-buildroot/
Basically, the steps are:

*

*Create the rootfs.tar as you would any other x86_64 buildroot environment

*Create a filesystem overlay for the files:
(a) /etc/resolv.conf and /sbin/init by touching
(b) /lib/x86_64-linux-gnu/libpthread.so.0, /lib/x86_64-linux-gnu/libc.so.6, and /lib64/ld-linux-x86-64.so.2 by cping from the local filesystem

*tar r the files (iow, append) to rootfs.tar to create fixup.tar

*docker import - tag < fixup.tar
However, when I attempt to import this, docker returns:
Error response from daemon: Untar re-exec error: duplicates of file paths not supported: output:

I presume this is because tar r appends rather than replaces files, so tar has multiple indexes for the same file and this causes docker to be confused.
I looked around, but I couldn't find a newer version of this tutorial.
How does one go about correcting this so that I can create a docker image from a buildroot environment?


text:
Q: Selenium: How to find which element to click in a custom jquery plugin generated select box I am trying to automate a click on the multiple select dropdown in this example:
http://davidwalsh.name/dw-content/jquery-chosen.php
I am sending the click event to the li element with the class "active-result" (after clicking on the element that says "Select Frameworks...").
The issue is that the li element doesn't have the onclick handler, so the option is not added to the list.  How can I find the element that actually has the onclick handler in order to perform the action?

A: Found out by searching the code that the element didn't have an onclick handler, it actually was listening for a mouseup event.  So I modified my test to use:
selenium.mouseup().


text:
Q: How to create a ServiceMonitor for prometheus-operator? Recently, prometheus-operator has been promoted to stable helm chart (https://github.com/helm/charts/tree/master/stable/prometheus-operator).
I'd like to understand how to add a custom application to monitoring by prometheus-operator in a k8s cluster. An example for say gitlab runner which by default provides metrics on 9252 would be appreciated (https://docs.gitlab.com/runner/monitoring/#configuration-of-the-metrics-http-server).
I have a rudimentary yaml that obviously doesn't work but also not provides any feedback on what isn't working:
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: gitlab-monitor
  # Change this to the namespace the Prometheus instance is running in
  namespace: default
  labels:
    app: gitlab-runner-gitlab-runner
    release: prometheus
spec:
  selector:
    matchLabels:
      app: gitlab-runner-gitlab-runner
  namespaceSelector:
    # matchNames:
    # - default
    any: true
  endpoints:
  - port: http-metrics
    interval: 15s

This is the prometheus configuration:
> kubectl get prometheus -o yaml

...
serviceMonitorNamespaceSelector: {}
serviceMonitorSelector:
  matchLabels:
    release: prometheus
...

So the selectors should match. By "not working" I mean that the endpoints do not appear in the prometheus UI.

A: Thanks to Peter who showed me that it idea in principle wasn't entirely incorrect I've found the missing link. As a servicemonitor does monitor services (haha), I missed the part of creating a service which isn't part of the gitlab helm chart. Finally this yaml did the trick for me and the metrics appear in Prometheus:
# Service targeting gitlab instances
apiVersion: v1
kind: Service
metadata:
  name: gitlab-metrics
  labels:
    app: gitlab-runner-gitlab-runner
spec:
  ports:
  - name: metrics # expose metrics port
    port: 9252 # defined in gitlab chart
    targetPort: metrics
    protocol: TCP
  selector:
    app: gitlab-runner-gitlab-runner # target gitlab pods
---
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: gitlab-metrics-servicemonitor
  # Change this to the namespace the Prometheus instance is running in
  # namespace: default
  labels:
    app: gitlab-runner-gitlab-runner
    release: prometheus
spec:
  selector:
    matchLabels:
      app: gitlab-runner-gitlab-runner # target gitlab service
  endpoints:
  - port: metrics
    interval: 15s

Nice to know: the metrics targetPort is defined in the gitlab runner chart.

A: I know this question is already answered. But I had a similar problem when Prometheus deployed in Kubernetes with Helm's stable/prometheus-operator chart couldn't find any active targets for my ServiceMonitor.
It turned out that my Service exposed a port that I didn't explicitly named:
  - protocol: TCP
    port: 8080
    targetPort: uwsgi

I could use it in Ingress by targeting uwsgi port. But it seems that ServiceMonitor needs an explicitly named port in Service even if it has the same name as its own tagetPort:
  - name: uwsgi
    protocol: TCP
    port: 8080
    targetPort: uwsgi

I have written a blog post about this problem here

A: This image perfectly shows the connection between Prometheus,ServiceMonitors and Services

If any of the matches are not correct, targets won't show up.
Read more: https://github.com/prometheus-operator/prometheus-operator/blob/main/Documentation/troubleshooting.md#troubleshooting-servicemonitor-changes

A: The above solutions are working fine till now.
The Release Label is important. Without this, Prom cannot add the app metrics to its target list.
Make sure you add the correct Release Label by checking in the ServiceMonitor of Prometheus itself. Also make sure to add the release Label to the Service and Deployment file too, in the metadata & Specs section.
If you encounter a situation where Prometheus is showing the Target but not the endpoints, take a look at this: https://github.com/prometheus-operator/prometheus-operator/issues/3053


text:
Q: How to show different modal using Javascript with multiple button depending on the data body html code:
note: that id is to differentiate the button click
 foreach($threads as $t) { ?>
 <button id="myBtn<?php echo $ids;?>" Open Modal</button>
 <? } ?>

This is the modal code how can apply fetch data in here modal?:

                            ×

Modal Header

Some text in the Modal Body

Modal Footer

This is the Javascript:

How can I manage modal in different value, if I'm fetching data from the database?


text:
Q: How to intercept packet on TCP layer in kernel to analyze data? I intend to find certain packet data in the kernel and intercept it (either drop certain packets or redirect them). A natural way is to somehow catch all packets, inspect their data and drop/redirect certain packets.
I have tried to intercept them directly in the kernel code (here, at the point to copy the data into user space) but the data that is pushed by the server without requests cannot be accessed there.
Another choice could be netfilter hooks like this post. However, such hook is below TCP layer and it seems that reordering and packet losing is not dealt with yet.
So I'm wondering whether there are any elegant solutions to catch packet and operate on them upon TCP layer?
Thanks!

A: If you want to receive only specific stuff and drop not matching stuff, could you open a raw/tcp socket with a BFP filter attached to it ?
Ex - https://www.kernel.org/doc/Documentation/networking/filter.txt


text:
Q: Dompdf stream() Not Rendering Properly and Returning Random Characters Laravel 8 I am generating a pdf file and am trying to preview it using stream() as well as attach it to an email.
When I try to stream() the pdf using the code:
function previewPDF(Request $request) {
       $pdfData = $this->getPDFData($request);
       $domainData = $this->getDomainData($request);
       $hourSumData = $this->getHourSumData($request);
       $userData = Auth::user();

       $pdf = PDF::loadView('trackerPDF', ['pdfData' => $pdfData, 'domainData' => $domainData, 'hourSumData' => $hourSumData, 'userData' => $userData]);

       return $pdf->stream("mypdf.pdf");
   }

I get the following:

However, it seems that the pdf should be generating correctly as I am able to generate and attach the pdf to an email with no issues using this:
function pdf(Request $request) {

        $messages = [
            'recipientname.required' => "The Recipient's Name is required field is required.",
            'recipientemail.required' => "The Recipient's Email is required field is required.",
            'recipientemail.email' => "The Recipient's Email must be a valid email address.",
        ];

        Validator::make($request->all(), [
            'recipientemail' => ['required','email'],
            'recipientname' => ['required'],
        ], $messages)->validate();

        $pdfData = $this->getPDFData($request);
        $domainData = $this->getDomainData($request);
        $hourSumData = $this->getHourSumData($request);
        $userData = Auth::user();

        $pdf = PDF::loadView('trackerPDF', ['pdfData' => $pdfData, 'domainData' => $domainData, 'hourSumData' => $hourSumData, 'userData' => $userData]);

        /*Emailing stuff*/
        $data["title"] = "Professional Development From ". (string)Auth::user()->name;
        $data["body"] = (string)$request->emailmessage;
        $data["recipientname"] = (string)$request->recipientname;
        $data["toaddress"] = (string)$request->recipientemail;
        $data["ccaddress"] = (string)Auth::user()->email;
        $data["fromname"] = (string)Auth::user()->name;
        $data["credentials"] = str_replace(array("[", "]", "\"", "\\"), "", (string)Auth::user()->designation);

        if ( $request->sendtoself) {
            Mail::send('emailtemplates.trackeremail', $data, function($message)use($data, $pdf) {
                $message->to($data["toaddress"])
                        ->cc($data["ccaddress"])
                        ->subject($data["title"])
                        ->attachData($pdf->output(), "Professional Development Tracker.pdf");
            });
        } else {
            Mail::send('emailtemplates.trackeremail', $data, function($message)use($data, $pdf) {
                $message->to($data["toaddress"])
                        ->subject($data["title"])
                        ->attachData($pdf->output(), "Professional Development Tracker.pdf");
            });
        }

        return redirect()->route('tracker')
                    ->with('message', 'Email Sent Successfully.');
    }

I am using Jetstream with Interia.js & Vue.js.
Here is  my route:
Route::middleware(['auth:sanctum', 'verified'])->post('tracker/preview-pdf',
[DynamicPDFController::class, 'previewPDF']);

And how I am posting the form in the Vue page:
previewPDF() {
      this.$inertia.post("/tracker/preview-pdf", this.form);
    },

All of the data is loaded the exact same way. I have searched but cannot figure out what I am doing wrong, any help or direction would be appreciated.

A: Don't use inertia routing for this purpose, use  tag.
In TrackerController;
public function pdf($id){
  //Using domPdf
  $data = []; //get data using $id
  $pdf = App::make('dompdf.wrapper');
  $pdf->loadView('print_view_file', compact('data''));
  return $pdf->stream();
};

Now in Page.vue use;
 Print

This will open new tab and stream the pdf file.


text:
Q: Overwriting and Pushing a Git Branch In merging my changes against an upstream master, I frequently find myself doing the following:
git checkout somefeature
git checkout -b integration
git rebase master # resolving conflicts along the way
git checkout somefeature
git merge integration # or rebase, doesn't matter in this example

I'll often find that merging the integration branch back into my feature branch fails do to some conflicts. The first question I have is, "why is this happening if my integration branch is a descendent of somefeature and I've already resolved conflicts against the upstream master?"
If you're wondering why I'm using an integration branch to begin with, it's to prevent polluting my current branch with a half-failed merge.
My current workaround is to do this:
git checkout integration
git branch -f somefeature # overwrite the branch

The problem now is that I can't push my changes back to a remote branch:
git push origin somefeature
! [rejected]        somefeature -> somefeature (non-fast forward)

So now I have to remove the remote branch and re-push my changes. This can't be the optimal way to do this, so I'm wondering, "what's the best way to overwrite a branch and push the changes to a remote branch?"

A: You could use git merge -s recursive -Xtheirs, which will auto-resolve conflicts in favor of the integration branch.  However, that still does a merge and may not play well with files moving around and such.
However, since your branch is pushed, you have a reason to want to keep its history around.  To get the ideal behavior you want, you could use the 'ours' strategy in the integration branch.
git checkout somefeature
git checkout -b integration
git rebase master # resolving conflicts along the way
git merge -s ours somefeature # mark integration as superseding the somefeature branch
git checkout somefeature
git merge integration # this is now a fast-forward, no conflicts

A: The problem is caused because git rebase generates a new series of commits that aren't descended from the somefeature branch, then when you try and merge them back into somefeature the conflict resolution done during the rebase doesn't apply.  If you were to just merge instead of rebase then this would work as the merge commit would descend from the somefeature branch.
In terms of pushing to the remote branch you can just use --force to make the push succeed, that will cause problems for anyone else that has a copy of it though.

A: You could make sure your final merge overwrite the destination branch with a merge driver:
See "Can I tell git pull to overwrite instead of merge?" for example.
The idea is to have a custom merge driver with a "keepTheir" script.

A: Your first bit of operations is very strange. You make a copy of somefeature. You rebase that against master. Then you go back to that feature and merge it with the rebased equivelant of itself. This is not the way to do things.
Don't over complicate things. If you want the feature branch to start somewhere else instead (like the latest master), just rebase it.
Then push it with --force (or -f). Tell anyone else that was using that feature branch that they have to fetch the changes and adjust anything that they had locally that they didn't push yet.
Merge is better in the case when others have been working on it.
Hope this helps.


text:
Q: Using JNA/JNI to call C socket functions from Java threads I have to use a third-party library that has some socket functions. I have no access to the source code but it uses some simple functions:

*

*OpenConn to open a socket connection

*CloseConn to close the connection

*SocketRecv is a blocking function to receive data

These functions use a specific protocol so I can't use Java sockets instead.
Edit: I must use the library since it is a requirement. Discarding the library is not possible.
This is the code I'm using that I will describe below:
public class Test {
    private static int descriptor = -1;
    private static int numBytesRecv;
    public static byte[] buffer = new byte[255];
    public static SocketLib lib = null;

    public static void main(String[] args) throws InterruptedException{
        String server_ip = "0.0.0.0";
        lib = SocketLib.INSTANCE;
        descriptor = lib.OpenConn(server_ip);
        System.out.println("Descriptor: " + Integer.toString(descriptor));

        RecvThread t = new RecvThread();
        t.start();

        int closeResult = lib.CloseConn(descriptor);
        System.out.println("Close result: " + Integer.toString(closeResult));

        t.join();
        System.out.println("Program finish");
    }

    static class RecvThread extends Thread {
        public void run() {
            System.out.println("Starting RecvThread");
            numBytesRecv = lib.SocketRecv( descriptor, buffer, 255);
            System.out.println("Finishing RecvThread");
        }
    }

(JNA definitions code is not included)
I first call to OpenConn to open a connection in the main thread.
Then I start a thread with the SocketRecv function to wait for any data.
Then I close the connection in the main thread.
The expected behaviour would be that, after closing the connection, the socket is closed and the receiving function is released so the program finishes.
If I use a similar C application to test that behaviour, it works OK.
But when using JNA (as in the code above) or JNI to call the C functions, the socket is not closed when I call the CloseConn function and, because of that, the SocketRecv thread never finishes (if no data is received).
Edit: Via debugging, I am sure that the receiving thread is started before the closing function is called. If the close function is called before the SocketRecv, the SocketRecv function does not block and its thread finishes.
What could be causing that the socket is not closed when calling the CloseConn function from Java? I've thought about any issues with the fact that I use a separate Java thread to call the SocketRecv function, but I haven't found any similar case as a reference.


text:
Q: Difference between ChangeListener and InvalidationListener javafx I have exams soon and my teacher just can't explain it.
I've already read https://docs.oracle.com/javafx/2/api/javafx/beans/value/ObservableValue.html
and don't understand the InvalidationListener.
At what time is the ObservableValue recomputed so the InvalidationsListeners method invalidated would be executed?
In which cases would the Listeners method run if I would use an ChangeListener but not if I would use an InvalidationListener?


text:
Q: 504 Gateway Time-out - Form submission on Laravel Forge server with Wordpress I am facing an error on a Laravel Forge server that has Wordpress installed when submitting forms through any form plugin.
The error is:
504 Gateway Time-out

nginx/1.11.9

The form will keep spinning and not actually submit. The head request is sent, but the server eventually times out.
It's worth noting, I have tried disabling all other plugins and themes in order to ensure it is not a plugin/theme conflict.
Any ideas?

A: The answer to this problem is that you need to implement a way for emails to be sent. There are free WordPress plugins for external transactional email senders, such as SparkPost.
Once this was correctly set up, everything works as intended.


text:
Q: Converting string with color name to color"id" I have
public String colorid = "Blue";

And
  Sbrush = new SolidBrush(Color.Convert.ToInt32(colorid));

I want to be able to define the colorid somewhere else, that's why I wrote the SolidBrush code like that. Now this doesn't work and I would appreciate it if someone could help me

A: Use creating color from name
Color.FromName("Blue")

A: This way support both color name and html colors:
string nm = "Blue"; // or f.ex. "#0000ff"

if (nm.StartsWith("#")) {
    return ColorTranslator.FromHtml(nm);
}
else {
    return Color.FromName(nm);
}


text:
Q: PHP 7.1 install with Homebrew - error running brew tap homebrew/homebrew-php I'm trying to install PHP 7.1 on my Mac using Brew.  I do not have any version of PHP other than what Apple installs as default.
I've run the following commands (based on various posts) to install PHP 7.1:
brew tap homebrew/dupes
brew tap homebrew/versions
brew tap homebrew/homebrew-php

When I run the brew tap for homebrew-php I get the following messages (copied from terminal).  Can anyone suggest what I need to do?
brew tap homebrew/homebrew-php
==> Tapping homebrew/php
Cloning into '/usr/local/Homebrew/Library/Taps/homebrew/homebrew-php'...
remote: Counting objects: 757, done.
remote: Compressing objects: 100% (512/512), done.
remote: Total 757 (delta 505), reused 305 (delta 236), pack-reused 0
Receiving objects: 100% (757/757), 306.08 KiB | 0 bytes/s, done.
Resolving deltas: 100% (505/505), done.
Checking out files: 100% (748/748), done.
Error: Invalid formula: /usr/local/Homebrew/Library/Taps/homebrew/homebrew-php/Formula/deployer.rb
invalid attribute for formula 'homebrew/php/deployer': version (nil)
Error: Cannot tap homebrew/php: invalid syntax in tap!

A: You can try:
brew search php7

A list of available php extensions will be listed to you.
To install php7.1 you can use:
brew install homebrew/php/php71

A: I realized I needed to add homebrew/php to my repositories then I was able to run brew install homebrew/php/php71 and it worked. I have to wonder if I might had a typo.  Either way, it installed a bunch of dependencies and it just worked.