text:
Q: Is there long long defined? Where to check if type long long is defined? I wanna do something like this:
#ifdef LONGLONG
#define long_long long long
#else
#define long_long long
#endif

A: LLONG_MAX gives the maximum value representable by a long long; if your implementation doesn't support long long, it shouldn't define LLONG_MAX.
#include <limits.h>

#ifdef LLONG_MAX
#define long_long long long
#else
#define long_long long
#endif

This isn't a perfect solution.  long long isn't standard in C++03, and long long has been around longer than C99, so it's possible (and likely) that a compiler could support long long but not define LLONG_MAX.
If you want an integer type with a specific size, you should use <stdint.h> if your implementation supports it.  If your implementation doesn't support it, Boost has an implementation of it.

A: Rather than worry about whether or not a type with that name is defined, I'd #include <climits> and check whether or not you can find an integer type large enough for your intended use. (Although you could probably just check if LLONG_MAX is defined to find out if long long exists.)
Edit: Or, if you can assume C99 headers and types to be available, #include <cstdint.h> and use e.g. int64_t to get a 64-bit type or int_fast64_t to get a "fast" 64-bit type (by some compiler-specific definition of fast). Or intmax_t if you want the largest available type.


text:
Q: Name of this effect, or related plugin What do you call this kind of effect, that Tumbler has, where content are displayed and animated?
http://www.tumblr.com/
Thank you in advance...

A: It's generally called a slider.

A: There are 2 div's here,
1st div - till the copyright statement and
2nd div - 30 reasons you'll love Tumblr
When you hit the down arrow, div1 slides up, the jQuery code will look something like this
$("#div1").slideUp(1000);

this slidUp will allow another div, div3 - The easiest way to blog to appear.
and the same is done when you hit the home button,
The div3 slides down, the jQuery code will look something like  this,
$("#div3").slideDown1(1000);

this slideDown will let div1 appear again.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Preserve tabs in Sphinx Makefile code-block's I use Sphinx with reStructuredText input and HTML output to document different pieces of the infrastructure. The idea is that a user who reads the documentation can copy examples and past them into her file. How can that be done for Makefile examples? Makefiles need tab characters at certain places, but Sphinx converts tabs into spaces.
Example: The command line must start with a tab in the final HTML. Here it is written with three spaces for indent and a tab:
.. code-block:: Makefile

   target: dependency
    command -i $< -o $@

code-block does not have an option to control tab expansion.
A web search with sphinx code-block makefile tab has answers for tab expansion in included code (I prefer to have it inline) or how the Sphinx Makefile can be edited, but nothing that soles my problem.

A: Tab expansion happens very early stage of parsing RST, so you have to customize parser itself to disable it. I hope this works.
from typing import Union
from docutils.nodes import document
from docutils.statemachine import StringList
from sphinx.parsers import RSTParser

class NoTabExpansionRSTParser(RSTParser):
    def parse(self, inputstring: Union[str, StringList], document: document) -> None:
        if isinstance(inputstring, str):
            lines = inputstring.splitlines()
            inputstring = StringList(lines, document.current_source)
        super().parse(inputstring, document)

def setup(app):
    app.add_source_parser(NoTabExpansionRSTParser, override=True)

FYI, here's where tab expansion happens, which is bypassed by the above code.
In sphinx.parsers.RSTParser#parse
lines = docutils.statemachine.string2lines(
    inputstring, tab_width=document.settings.tab_width,
    convert_whitespace=True)

↓
In docutils.statemachine.string2lines
return [s.expandtabs(tab_width).rstrip() for s in astring.splitlines()]


text:
Q: Smart Garbage Collection? You can garbage collect in Java simply by calling System.gc() but sometimes this "stalls" the application. Is it a bad idea to garbage collect like this and avoid stalls:
new Thread(new Runnable() {
   public void run() {
      System.gc();
   }
}).start();

Or might this lead to even more problems?

A: Yes, most times it is a very bad idea to call System.gc(). There are exceptions but they are few and it is mostly better to spend the time making sure you are not doing things that hurt performance in a GC environment and to study and make sure you understand how a gc works than to try to handle it yourself by explicitly calling System.gc().

A: I can't beat @haylem answer's clarity and force, sorry. But let me add that there are a lot of (better) ways to manage memory in Java. There is, for example, WeakReference and collections which handle these, like WeakHashMap. These are deterministic ways to handle memory, though explicit calls to GC are not, as per the javadoc
Calling the gc method suggests that the Java Virtual Machine expend effort toward
recycling unused objects in order to make the memory they currently occupy available
for quick reuse. When control returns from the method call, the Java Virtual Machine
has made a best effort to reclaim space from all discarded objects.

A: First Things First: DO NOT CALL THE GC EXPLICITLY
Except if you have a very good reason for it. And even if you think you do, you probably don't.
The GC Knows What It's Doing (most of the time...)
If you kept reading, I'm assuming you have a really awesomely good (albeit probably twisted) reason to attempt to screw around with the GC, even though it is very likely to be a lot clever than you are at determining when it should collect memory. Also, keep in mind that by calling it explicitely you confuse it and screw up its heuristics, so it gets less clever than it was before. All because you attempted to outsmart it.
The GC Doesn't Always Care About What You Say
If you do this for a very good reason, or in a case where you really want to ensure that you start an intensive code section with the best memory state possible, you need to know this probably won't work: calls to System.gc() do not guarantee a garbage collection to take place, as mentioned by its Javadoc (emphasis mine):

Calling the gc method suggests that the Java Virtual Machine expend effort
  toward recycling unused objects.

Other Recommendations
Hunt Down and Kill (Bad) Explicit GC

*

*turn on -XX:+DisableExplicitGC (if your JVM supports it) to prevent those crazy calls of doing any harm (credit to Fredrik in the comments)

*look with your favorite IDE or grep for calls to System.gc() and its equivalents and get rid of them.

Find Another Way
See Grooveek's answer for other useful suggestions (like using WeakReferences).
Experiment with Other GCs and Fine-Tune Your VM for Your App
Depending on your use case, maybe experimenting with other GC implementations might help: CMC, G1, ParallelGC, etc... If you want to avoid "stalls", I have had very good results with G1 since its introduction in the latest Java SE 6 updates and since the Java 7 release, running intensive enterprise applications for long-running periods.
Just be aware that JVM tuning is a very complicated art.
Further Reading
You can flip through these for a lot more details:

*

*The official HotSpot documentation

*Java SE 6 HotSpot VM Garbage Collection Performance Tuning

*Tuning Garbage Collection with the Java 5.0 Virtual Machine

*HotSpot Command Line Options *

*Understanding the Java Memory Model and Garbage Collection
* Use with care: sometimes not perfectly up-to-date, doesn't document everything, and lists a lot of experimental features, or HotSpot-only features.

A: Apart from what was already said so far, the whole idea is horribly flawed because you sadly miss one important detail:
While a full GC is running the application will be stopped! (at least currently on a modern Hotspot VM - and what else would you be using?)
There's a concurrent mark & sweep implementation in hotspot (though afaik not activated by default), but that incurs some extra overhead and still has to stop all threads before doing the sweep. So basically unimportant from which thread you do System.gc() the VM will wait for all threads to reach a safe point, stop them and then do the collection. So using a thread is completely useless.

A: I totally agree that explicitely calling the garbage collector is not recommended in general. It can stall the application for several seconds and sometimes minutes. This is usually not an issue if you are dealing with a background service, but if it is exposed to users, they will have a bad experience.
However, there are extreme cases when you will want to do this: when memory is running really short and the application could crash. But a lot can be done is the application's design and implementation to avoid those situations.
One of the features of Java I love when it comes to recollecting memory and avoid memory leak are WeakReference objects. They are your friends.

A: As others have said, calling System.gc() is usually a mistake.  (Not always ... )
Assuming that you have one of those rare use-cases where calling System.gc() is likely to be beneficial, there are two cases to consider:

*

*If your JVM is using a classical "stop the world" collector, then running it in a separate thread will make no difference.  The GC stops all application threads for the duration.

*If your JVM is running a concurrent collector, then running it in a separate thread may be a good idea.  It is true that all collectors have a phase in which all threads are stopped, but calling System.gc() is documented as returning after "the Java Virtual Machine has made a best effort to reclaim space from all discarded objects".  So running it in a separate thread will allow the current thread to do something else.  However, you  need to be careful to avoid launching multiple threads that each call System.gc(); i.e. the code that is responsible for launching the thread needs to keep track of any previous GC threads.


text:
Q: Set partitions of pairs Suppose I am given a set of $n$ pairs of items (so I have $2n$ items in the set). I wish to partition the set into 2 disjoint sets such that at least one pair of items has a member in each set. I want to know how many 2-partitions there are of the $2n$ items where the smallest set has $k$ elements.
For example, if I have two pairs of items $\{a_1,a_2,b_1,b_2\}$ I can partition them into the following subsets:

*

*$\{a_1,a_2,b_1\}$$\{b_2\}$;

*$\{a_1,a_2,b_2\}$$\{b_1\}$;

*$\{a_1,b_1,b_2\}$$\{a_2\}$;

*$\{a_2,b_1,b_2\}$$\{a_1\}$;

*$\{a_1,b_1\}$$\{a_2,b_2\}$;

*$\{a_1,b_2\}$$\{a_2,b_1\}$;

So there are 4 partitions with the smallest set of size 1, and 2 partitions with the smallest set of size 2.
I have exhaustively computed the numbers for 1, 2, and 3 pairs, but I'm looking for a general formula. I know if $k=1$ there are $2n$ partitions, but I haven't found a closed form for a general solution, or even a recursive formula.
edit: I can show that if $k=2$ there are $4n-4$ partitions.

A: First count the total number of partitions where the smallest set has $k$ elements, and then count the bad partitions, in which all pairs are together. Subtract bad from total.
The situation is a little different for $k=n$ than for $k\lt n$. This is because in the case $k=n$ there are $\frac{1}{2}\binom{2n}{n}$ partitions, and for $k\lt n$ there are $\binom{2n}{k}$.
Let us deal with $k\lt n$. If $k$ is odd, there is no bad partition. At least one couple must be separated, else our $k$-set would be made up of couples, so would have an even number of elements.
Now we deal with the case $k$ even, say $k=2l$. To make a bad partition, we choose $l$ couples. This can be done in $\binom{n}{l}$ ways.
A similar calculation takes care of the case $k=n$.


text:
Q: R Message: Error - replacement has x rows, data has y I am trying to use the package ggmap to caculate the distance for a target address with a list of addresse. My data in a csv looks like below:
Order ID    Address
1652049  435 E 70TH ST,10021
1652123  1365 YORK AVE,10021
1652053  530 E 72ND ST,10021

so I try to get the distance from my input address to all those address for example: 400 Hudson St,10013, and I have following code in R:
library(ggmap)
mydata<-read.csv("address.csv")
mydata$Address<-as.character(mydata$Address)
mydata$Distance<-NA
a<-c("289 Hudson St,10013")
mydata$Distance<-mapdist(mydata$Address,a)$miles

However the code gives me a error message as below:
Error in `$<-.data.frame`(`*tmp*`, "Distance", value = c(8.2403854, 8.2403854,  :
  replacement has 53 rows, data has 31

A: Make sure column names don't have spaces; so instead of the name "Order ID", use something like "Order_ID". Also have each address as its own separate string:
library(ggmap)

mydata$Address<-as.character(mydata$Address)
mydata$Distance<-NA
a<-c("289 Hudson St,10013")
mydata$Distance<-mapdist(mydata$Address,a)$miles

Output:
  Order_ID             Address Distance
1  1652049 435 E 70TH ST,10021 8.240385
2  1652123 1365 YORK AVE,10021 8.475275
3  1652053 530 E 72ND ST,10021 8.618197

Sample data:
mydata <- data.frame(Order_ID=c(1652049,1652123,1652053),
                     Address=c('435 E 70TH ST,10021','1365 YORK AVE,10021',
                               '530 E 72ND ST,10021'))

EDIT:
Note that in the above data, each address is its own string within a vector c(). We can see this is the case by the use of single quotation marks around each address. The reason we do this is to prevent mixing up the data in the case of using CSV files, which have columns that are comma-separated. Before reading a CSV file into R which has commas in its columns, like the address column above, make sure each value/cell in that column is saved as its own string as I've done (i.e. surrounded by single quotes).


text:
Q: Having difficulty with Dependency properties I created my own CustomSlider (UserControl). See the code below:
Code behind:
    public partial class CustomSlider : UserControl, INotifyPropertyChanged
    {

        public CustomSlider()
        {
            InitializeComponent();
            this.Loaded += CustomSlider_Loaded;
        }

        public static readonly DependencyProperty PositionProperty;

        static CustomSlider()
        {
            PositionProperty = DependencyProperty.Register("Position", typeof(double), typeof(CustomSlider), new FrameworkPropertyMetadata());
        }

        public double Position
        {
            get
            {
                return (double)GetValue(PositionProperty);
            }
            set
            {
                SetValue(PositionProperty, value);
                NotifyPropertyChanged("Position");
            }
        }

        double length = 0;

        void CustomSlider_Loaded(object sender, RoutedEventArgs e)
        {
            track.DataContext = this;
        }

        public double MaxValue { get; set; }

        public event EventHandler ValueChangedManually;

        //Changing the position manually
        private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            length = this.Width;
            if (Double.IsNaN(this.Width))
                length = this.ActualWidth;
            Point p = Mouse.GetPosition(this);
            try
            {
                //Position = p.X; // this didn't work too
                this.SetValue(PositionProperty, p.X);
            }
            catch (Exception ex)
            {
                //test
            }
        }

        #region INotifyPropertyChanged Members
        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
        #endregion
    }

XAML:
    <Grid>
        <Border BorderThickness="1" Background="White" BorderBrush="Blue" MouseLeftButtonDown="Border_MouseLeftButtonDown"/>
        <Label Name="track" Background="#FF4250D8" Width="{Binding Path=Position, Mode=TwoWay}" HorizontalAlignment="Left" MouseLeftButtonDown="Border_MouseLeftButtonDown" />
    </Grid>

I created a new instance of my control in my form and tried to change the Position(one of the properties of my control) by clicking on top of CustomSlider. It changes the position as I expect. Then I tried to do this with DoubleAnimation. It works fine too. Problem is I can't change the Position by clicking on top of CustomSlider after changing the Position with DoubleAnimation. Here is the Animation code:
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            DoubleAnimation anim = new DoubleAnimation();
            anim.From = 0;
            anim.To =350;
            anim.Duration = TimeSpan.FromMilliseconds(1000);
            slider.BeginAnimation(CustomSlider.PositionProperty, anim);
        }

Is there something wrong with my DependecyProperty? Please help to fix this problem.
Thanks,

A: Copy of the @sa_ddam213's comments. That solved my problem.
That because the Animation is still running, try setting the Animations FillBehaviour to Stop anim.FillBehavior = FillBehavior.Stop; this will stop the TimeLine and allow you to modifiy the Dependancyproperty after the animation runs
FillBehavior.Stop will stop the animation and might revert the property to its pre-animated state.


text:
Q: Remapping one range of values to another, encountering integer overflow I need to remap several different ranges of values in my application, for example [0 1.0] to [-1000 1000]. So I created a template class (below) with the previous max/min and type (int/double) and the new max/min and type. The code works for small ranges, but when I try to convert ranges that exceed the integer range I am getting wrong results.
What I mean is if I try and map a range of std::int16_t [-32767 32767] to something else, I am encountering integer overflow/rollover. How can I fix this?
template<class P, class N>
class Remap {
public:
  /**
   * @brief Construct a new Remap object
   *
   * @param prevMin the previous range minimum value
   * @param prevMax the previous range maximum value
   * @param newMin the new range minimum value
   * @param newMax the new range maximum value
   */
  Remap(P prevMin, P prevMax, N newMin, N newMax) :
    prev_min_(prevMin),
    prev_max_(prevMax),
    new_min_(newMin),
    new_max_(newMax) {
    // TODO: Need to handle if min == max

    prev_range_ = prev_max_ - prev_min_;
    new_range_ = new_max_ - new_min_;
  };

  // Convert a previous value to the new mapping
  N Convert(P v) {
    return static_cast<N>((v - prev_min_) * new_range_ / prev_range_ + new_min_);
  }

private:
  P prev_min_;
  P prev_max_;
  N new_min_;
  N new_max_;
  P prev_range_;
  N new_range_;
};

An example that causes incorrect values
Remap<std::int16_t, double> my_remap(-32767, 32767, -1.0, 1.0);
// Should get 1.0
my_remap.Convert(32767);

I have traced the problem to
prev_range_ = prev_max_ - prev_min;

The correct value should be 65534 however since P is type int16_t I am not getting that value. Suggestions on how I can fix this?
** Edit: ** I can fix this by declaring Remap<std::int32_t, double> ... but not sure if there is a better/proper solution that actually uses the desired type of std::int16_t.

A: One thing that could mitigate this problem would be take out prev_range_ and new_range_ entirely and replace them with a scale factor, which is inherently a floating point number.
#include <stdexcept>      // std::out_of_range

template<class P, class N>
class Remap {
public:
  /**
   * @brief Construct a new Remap object
   *
   * @param prevMin the previous range minimum value
   * @param prevMax the previous range maximum value
   * @param newMin the new range minimum value
   * @param newMax the new range maximum value
   */
  Remap(P prevMin, P prevMax, N newMin, N newMax) :
    prev_min_(prevMin),
    prev_max_(prevMax),
    new_min_(newMin),
    new_max_(newMax)
  {
    if (prev_min_ == prev_max_)
        throw std::out_of_range("prev_min_ == prev_max_ !!\n");
    scale_ = (0.5*new_max_ - 0.5*new_min_)/(0.5*prev_max_ - 0.5*prev_min_);
  }

  // Convert a previous value to the new mapping
  N Convert(P v)
  {
    return 2*static_cast<N>((0.5*v - 0.5*prev_min_) * scale_ + 0.5*new_min_);
  }

private:
  P prev_min_;
  P prev_max_;
  N new_min_;
  N new_max_;
  double scale_; // Replaces prev_range_ and new_range_
};


text:
Q: For loop with two input files I wish to use a for loop for a command that requires two input files. There is a single character change between the two files. Here are two example files:
Fay2_TCCGGAGA-CCTATCCT_L001_R1_001.fastq
Fay2_TCCGGAGA-CCTATCCT_L001_R2_001.fastq

Here is my attempt of the command:
for f in /directory/*R1*.fastq
 pref=${basename "$f" _*R1*.fastq}
command input1 $f input2 ${pref}_*R2*.fastq

The issue most likely lies in manipulating the basename so the loop uses the permutation of file1 to find file2. How do I make the basename shorter than the entire file name. I am getting the error
Fay2_TCCGGAGA-CCTATCCT_L001_R2_001.fastq_*R2.fastq does not exist

Thanks to comments below the looping is working properly but my files are being overwritten whenever a the command loops over a new file. The following is my entire command which requires naming both output files.
for f1 in /directory/*R1*.fastq
f2="${f1/_R1_/_R2_}"
 pref=${basename "$f" _*R1*.fastq}
command output1 ${pref}_trim_R1.fastq output2 ${pref}_trim_R2.fastq input1 $f input2 $f2

A: You can loop through the R1 files and use brace expansion to derive R2 file names:
for r1_file in /directory/*_R1_*.fastq; do
  r2_file="${r1_file/_R1_/_R2_}"
  command input1 "$r1_file" input2 "$r2_file"
done


text:
Q: Designing Latex title page for Bachelor Thesis I'm completely new to Latex and would like to design a title page for my Bachelor thesis.
After some research, I've found a title page layout in another post here that I would love to use:
Adding supervisor to thesis
Unfortunately, I don't know how to implement it in Latex and don't understand the instructions given in the other post. I would be grateful for any help!
Currently, this is my preamble and start:
\documentclass[a4paper, 12pt]{article}
\usepackage{apacite}
\usepackage{verbatim}
\usepackage{graphicx}
\usepackage{etoolbox}
\usepackage[hyphens]{url}
\urlstyle{same}
\usepackage{amsmath}
\usepackage{rotating}
\usepackage{dcolumn}

\makeatletter
\patchcmd{\@caption}{\csname the#1\endcsname}{\csname fnum@#1\endcsname:}{}{}
\renewcommand*\l@figure{\@dottedtocline{1}{1.5em}{4.5em}}
% default for 3rd arg: 2.3em
\let\l@table\l@figure % as in article.cls
\makeatother

%define the author
\author{John Smith}

%define the title
\title{Blue Elephants}

\begin{document}

%omits page number
\pagenumbering{gobble}

%generates the title
\maketitle

\newpage
\end{document}

My existing code is mostly copy and pasted from this website to get my thesis layout to work. It's just the title page that I'm having issues with.
This is my first post. I hope I respected any potential rules.
Thank you!

A: Please, note that this is not an answer, is just a tip to let you go started with the definition of your title page.
The page that you provided has a broken link to google drive so I don't what layout you prefer. In the following I just added the standard definition of a title page with a supervisor.
\documentclass[a4paper, 12pt]{article}
\usepackage{apacite}
\usepackage{verbatim}
\usepackage{graphicx}
\usepackage{etoolbox}
\usepackage[hyphens]{url}
\urlstyle{same}
\usepackage{amsmath}
\usepackage{rotating}
\usepackage{dcolumn}

\makeatletter
\def\@maketitle{%
  \newpage
  \null
  \vskip 2em%
  \begin{center}%
  \let \footnote \thanks
    {\LARGE \@title \par}%
    \vskip 1.5em%
    {\large
      \lineskip .5em%
      \begin{tabular}[t]{c}%
        \@author\\
        \supervisor%
      \end{tabular}\par}%
    \vskip 1em%
    {\large \@date}%
  \end{center}%
  \par
  \vskip 1.5em}
\patchcmd{\@caption}{\csname the#1\endcsname}{\csname fnum@#1\endcsname:}{}{}
\renewcommand*\l@figure{\@dottedtocline{1}{1.5em}{4.5em}}
% default for 3rd arg: 2.3em
\let\l@table\l@figure % as in article.cls
\makeatother

%define the author
\author{John Smith}

%define the title
\title{Blue Elephants}

%define the supervisor
\def\supervisor{John Doe}

\begin{document}

%omits page number
\pagenumbering{gobble}

%generates the title
\maketitle

\newpage
\end{document}

Here the result.

A: Try using titlepage environment:
...
\begin{document}
\begin{titlepage}
\begin{center}
\vfill
\begin{Large}University...{Large}
\vfill
\begin{large}Faculty...\end{large}
\vfill
\includegraphics[width=4cm]{logo.png}
\vfill
\begin{large}\begin{czech}\textbf{Your Name}\end{czech}\end{large}
\vfill
\begin{huge}My thesis...\end{huge}
\vfill
\begin{large}Bachelor thesis\end{large}
\vfill
\textbf{Supervisor...}\\
\vfill
City, 2018
\vfill
\end{center}
\end{titlepage}
...
% Rest of the document

Basically, You use the above code instead of \maketitle command. Alter it as You like.


text:
Q: How to display the animation views on the top of buttons like UIAlertView I displayed 20 buttons on the view(almost the view is covered with bottons images), now I want to display information using animations on the top of all these buttons like UIAlertView.
Now I am displaying the alert view but instead of that I need to display the animated view on the top of all the buttons.
How can I achieve it, is there any idea to display the information on the top of all the buttons using view animations.
Please help me,
thank you, Madan Mohan.

A: Madan for this you will need two views. If you observe behavior of UIAlertView then you will find that when alert view is shown we can not interact with any other item on the view. So one view will serve the purpose for alertview and other will block interaction with UI.
You can do this as follows:
Have two views on your self.view. One view will hold all the elements that are currently on the self.view and other will have alertview. so hierarchy goes like this
self.view
   |------------View1
   |               |-----it will have all buttons and other ui that were earlier on self.view
   |
   |-------------View2
                   |------it will have a uiview which you will make,look like alertview.

initially view1 will be at front and view2 will be added at back.

Now how to piece all this together.
When user will tap on any button the you will need to bring backview to front inside [UIView beginanimation] and  other animation code and commite it.
and when user is done with this view you will send it to back.
Also, to make transparent look as we have when alertview is shown, set View2's backgroundColor black and alpha property 0.3 (or as you wish).
Thanks,


text:
Q: How do I condense this repetitive F# code? EDIT: possible solutions at bottom
I'm doing some data work where I need to be very careful about string lengths that will eventually be sent in fixed width text output, stored in limited size nvarchar fields, etc.  I want to have good strict typing for these rather than naked System.String types.
Suppose I've got some code like this to represent these, with a few useful module functions that play nicely with Result.map, Option.map, etc.
module String40 =
    let private MaxLength = 40
    type T = private T of string
    let create (s:string) = checkStringLength MaxLength s |> Result.map T
    let trustCreate (s:string) = checkStringLength MaxLength s  |> Result.okVal |> T
    let truncateCreate (s:string) = truncateStringToLength MaxLength s |> T
    let toString (T s) = s

    type T with
        member this.AsString = this |> toString

module String100 =
    let private MaxLength = 100
    type T = private T of string
    let create (s:string) = checkStringLength MaxLength s |> Result.map T
    let trustCreate (s:string) = checkStringLength MaxLength s  |> Result.okVal |> T
    let truncateCreate (s:string) = truncateStringToLength MaxLength s |> T
    let toString (T s) = s

    type T with
        member this.AsString = this |> toString

Obviously these are almost entirely repetitive with only the module name and max length different in each block.
What options are available to try and cut down on the repetitiveness here?  I would love to have something like this:
type String40 = LengthLimitedString<40>
type String100 = LengthLimitedString<100>

tryToRetrieveString ()   // returns Result<string, ERRType>
|> Result.bind String40.create

*

*T4 code generation doesn't seem to be an option for F# projects

*Type providers seem like overkill for this kind of simple templating, and as best as I can tell they can only produce classes, not modules.

*I'm aware of Scott Wlaschin's constrained strings page, but I end up with roughly the same level of repetitive code in the 'Create a type', 'Implement IWrappedString', 'create a public constructor' steps he lists.

These code blocks are fairly short and it wouldn't be the end of the world to just copy/paste a dozen times for the different field lengths.  But I feel like I'm missing a simpler way to do this.
UPDATE:
One other note is that it's important that records using these types give information about what type they're carrying:
type MyRecord =
  {
    FirstName: String40;
    LastName: String100;
  }

and not be something like
type MyRecord =
  {
    FirstName: LimitedString;
    LastName: LimitedString;
  }

Tomas' answer, using the Depended Type Provider nuget library is a pretty good one, and would be a good solution for a lot of people who are fine with its behavior as-is.  I felt like it would be a little tricky to extend and customize unless I wanted to maintain my own copy of a type provider which I was hoping to avoid.

Marcelo's suggestion of static parameter constraints was a fairly productive path of research.  They give me basically what I was looking for -- a generic argument that is basically an 'interface' for a static methods.  However the kicker is that they require inline functions to operate and I don't have the time to evaluate how much that would or would not matter in my code base.
But I took that and altered it to use regular generic constraints.  It's a bit goofy to have to instantiate an object to get a max-length value, and fsharp type/generic code is just gross to look at, but from the module users's perspective it's clean, and I can easily extend this however I want.
    type IMaxLengthProvider = abstract member GetMaxLength: unit -> int

    type MaxLength3 () = interface IMaxLengthProvider with member this.GetMaxLength () = 3
    type MaxLength4 () = interface IMaxLengthProvider with member this.GetMaxLength () = 4

    module LimitedString =

        type T< 'a when 'a :> IMaxLengthProvider> = private T of string

        let create< 't when 't :> IMaxLengthProvider and 't : (new:unit -> 't)> (s:string) =
            let len = (new 't()).GetMaxLength()
            match checkStringLength len s with
            | Ok s ->
                let x : T< 't> = s |> T
                x |> Ok
            | Error e -> Error e
        let trustCreate< 't when 't :> IMaxLengthProvider and 't : (new:unit -> 't)> (s:string) =
            let len = (new 't()).GetMaxLength()
            match checkStringLength len s with
            | Ok s ->
                let x : T< 't> = s |> T
                x
            | Error e ->
                let msg = e |> formErrorMessage
                failwith msg

        let truncateCreate< 't when 't :> IMaxLengthProvider and 't : (new:unit -> 't)> (s:string) =
            let len = (new 't()).GetMaxLength()
            let s = truncateStringToLength len s
            let x : T< 't> = s |> T
            x

        let toString (T s) = s
        type T< 'a when 'a :> IMaxLengthProvider> with
            member this.AsString = this |> toString

    module test =
        let dotest () =

            let getString () = "asd" |> Ok

            let mystr =
                getString ()
                |> Result.bind LimitedString.create<MaxLength3>
                |> Result.okVal
                |> LimitedString.toString

            sprintf "it is %s" mystr

A: I think the BoundedString type provider from the Dependent type provider project lets you do exactly what you need. Using the example from the project documentation, you can do e.g.:
type ProductDescription = BoundedString<10, 2000>
type ProductName = BoundedString<5, 50>

type Product = { Name : ProductName; Description : ProductDescription }

let newProduct (name : string) (description : string) : Product option =
  match ProductName.TryCreate(name), ProductDescription.TryCreate(description) with
  | Some n, Some d -> { Name = n; Description = d }
  | _ -> None

I don't know how many people use this project in practice, but it seems quite simple and it does exactly what you were asking for, so it might be worth a try.

A: Using a touch of careful reflection magic, we can achieve a lot and get some really nice types. How about something like this?
module Strings =
    type [<AbstractClass>] Length(value: int) =
        member this.Value = value

    let getLengthInst<'L when 'L :> Length> : 'L =
        downcast typeof<'L>.GetConstructor([||]).Invoke([||])

    type LimitedString<'Length when 'Length :> Length> =
        private | LimitedString of maxLength: 'Length * value: string

        member this.Value =
            let (LimitedString(_, value)) = this in value
        member this.MaxLength =
            let (LimitedString(maxLength, _)) = this in maxLength.Value

    module LimitedString =
        let checkStringLength<'L when 'L :> Length> (str: string) =
            let maxLength = getLengthInst<'L>.Value
            if str.Length <= maxLength then Ok str
            else Error (sprintf "String of length %d exceeded max length of %d" str.Length maxLength)

        let create<'L when 'L :> Length> (str: string) =
            checkStringLength<'L> str
            |> Result.map (fun str -> LimitedString (getLengthInst<'L>, str))

open Strings

// === Usage ===

type Len5() = inherit Length(5)
type Len1() = inherit Length(1)

// Ok
LimitedString.create<Len5> "Hello"
// Error
LimitedString.create<Len1> "world"

A: One option might be to use a single module for limited-length strings that uses curried parameters for the length-limit and the string itself, then just partially apply the limit parameter.  An implementation might look like this:
module LimitedString =
    type T = private T of string
    let create length (s:string) = checkStringLength length s |> Result.map T
    let trustCreate length (s:string) = checkStringLength length s  |> Result.okVal |> T
    let truncateCreate length (s:string) = truncateStringToLength length s |> T
    let toString (T s) = s

    type T with
        member this.AsString = this |> toString

Then, your modules for each length would still be required, but wouldn't have all the boilerplate:
module String100 =
    let create = LimitedString.create 100
    let trustCreate = LimitedString.trustCreate 100
    let truncateCreate = LimitedString.truncateCreate 100

EDIT
After reading the comment and the update to the original post, I would change my suggestion a bit.  Instead of defining the T type inside each module, I would have a specific struct-type single-case union for each string length at the top level.  Then, I would move to toString to the individual string modules.  Finally, I would add one more parameter to the LimitedString module to allow us to partially apply both the length and the specific single-case union type:
[<Struct>] type String40 = private String40 of string
[<Struct>] type String100 = private String100 of string

module LimitedString =
    let create length ctor (s:string) = checkStringLength length s |> Result.map ctor
    let trustCreate length ctor (s:string) = checkStringLength length s  |> Result.okVal |> ctor
    let truncateCreate length ctor (s:string) = truncateStringToLength length s |> ctor

module String40 =
    let create = LimitedString.create 40 String40
    let trustCreate = LimitedString.trustCreate 40 String40
    let truncateCreate = LimitedString.truncateCreate 40 String40
    let toString (String40 s) = s

module String100 =
    let create = LimitedString.create 100 String100
    let trustCreate = LimitedString.trustCreate 100 String100
    let truncateCreate = LimitedString.truncateCreate 100 String100
    let toString (String100 s) = s

type MyRecord =
    {
        FirstName: String40
        LastName: String100
    }

There's still a fair amount of boilerplate here, but I think this is in the ballpark for a solution using single-case unions and modules.  A Type Provider might be possible, but you would have to consider whether the added complexity outweighs the boilerplate.

A: Can't you use Static Parameters, as shown on the F#.Data package's HtmlProvider example?


text:
Q: How can I get the ID generated when I insert a file in Karate DSL using SOAP I have a scenario where I POST a file using soap service (xml). The scenario works ok, but I need to get the id that is generated automatically and incrementaly and to save it in a variable. Someone asked me to use this:

*

*def id= //logId
And print id

It worked in another case where the id is always the same. That is, in one case  where I insert a file that is overwritten, keeping the same id.
However, if I try to use it for the first case, where the id is incremental it returns a #notpresent message in the "print id".  But if I use and assertion where I write:
id == #present, it returs ok.
This es the response after executing the scenario. It is Ok, the id is present in the assertion but it doesn't print.
And match response /Envelope/Body/respuesta/return/message == 'OK'
And match response /Envelope/Body/respuesta/return/status == '0100'
And match response /Envelope/Body/respuesta/return/logId == '#present'

* def id = //logId
And print id

12:48:23.800 [print] #notpresent
Thanks for your help.

A: Thanks for your help.
I have solved the issue.
I had to put a "return" after the double //:

*

*def id = //return/logId


text:
Q: gridview replace string from a boundfield I have a SPGridView that displays items from a list (using spboundfield).
The multi-lookup fileds in my SPGridview the filter values of a lookupfield appear in this format:
{id};#{Value}
How do I replace the id;# from the field?

A: Here is how I solved this issue. (NOTE i had to put a dot before asp and itemtemplate for this post. remove those dots)

asp:TemplateField HeaderText="Campaign Members">
 ItemTemplate>
%# RemoveCharacters(Eval("CampaignMembers").ToString())%>
 /ItemTemplate>
/asp:TemplateField>
// Make sure declare using System.Text.RegularExpression;
 protected string RemoveCharacters(object String)
{
 string s1 = String.ToString();
string newString = Regex.Replace(s1, @"#[\d-];", string.Empty);
newString = Regex.Replace(newString, "#", " ");
return newString.ToString();
 }


text:
Q: Change the order of a std::set as a member attribute I am trying to change the order of a set in a particular configuration :
a customObject has the following form
class CustomObject{
public:

...
std::set<CustomObject*> container;

};

and I would like to keep permanently the property telling that the container is sorted in the following order :
elt1 & elt2 are elements of container,
and
elt1 < elt2 iff elt1.container.size()<elt2.container.size()
I know I have to use
struct cmpStruct {
    bool operator() (int const & lhs, int const & rhs) const
  {
    return lhs > rhs;
  }
};

as described Is the std::set iteration order always ascending according to the C++ specification?
But I don't know how to do to access the "this" inside the structure
Thanks a lot for your help

A: Something like that?
class CustomObject{
public:
    CustomObject(int _x) : x(_x) {};
    int x;
};

struct cmpStruct {
    bool operator() (const CustomObject*  lhs, const CustomObject*  rhs) const
    {
        return lhs->x > rhs->x;
    }
};

int main(int argc, char* argv[])
{
    std::set<CustomObject*, cmpStruct> container;

    CustomObject a(10);
    CustomObject b(20);
    CustomObject c(5);

    container.insert(&a);
    container.insert(&b);
    container.insert(&c);

    for(auto co : container) {
        std::cout << co->x << std::endl;
    }
    return 0;
}

Output:
20
10
5


text:
Q: I need to extract tracking number from _wc_shipment_tracking_items field in wordpress woocommerce order I need to extract tracking_number from _wc_shipment_tracking_items field in wordpress woocommerce order.
I retrieve the data like this:
return get_post_meta($order->id)['_wc_shipment_tracking_items'][0];

and in response I get JSON format list of data:
[
{"tracking_provider": "australia-post",
"custom_tracking_provider":",
"custom_tracking_link":"",
"tracking_number":"WZGZ10000709",
"tracking_product_code":",
"date_shipped":"1672963200",
"products_list":",
"status_shipped": "1",
"tracking_id":"f98fb8c0fe94b25688d15db12fd73"}
]

How do I get just the tracking number WZGZ10000709?


text:
Q: Is there any alternatives in useState when calling multipleStates? So I don't really have a problem but I'm troubling with a lot of codes and I want to reduce it.
So for example I have
import React, { useState } from 'react'

function Source() {

    const [addClockName,setAddClockName] = useState("Add Clock Name")
    const [addTime,setAddTime] = useState("Time")
    const [addMusic,setAddMusic] = useState("Music")
    const [addAlarmlength,setAddAlarmlength] = useState("Alarm length")

    return [
        addClockName,setAddClockName,
        addTime,setAddTime,
        addMusic,setAddMusic,
        addAlarmlength,setAddAlarmlength
    ]
}

export default Source

When I'm importing this it will be something like this in other files
import Source from 'path'

    const [
        addClockName,setAddClockName,
        addTime,setAddTime,
        addMusic,setAddMusic,
        addAlarmlength,setAddAlarmlength
    ] = Source()

    instead like this
    const { addTime } = Source()

    ...or whatsoever

but what I only want to import is just certain items that I need and I want to avoid recalling the same array of items. Is there any alternatives or just a simpler way to do this?

A: Don't return an array, return an object. Then you can pick only the properties of the object that you want. Since it's a custom hook, you should also probably prefix it with use.
const useSource = () => {
    // ...
    return {
        addClockName, setAddClockName,
        addTime, setAddTime,
        addMusic, setAddMusic,
        addAlarmlength, setAddAlarmlength
    };

and, for example, if you only want to use the music state:
const {
    addMusic,
    setAddMusic,
} = useSource()

But keep in mind that if you do this, you'll have separate states every time you call useSource, which may not be desirable. If you want to have just one full Source state, call it once, then pass down the result so that children can pick what they want to use, like:
const Parent = () => {
    const sourceObj = useSource();
    // ...
    return <SomeComponent sourceObj={sourceObj}>
}
const SomeComponent = ({ sourceObj }) => {
    const { addMusic, setAddMusic } = sourceObj;
    // ...

A: Don't worry
You can make your own hooks and use it.
Example:
Make custom hooks
const useFetch = (url) => {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch(url)
      .then((res) => res.json())
      .then((data) => setData(data));
  }, [url]);

  return [data];
};

export default useFetch;

and use it:
const Home = () => {
  const [data] = useFetch("https://jsonplaceholder.typicode.com/todos");

  return (
    <>
      {data &&
        data.map((item) => {
          return
{item.title}
;
        })}
    </>
  );
};

Good luck..


text:
Q: Using external class in my Controller Im working on my first project in CodeIgniter and I wonder How can I use my class from library in my Controller.
libraries/Twitterclass.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Twetterclass {

public function __construct($hashtag, $tweet_id)
{
    require_once('TwitterAPIExchange.php');

    //There is my working code

    //I want to make use of this $n in my Controller
    return $n;

}
}

/* End of file Twetterclass.php */

My Controller:
    public function microtweets()
    {
        $params = array('hashtag' => 'somehashtag', 'tweet_id' => '673899616799191040');
        $data['count_tweets'] = $this->load->library('Twetterclass', $params);

        $this->load->view('tweets', $data);
    }

I want to use his extended class in my controller and work there on this $n value or for example display it in my View.
I get few errors:

A PHP Error was encountered
Severity: Warning
Message: Missing argument 2 for Twetterclass::__construct(), called in
  /home/jail/kg7dad5/home/kg7dad5/domains/badzlepszy.pl/public_html/coinmonitor/system/core/Loader.php
  on line 1246 and defined
Filename: libraries/Twetterclass.php
Line Number: 5
Backtrace:
File: /application/libraries/Twetterclass.php Line: 5 Function:
  _error_handler
File: /application/controllers/Cointweet.php Line: 24 Function:
  library
File: /public_html/coinmonitor/index.php Line: 292 Function:
  require_once

A: first try to debug parameter you passed in constructor
public function __construct($hashtag, $tweet_id)
{
   echo $hashtag;
   echo $tweet_id;
   die;
}

A: according to your code, change like this,
public function __construct($arr)
{
   echo $arr['hashtag'];
   echo $arr['tweet_id'];
   exit;
}

Because you are passing 1 array, so access in library with array index.


text:
Q: Accessing Scope_Identity from controller with Entity Framework I need to generate a value from whatever gets produced by a table's identity. The code is working, but I'm wondering if there is a more elegant way to do what I'm doing.
The issue is my controller is unaware of the Entity Framework, so I don't have direct access to the EF entity which will hold the identity value once the context has been saved.
[HttpPost]
    public ActionResult Index(NewPlannerEntryCreateViewModel vm)
    {
        if (ModelState.IsValid)
        {
            Mapper.CreateMap<PlannerEntryRecord, TradeSpendRecord>();

                //Need to insert the records, then update them so that I
                //can leverage existing stored procs
                TradeSpendRecord r = Mapper.Map<PlannerEntryRecord, TradeSpendRecord>(vm);
                r.VersionDate = now;
                _tsRepo.Insert(r);
                _uow.Save();
                _tsRepo.PostInsert();
                _uow.Save();

            return RedirectToAction("Index", "Home", new { area = "US" });
        }

So I call my repo's insert method, which assigns the EF entity to a private field, then I call Save() on my context, which updates that EF entity, and then I call a PostInsert() method to generate my value:
 public class TradeSpendRepository : EFRepository<tblTradeSpend>, ITradeSpendRepository
{
    tblTradeSpend _record;

    public void Insert(TradeSpendRecord record)
    {
        Mapper.CreateMap<TradeSpendRecord, tblTradeSpend>();
        _record = Mapper.Map<TradeSpendRecord, tblTradeSpend>(record);

        base.Insert(_record);
    }

    /// <summary>
    /// We need to access the identity of this record, which
    /// we can only do after SaveChanges() is executed in the controller
    /// </summary>
    public void PostInsert()
    {
        //Build the promo id off the ID
        string promoId = (_record.ID + 1).ToString();
        promoId = "000000" + promoId;
        promoId = "P" + promoId.Substring(promoId.Length - 7, 7);
        _record.PromoID = promoId;
        Update(_record);
    }

Any way to clean this up?
Chris


text:
Q: Regex return all text other than text in MULTIPLE sets of parentheses I am looking for regex that will allow me to extract the names and drop everything inside the parentheses. Example data below.
Text string:
John (Juan, Jonathan, Jon, Jonny) James Doe (born on January 1, 1900)

Desired output:
John James Doe

Further in some cases the text string may be like:
John (Juan, Jonathan, Jon, Jonny) James Doe (born on January 1, 1900) (Canada)

and in this case we would still want returned:
John James Doe

I tried the solution from the linked question, but I still get the wrong output:
John James Doe (born on January 1, 1900)

A: Using regex only and not any replace function :
[^\S]*(\w*)(?:\s*)(?:\([^()]*\))*
https://regex101.com/r/zF2cMM/4
Edit :
(?:[^\S]*(\w*)(?:\s*)(?:\s*\([^()]*\)\S*)*)
I have made this last one version correcting a problem on last match
You can compare V4 and V6 and see that the result is a little bit different
https://regex101.com/r/zF2cMM/6
Now this work fine.


text:
Q: current location in fragment I have tried many sources but I am not getting what should be used for my fragment to get the current location.
This is my fragment:
 public class GMapFragment extends Fragment implements OnMapReadyCallback {
    private GoogleMap googleMap;
    MapFragment fragment;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {

            View rootView = inflater.inflate(R.layout.fragment_gmap, container, false);
            initilizeMap();
            return rootView;
        }
         private void initilizeMap()
        {
            MapFragment fragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
               if (fragment != null){
                   fragment.getMapAsync(this);

               }

        }
        @Override
        public void onMapReady(final GoogleMap googleMap) {
            googleMap.setMyLocationEnabled(true);
            googleMap.getUiSettings().setZoomControlsEnabled(true);

        }

         @Override
        public void onPause() {

            final FragmentManager fragManager = this.getFragmentManager();
            final Fragment fragment = fragManager.findFragmentById(R.id.map);
            if(fragment!=null){
                fragManager.beginTransaction().remove(fragment).commit();
            super.onPause();

            }
        }
        @Override
        public void onDestroy() {
            super.onDestroy();
            final FragmentManager fragManager = this.getFragmentManager();
            final Fragment fragment = fragManager.findFragmentById(R.id.map);
            if(fragment!=null){
                fragManager.beginTransaction().remove(fragment).commit();
            }
        }
        }

If anyone can help? I need a source or sample that can be used with this fragment. please help, I'm stuck here for days

A: Did you have ACCESS_FINE_LOCATION in your Manifest file?
Also, know that if your app is running on >= API 23 device, you have to request the permission grant from the users.
Follow the official GUIDE
EDIT:
Do you have initialized Google Play Services?

A: from documentation

While enabled and the location is available

Do you have available location ?

A: SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(getActivity()).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();

Connect the above google api client in onStart and disconnect in onstop
@Override
    public void onStart() {
        super.onStart();
        if (mGoogleApiClient != null)
            mGoogleApiClient.connect();
    }

Override the methods.
public void onConnected(@Nullable Bundle bundle) {

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
        }
        myLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (myLocation != null) {
            showCurrentLocation(myLocation);
            return;
        }
        if (!NetworkHelper.isGpsEnabled(getActivity()))
            PopUp.showAlertDialog(act, "Enable GPS",
                    "Help us to get your current location");
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, locationRequest, new LocationListener() {
                    @Override
                    public void onLocationChanged(Location location) {
                        if (location == null)
                            return;
                        myLocation = location;
                        showCurrentLocation(location);
                    }
                });

    }


text:
Q: Writing to ffpmeg stdin freezes program I'm trying to convert a file in memory using ffmpeg to another format by using stdin and stdout, but everytime I try to write to stdin, of my ffmpeg command, it just freezes there.
package main

import (
    "bufio"
    "fmt"
    "io"
    "os"
    "os/exec"
)

func test(bytes []byte) ([]byte, error) {

    cmd := exec.Command(
        "ffmpeg",
        "-i", "pipe:0", // read from stdin
        "-vcodec", "copy",
        "-acodec", "copy",
        "-f", "matroska",
        "pipe:1",
    )

    in, err := cmd.StdinPipe()
    if err != nil {
        panic(err)
    }
    out, err := cmd.StdoutPipe()
    if err != nil {
        panic(err)
    }

    fmt.Println("starting")
    err = cmd.Start()
    if err != nil {
        panic(err)
    }

    fmt.Println("writing")
    w := bufio.NewWriter(in)
    _, err = w.Write(bytes)
    if err != nil {
        panic(err)
    }

    err = w.Flush()
    if err != nil {
        panic(err)
    }

    err = in.Close()
    if err != nil {
        panic(err)
    }

    fmt.Println("reading")
    outBytes, err := io.ReadAll(out)
    if err != nil {
        panic(err)
    }

    fmt.Println("waiting")
    err = cmd.Wait()
    if err != nil {
        panic(err)
    }

    return outBytes, nil
}

func main() {
    dat, err := os.ReadFile("speech.mp4")
    if err != nil {
        panic(err)
    }

    out, err := test(dat)
    if err != nil {
        panic(err)
    }

    err = os.WriteFile("test.m4v", out, 0644)
    if err != nil {
        panic(err)
    }
}

It prints
starting
writing

and gets stuck there. I tried similar code with grep, and the everything worked fine, so this seems to be some ffmpeg specific problem.
I tried running
cat speech.mp4 | ffmpeg -i pipe:0 -vcodec copy -acodec copy -f matroska pipe:1 | cat >  test.mkv
and that works fine, so it's not an ffmpeg problem, but some problem with how I'm piping/reading/writing my data.
My speech.mp4 file is around 2MB.

A: So the secret lied in reading stdout as you dumped the bytes into stdin, since writing to the pipe blocks. Thanks @JimB for helping me figure this out.
You just have to read as you write:
cmd := exec.Command(
    "ffmpeg",
    "-i", "pipe:0", // read from stdin
    "-vcodec", "copy",
    "-acodec", "copy",
    "-f", "matroska",
    "pipe:1",
)

out, err := cmd.StdoutPipe()
if err != nil {
    panic(err)
}

in, err := cmd.StdinPipe()
writer := bufio.NewWriter(in)
if err != nil {
    panic(err)
}

fmt.Println("starting")
err = cmd.Start()
if err != nil {
    panic(err)
}

go func() {
    defer writer.Flush()
    defer in.Close()
    fmt.Println("writing")
    _, err = writer.Write(bytes)
    if err != nil {
        panic(err)
    }
}()

var outBytes []byte

defer out.Close()
fmt.Println("reading")
outBytes, err = io.ReadAll(out)
if err != nil {
    panic(err)
}
fmt.Println("waiting")
err = cmd.Wait()
if err != nil {
    panic(err)
}

return outBytes, nil


text:
Q: Python Launcher automatically opens I am using a MacBook Pro, every time I use command+F5 in IDLE to run my python scripts, Python Launcher would automatically opens. However, the logo keeps jumping on my Dock and I actually got the message "Application Not Responding". I later found that if I run my script from Terminal, Python Launcher will also automatically opens and quits after several seconds.
Is this normal. If not, how could I solve it.
Thanks!


text:
Q: Solving an equation with absolute values inside absolute value How do I solve this?
$$\big||2x-6|-|x-9|\big|<3$$
I know you can just square $[()^2]$ the whole inequation, but in this case it becomes a very ugly expression.
I'm sure there's an easier way!

A: The first step would be to write it in an equivalent way:
$$\big||2x-6|-|x-9|\big|<3\iff -3+|x-9|<|2x-6|<3+|x-9|.$$
Now, the absolute values have important points in $x=3$ and $x=9$. So one can write, for example, for $x\ge 9$:
$$   -3+ x-9 < 2x-6 <3+ x-9 $$
or
$$    x-12 < 2x-6 <  x-6, $$
which gives us the system
$$-6<x \quad\text{and}\quad x<0\quad\text{and}\quad x\ge 9.$$ Clearly, this system has no solutions.
Can you take it from here and write all remaining cases?

A: Assuming $x$ to be  a complex number
Using this,  $$||w| - |z|| ≤ |z - w| $$
$$\implies \big||2x-6|-|x-9|\big|\le |(2x-6)-(x-9)|=|x+3|$$
So we need $|x+3|<3$
If $x$ is purely real, $-3<x+3<3\iff -6<x<0$
If $x$ is purely imaginary $=ib$(say), where $b$ is real  $|x+3|=\sqrt{9+b^2}\ge3$
else $x=a+ib $ where $a,b$ are real and $ab\ne0$
$\implies |x+3|=\sqrt{(a+3)^2+b^2}<3\iff (a+3)^2+b^2<9$
So, $(a,b)$ lies inside a circle with center $(-3,0)$ and radius $3$ unit


text:
Q: How many points necessary for standard deviation? First off, I'm not a mathematician, and never took statistics in college, what I know about standard deviation I've learned in the past few weeks, so be gentle...
I'm working on a piece of software that calculates the standard deviation of the concentration of oxygen in a sample of water over time.  I'm using a rolling numerical array of 600 doubles taken at 1 second intervals (10 minutes of data).  By rolling array I mean that over time as the array fills, I increment a counter until it hits the limit of the array (600 elements), and then I reset the counter to zero to begin overwriting previous elements in the array.  In this manner, as the percent oxygen settles out, the standard deviation drops over time.  When the σ gets to the required level, the oxygen sensor takes a reading on the concentration of oxygen and then moves on to the next gas point.
My question is:  am I taking too many points?  It can take a very long time for the σ to drop to the level requested for the experiment before taking a calibration reading at that gas point.  Because it takes so long, I'm actually allowing the software to move to the next point when the σ is an order of magnitude greater than requested (σ = 0.02 vs σ = 0.002).
If I reduce the number of elements in the array, I think the calculation would move much faster because there are simply fewer elements to calculate and the resultant dataset is smaller to manipulate.  The software doesn't care what size the array is, it just calculates whatever size array is passed to it.  Would reducing the number of elements in the array reduce the accuracy of the calculation significantly?  Basically trading accuracy for speed?
For the piece of software I'm using to calculate standard deviation, you can find it here:  http://www.devx.com/vb2themax/Tip/19007.  It's been slightly modified from this example, but not very much:
Function ArrayStdDev(arr As Variant, Optional SampleStdDev As Boolean = True, _
Optional IgnoreEmpty As Boolean = True) As Double
Dim sum As Double
Dim sumSquare As Double
Dim value As Double
Dim count As Long
Dim Index As Long

' evaluate sum of values
' if arr isn't an array, the following statement raises an error
For Index = LBound(arr) To UBound(arr)
    value = arr(Index)
    ' skip over non-numeric values
    If value <> 0 Then
        ' add to the running total
        count = count + 1
        sum = sum + value
        sumSquare = sumSquare + value * value
     End If
Next

' evaluate the result
' use (Count-1) if evaluating the standard deviation of a sample
If count < 2 Then
ArrayStdDev = -9.99999

ElseIf SampleStdDev Then
    ArrayStdDev = Sqr((sumSquare - (sum * sum / count)) / (count - 1))
Else
    ArrayStdDev = Sqr((sumSquare - (sum * sum / count)) / count)
End If

End Function

I hope I've asked an answerable question and appreciate any insight offered.

A: Based on the various suggestions in the comments above, I reduced the number of elements in the array from 600 to 200.  Empirical testing showed me that anything below 200 and the calculation spanned too short of a sample and the accurate sensor would be triggered too soon (before the ml/L of oxygen measured σ had settled enough for it to be an accurate measurement).  This cascaded into modifying a number of other parameters for the water bath to accommodate the changes.  This wasn't unexpected, we are after all, in the experimental stages of this new type of calibration.  Thanks to the suggestions provided by you guys we're now in the tweaking part of the experiment, instead of the "why isn't this working right part".
So the answer to my question seems to be "200". I was hoping for 42...


text:
Q: transfer a "32bit float" variable I need to transfer many "32 bit float" variables from one DSP to another DSP through SPI.
However, the register is alaways 16bit that I need to split the "32bit float" variable into two parts.
I used the C type union like
union mytype {
  float a;
  uint16_t b[2];
};

It works well but I get the new problem that it is hard to know whether the received 16bit data is for b[0] or b[1] at startup. (The two DSP may power on at different time, so the 1st data may not always be b[0]).
I tried to split the 32bit float into 4 bytes, and when I transfer the 16bit, I add a tag before the 8bit data. That also works perfect. But I got performance slow down doubled.
Is there any way to transfer the "32bit float" by two 16bit data? I known my number range is within "0.0000001 ~ 1000000 "(both +/-). Or any other suggestions? I also think about hand-shake on SPI between two DSPs, but it seems to make it complex. I just want to capture the startup data is b[0], then I can receive everything in sequence.
THanks

A: Akin to @Cantfindname idea, but remove 2 bits out of the exponent.  No precision loss.
Further, reject any out of sequence pairs to prevent forming a float from halves that do not belong together.
I see @Patricia Shanahan has commented that.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void encode(float f, uint16_t *u16) {
  volatile union {
    float f;
    uint32_t u;
  } x;
  x.f = f;
  x.u -= 0x30000000u;
  u16[0] = 0x0000u | ((x.u >>  0) & 0x7FFFu);
  u16[1] = 0x8000u | ((x.u >> 17) & 0x4000u) | ((x.u >> 15) & 0x3FFFu);
}

int decode(const uint16_t *u16, float *f) {
  volatile union {
    float f;
    uint32_t u;
  } x;
  if (((u16[0] & 0x8000u) != 0x0000u) || ((u16[1] & 0x8000u) != 0x8000u)) {
    printf("Fail\n");
    return 1; // fail
  }
  x.u =  (u16[1] & 0x4000ul) << 17;
  x.u |= (u16[1] & 0x3FFFul) << 15;
  x.u |= (u16[0] & 0x7FFFu);
  x.u += 0x30000000u;
  *f = x.f;
  return 0;
}

int test(float f) {
  uint16_t u[2];
  encode(f, u);
  float f2;
  decode(u, &f2);
  if (f != f2) {
    printf("%.8e %.8e\n", f, f2);
  }
  return f != f2;
}

#include <math.h>

int main(void) {
  float f;
  for (f= 0.0000001; f <= 1000000.0; f = nextafterf(f,2*f)) {
    test(f);
    test(-f);
  }
  return 0;
  puts("Done");
}

Given the range "0.0000001 ~ 1000000", the MSBits of a binary32 float are always s011 to s100.  s is the sign bit.  By subtracting 3, the range is s000 s001.  That allows ignoring the middle 2 bits and then only 30 bits of the 32 bit float need to be maintained.  Sending 2 16-bit messages, each with a "phase" bit and a 15-bit portion of the 30-bits, allows total reconstruction of the original float.
Should the receiving end receive a message out-of-phase, it should ignore messages until a consecutive phase-0/phase-1 combination arrives.

By subtracting other values, at least 1 more bit can be ignored, allowing an additional sequence bit number, further insuring proper re-combination.  After all it appears only 340,000,000 combinations of the 4,294,967,296 floats are used.

A: Here is an idea if you can live with some minimal loss of precision on large numbers:
Lose the two least significant bits of the float (bits 0 and 1). Then rearrange the bits of the float so that:

*

*b[0] contains a 0 and bits 16..2 of the float

*b[1] contains a 1 and bits 31..17 of the float

Then, when you receive a 16 bit integer, check the most significant bit to see if it is a b[0] or a b[1], and reconstruct your float with 2 zeros on bits 0 and 1.
The loss of precision should be minimal on the range of numbers that you need, and this conversion only requires logical operations, so it should be fast.

A: If the payload data does not include NaNs, periodically send two all-bits-one chunks. When the receiver starts up, it scans the data until it sees such a pair, and then takes the next chunk with at least one zero bit as a b[0], the following chunk as its b[1] etc.
Each subsequent time it sees an all-bits-one pair, it should ignore it.
You would have a trade-off between how much bandwidth you waste sending unneeded all-bit-one pairs, and how much data the receive drops before getting in sync and processing real data on start-up.

A: if that range is absolute you only need 28 bits to express it. That leaves you 4 to do with what you want. I would reccomend making the first 2 bits of either uint16 an identifier so that when you recieve it you can perform some operation on it to decide which part of the integer it is.


text:
Q: React Build - Failed to compile. ./src/scss/style.scss ParserError: Syntax Error at line: 1, column 39 My react app build fails with the error that parsing style.scss fails.

I am using Docker to build the image. The relevant Dockerfile snippet is:
FROM node:lts-alpine3.16 as builder
WORKDIR /app
ENV PATH /app/node_modules/.bin:$PATH
COPY ./package.json /app/package.json
COPY . ./
RUN npm install
RUN npm install react-scripts@3.4.1 -g
RUN npm run build

The style.scss is valid. The deployment worked a couple of months ago with the same style.scss. Anyway, this is the style.scss. I am using CoreUI react template, if that is helpful.
// If you want to override variables do it here
@import "variables";

$enable-ltr: true;
$enable-rtl: true;

// Import CoreUI styles
@import "@coreui/coreui/scss/coreui";

// Import Chart.js custom tooltips styles
@import "@coreui/chartjs/scss/coreui-chartjs";
@import "@coreui/coreui/scss/mixins/_ltr-rtl.scss";

@import "~bootstrap/dist/css/bootstrap.min.css";

@import "rc-tree/assets/index.css";

Any idea or help will be appreciated.


text:
Q: Very large canvases in JavaFX2 My application has a very large Canvas contained by a ScrollPane.
At about 10 million pixels JavaFX starts throwing these null pointer exceptions during canvas operations:
at com.sun.javafx.sg.prism.NGCanvas$RenderBuf.validate(Unknown Source)
at com.sun.javafx.sg.prism.NGCanvas.initCanvas(Unknown Source)
at com.sun.javafx.sg.prism.NGCanvas.renderContent(Unknown Source)
at com.sun.javafx.sg.prism.NGNode.doRender(Unknown Source)
at com.sun.javafx.sg.prism.NGNode.doRender(Unknown Source)
at com.sun.javafx.sg.BaseNode.render(Unknown Source)
at com.sun.javafx.sg.prism.NGGroup.renderContent(Unknown Source)
at com.sun.javafx.sg.prism.NGRegion.renderContent(Unknown Source)
at com.sun.javafx.sg.prism.NGNode.doRender(Unknown Source)
at com.sun.javafx.sg.prism.NGNode.doRender(Unknown Source)
at com.sun.javafx.sg.BaseNode.render(Unknown Source)
at com.sun.javafx.sg.prism.NGGroup.renderContent(Unknown Source)
at com.sun.javafx.sg.prism.NGRegion.renderContent(Unknown Source)
at com.sun.javafx.sg.prism.NGNode.renderForClip(Unknown Source)
at com.sun.javafx.sg.prism.NGNode.renderRectClip(Unknown Source)
at com.sun.javafx.sg.prism.NGNode.renderClip(Unknown Source)
at com.sun.javafx.sg.prism.NGNode.doRender(Unknown Source)
at com.sun.javafx.sg.prism.NGNode.doRender(Unknown Source)
at com.sun.javafx.sg.BaseNode.render(Unknown Source)
at com.sun.javafx.sg.prism.NGGroup.renderContent(Unknown Source)
at com.sun.javafx.sg.prism.NGRegion.renderContent(Unknown Source)
at com.sun.javafx.sg.prism.NGNode.doRender(Unknown Source)
at com.sun.javafx.sg.prism.NGNode.doRender(Unknown Source)
at com.sun.javafx.sg.BaseNode.render(Unknown Source)
at com.sun.javafx.sg.prism.NGGroup.renderContent(Unknown Source)
at com.sun.javafx.sg.prism.NGNode.doRender(Unknown Source)
at com.sun.javafx.sg.prism.NGNode.doRender(Unknown Source)
at com.sun.javafx.sg.BaseNode.render(Unknown Source)
at com.sun.javafx.sg.prism.NGGroup.renderContent(Unknown Source)
at com.sun.javafx.sg.prism.NGRegion.renderContent(Unknown Source)
at com.sun.javafx.sg.prism.NGNode.doRender(Unknown Source)
at com.sun.javafx.sg.prism.NGNode.doRender(Unknown Source)
at com.sun.javafx.sg.BaseNode.render(Unknown Source)
at com.sun.javafx.tk.quantum.ViewPainter.doPaint(Unknown Source)
at com.sun.javafx.tk.quantum.AbstractPainter.paintImpl(Unknown Source)
at com.sun.javafx.tk.quantum.PresentingPainter.run(Unknown Source)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.runAndReset(Unknown Source)
at com.sun.prism.render.RenderJob.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumRenderer$PipelineRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

I think the solution must be to virtualize the Canvas. I imagine this is conceptually similar to how ListView is implemented.
Please point me to any examples you may know of that are similar to this or any pages that may provide guidance. (Virtual and virtualized don't seem to be helpful keywords for googling this topic)
Thank you

A: We faced the same problem.
The explanation why it happens, is here: https://community.oracle.com/thread/3549359
We solved the problem bypassing the video card, using the following JVM parameter:
-Dprism.order=sw
You may want to increase heap memory as well using -Xmx because it will use much more memory.


text:
Q: Is there a better wording option for "at the moment"? I'm trying to find a better synonym for "at the moment". I found "currently" and "at present". However, they don't sound better than "at the moment" in my sentence, which is:

At the moment, our ERP system is on AWS.

Are there alternatives to "at the moment" in this sentence?
I don't want to be limited only to use this wording every time. That's why I'm asking.


text:
Q: Package does not exist - Apache AnT I am trying to build a project with Apache Ant. I am kinda new to Ant. I have 2 jars that have some classes that i need to include in my project. My build.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<project default="run" name="authentification user">
   <target name="run" depends="compile">
      <java classname="Authentification">
         <classpath path="staging" />
      </java>
   </target>
   <target name="compile">
      <javac includeantruntime="false" srcdir="./src" destdir="staging" />
      <classpath>
         <pathelement path="lib/OASSoapWrapper-3.19.0-8778.jar" />
         <pathelement path="lib/OASSoapClient-3.19.0-8778.jar" />
      </classpath>
   </target>
</project>

My project directory structure is:
bin
src
lib
staging
build.xml
.classpath
.project

When I try to compile the build.xml with Ant I get "package does not exist error" but the package is in the jar files.


text:
Q: How to read this JSON String json =
[
 {"a":{"aa":"string","ab":"string"} },
 {"b":{"ba":"string","bb":"string"} }
]

I am trying to parse this data using JsonObject.
 When i use this code :
JSONStringer Js= new JSONStringer(json);
 Log.d("json", ""+Js);

it gives me this : (the first line of json but i want all data)
{"a":{"aa":"string","ab":"string"} }

How can I read this with Android ?

A: It is a JsonArray not a simple JsonObject
try this:
    JSONArray a = new JSONArray(json);
    for (int i = 0; i < a.length(); i++) {
        JSONObject row = a.getJSONObject(i);
        Log.d("json", ""+row);
    }

A: Actually, this JSON is kind of weird, as it wraps the array objects into one additional object each ("a" and "b"), which will make it hard to parse. It should look like this:

String json =      [   {"name":"a","aa":"string","ab":"string"},
  {"name":"b","ba":"string","bb":"string"} ]

And then you would parse it like this:
JSONArray root = new JSONArray(jsonString); //this is the above string
for(int i = 0; i < root.length(); i++){
    JSONObject current = root.getJSONObject(i);

    //Do the parsing here
}


text:
Q: how to switch on a nullable variable I have the following code
 switch (xn.SelectSingleNode("@type").InnerText)
            {
                case "int":
                case "int16":
                case "int32":v=int.Parse(xn.InnerText);break;
                default:v=xn.InnerText; break;

            }

The xn.SelectSingleNode("@type") may return null,
How can I declare switch(x) to be nullable

A: var type = xn.SelectSingleNode("@type");
if (type == null)
{
    // Handle the case
}
else
{
    switch (type.InnerText)
    {
        case "int":
        case "int16":
        case "int32":v=int.Parse(xn.InnerText);break;
        default:v=xn.InnerText; break;
    }
}

A: Strings, being objects, are always nullable. Just include null as a possibility in your switch statement:
switch (xn.SelectSingleNode("@type").InnerText)
{
    case "int":
    case "int16":
    case "int32":v=int.Parse(xn.InnerText);break;
    case null:
        // Handle case
        break;
    default:v=xn.InnerText; break;

}

A: I'd go with this (expanded for readability)

var node = xn.SelectSingleNode("@type");
var innerText = (node == null ? (string)null : node.InnerText);
switch (innertext)
...

A: switch (xn.SelectSingleNode("@type").InnerText) {
    case "int":
    case "int16":
    case "int32":
        v = int.Parse(xn.InnerText);
        break;
    default:
        v = string.IsNullOrEmpty(xn.InnerText) ? null : xn.InnerText; // Here you shall avoid the `NullReferenceException`.
        break;
}

Besides, if I understand correctly, v looks like it is an int, so you might wish to consider assigning it to 0 when the xn.InnerText returns null.
v = string.IsNullOrEmpty(xn.InnerText) ? 0 : xn.InnerText;


text:
Q: Understanding AWS-Config Rules and Confuguration Changes I am currently using the aws-cdk and my task is to create config rules for 15 or so rules that we want to watch and receive notifications on. Here is my code for reference:
 const vpcFlowLoggingBucket = new s3.Bucket(this,'vpcFlowLoggingBucket', {
              accessControl:s3.BucketAccessControl.LOG_DELIVERY_WRITE

            });
            const generalConfigRole = new iam.Role(this,  'generalConfigRole',{
              assumedBy: new iam.ServicePrincipal('config.amazonaws.com')
            });

            const cloudTrailEnabledRule = new ManagedRule(this, 'cloudTrailEnabledRule', {
              identifier: 'CLOUD_TRAIL_ENABLED'
            });
            const  iamPasswordPolicyRule = new ManagedRule(this, 'iamPasswordPolicyRule',{
              identifier: 'IAM_PASSWORD_POLICY'
            });
            const userGroupMembershipRule = new ManagedRule(this, 'userGroupMembershipRule',{
              identifier: 'IAM_USER_GROUP_MEMBERSHIP_CHECK'
            });

            const userPolicyRule = new ManagedRule(this,'userPolicyRule',{
              identifier: 'IAM_USER_NO_POLICIES_CHECK'
            });
            const rootAccountMfaEnabledRule = new ManagedRule(this, 'rootAccountMfaEnabledRule',{
              identifier: 'ROOT_ACCOUNT_MFA_ENABLED'
            });
            const accessKeysRotatedRule = new ManagedRule(this, 'accessKeysRotatedRule',{
              identifier:'ACCESS_KEYS_ROTATED',
              inputParameters: {
                maxAccessKeyAge: 100, //rule triggers off of config change and keys must be rotated within 100 days
                configurationChanges: true
              }

              //TODO reference your custom lambda for this
              //Parameters need to be specified here for the amount of days to rotate
            });
            const cloudTrailEncryptionRule = new ManagedRule(this, 'cloudTrailEncryptionRule' ,{
              identifier:'CLOUD_TRAIL_ENCRYPTION_ENABLED'
            });
            const defaultSecurityGroupEniRule = new ManagedRule(this, 'defaultSecurityGroupEniRule',{
              identifier:'EC2_SECURITY_GROUP_ATTACHED_TO_ENI'
            });

            const ebsVolumeEncryption = new ManagedRule(this, 'ebsVolumeEncryption',{
              identifier:'EC2_EBS_ENCRYPTION_BY_DEFAULT'
            });
            const rdsStorageEncryptionRule = new ManagedRule(this, 'rdsStorageEncryptionRule',{
              identifier: 'RDS_STORAGE_ENCRYPTED'
              //This may need the arn of the kms key used for encryption
            });

            const s3BucketLoggingEnabledRule = new ManagedRule(this, 's3BucketLoggingEnabledRule',{
              identifier: 'S3_BUCKET_LOGGING_ENABLED'
              //@aroesec may be able to use a custom rule here for this one and my lambda
            // TODO add custom lambda to this for future purposes
            });
            const s3BucketServerSideEncryptionRule = new ManagedRule(this, 's3BucketServerSideEncryptionRule',{
              identifier:'S3_BUCKET_SERVER_SIDE_ENCRYPTION_ENABLED'
              //@aroesec may be able to use a custom rule here for my lambda
            // TODO add custom lambda to this for future purposes
            });

            const vpcFlowLogsEnabledRule = new ManagedRule(this, 'vpcFlowLogsEnabledRule',{
              identifier:'VPC_FLOW_LOGS_ENABLED',
              inputParameters: {
                trafficType:'ALL', //vpcs must track all traffic (ALLOW and DENY) with this rule
                configurationChanges: true
              }
            });

            const vpcDefaultSecurityGroupRule = new ManagedRule(this, 'vpcDefaultSecurityGroupRule',{
              identifier:'VPC_DEFAULT_SECURITY_GROUP_CLOSED'
            });

            const mfaEnabledForConsoleAccessRule = new ManagedRule(this, 'mfaEnabledForConsoleAccessRule',{
              identifier: 'MFA_ENABLED_FOR_IAM_CONSOLE_ACCESS'
            });

            const rdsMultiAvailZoneRule = new ManagedRule(this, 'rdsMultiAvailZoneRule',{
              identifier:'RDS_MULTI_AZ_SUPPORT'
            });
          }

        }

My issue is this, when I try to use the configurationChanges parameter and set it to True. I am looking for that config rule to scan that resource group when it notices a change there. The reason I want to do this and not use the "frequency" parameter is that our client does not want scans as frequent as 24 hours. They want them to be around 2 week scans for every rule. My question is, 1. can I make the config rules scan less frequently then 24 hours? for example, maybe weekly? 2. Can I make a lambda trigger the config rule to scan? For example have the lambda check for vpc flow logs and if they are not there trigger the config rule to return "incompliant". OR 3. Can I just set configurationChange to true for every config rule and let aws handle it from there? I ask this specific question because I have read something about config recorder but am not sure how to use it or if it's even necessary. Thank you all in advance!

A: *

*The lowest frequency for config rule to scan is 24 hours, not slower than that if check the boto3 API.

*You would want the opposite, have config rule run periodically or when configuration changes.

*AWS doesn't know what to handle. If u go with configuration changes, you API or your code (through lambda) needs to know what to check for (ie. bucket is open to public), then when a public bucket is detected, lambda will catch it and report (PutEvaluationAP


text:
Q: Shell select data with SPARQL and upload to virtuoso I am trying to run the following script to load RDF data into a Virtuoso store. The script runs fine, but it appears that nothing is uploaded to Virtuoso, as the SPARQL query does not display any results. Any ideas why?
#!/bin/bash
/usr/local/virtuoso-opensource/bin/isql 1111 dba dba <<EOF
 SPARQL CREATE GRAPH <free>;
 ld_dir('/home/najib', 'term.rdf', 'free');
 rdf_loader_run();
 SPARQL SELECT * FROM <free> WHERE {?s ?o ?p};
 EOF

A: Quote your heredoc EOF:
#!/bin/bash
/usr/local/virtuoso-opensource/bin/isql 1111 dba dba <<'EOF'
SPARQL CREATE GRAPH <free>;
ld_dir('/home/najib', 'term.rdf', 'free');
rdf_loader_run();
SPARQL SELECT * FROM <free> WHERE {?s ?o ?p};
EOF

As per man bash:

No  parameter  expansion, command substitution, arithmetic
  expansion, or pathname expansion is performed
         on word.  If any characters in word are quoted, the delimiter is the result of quote  removal  on  word,
         and  the  lines in the here-document are not expanded.  If word is unquoted, all lines of the here-docu‐
         ment are subjected to parameter expansion, command substitution, and arithmetic expansion.  In the  lat‐
         ter case, the character sequence \ is ignored, and \ must be used to quote the characters \, $,
         and `.

PS: Also make sure there is no space before closing EOF


text:
Q: Laravel3: Loading a content inside a content dynamically I have a form. When user submits the form and gets error, I show it like this:
Register Controller
return View::make('theme-admin.user_add')->with('error_msg', validation->errors->first());

register.blade.php
@if($error_msg !== null)

            {{ $error_msg }} <-- Error message is visible here.

@endif

//
    Actual HTML Form
//

However, I want to move that error div into a blade file. (error.blade.php) and I want to call it with parameters when there is an error.
It will look like this.
NEW register.blade.php
{{ MESSAGE_CONTENT }} //This should be replaced with error.blade.php dynamically
//
    Actual HTML Form
//

MESSAGE_CONTENT will be included via error.blade.php
error.blade.php

            {{ $message }} <-- Error message is visible here.

Let's say form failed and I got some errors. I will load error.blade.php so messages will get RED background etc.
Something like this;
return View::make('theme-admin.user_add')->with(message_content', (Load error.blade.php here))->with('message', $validation->errors->first();

If the form succeeds, I'll just load success.blade.php in messages area and messages will look with GREEN background.
 return View::make('theme-admin.user_add')->with(message_content', (Load success.blade.php here))->with('message', 'You successfully registered');

You probably got the logic.
How can I do this?
Ps. Image example: http://i.imgur.com/QExAiuA.png

A: A clean solution may be to have a simple alert object with a type and msg.
//in controller
$alert->type = 'error'; // or 'success'
$alert->class = 'red'; // or 'green'
$alert->msg = $validation->errors->first(); // or 'You successfully registered'
 return View::make('theme-admin.user_add')->with('alert', $alert);

//register.blade.php
@include('alert')

//Actual HTML Form

//alert.blade.php
@if(isset($alert))

class}} hideit max">

            {{ $alert->msg }}

          class}}">

@endif

A: You should create your view (View::make()) in a route defined for GET, and then handle your form input in your POST route:
//routes.php
Route::get('admin/adduser', array('as' => 'adduser', 'do' => function()
{
    return View::make('theme-admin.user_add');
}));

//route for handling form input
Route::post('register', array('before' => 'csrf', function()
 {
     $rules = array(
         //your vailidation rules here..
     );

     $validation = Validator::make(Input::all(), $rules);

     if ($validation->fails())
     {
         //re-populate form if invalid values, so add flashing input by with_input()
         //also pass errors by using with_errors
         return Redirect::to('adduser')->with_input()->with_errors($validation);
     }
     else {
         //use the named route we defined in Route:get above
         return Redirect:to('adduser')->with('message', 'Successfully added the new user!');
     }
 }));

There is no need to create new views for dislaying error and success messages. If you want to seperate your success and error into their own blade templates then you could use the following in your adduser.blade.php:
//adduser.blade.php
@if($errors->has())
    @include('errormsg'); //use {{ $errors->first() }} or @foreach($errors->all() as $message) to print error message(s)
@else
    @include('success'); //use {{ $message }} to print success
@endif

However you can also use sections in your view, and instead put both the success and error message inside the same view:
//feedback.blade.php
@section('error')
    {{ $errors->first() }}
@endsection

@section('success')
    {{ $message }}
@endsection

//adduser.blade.php
@include('feedback');

@if($errors->has())
    @yield('error');
@else
    @yield('success');
@endif

Hope that helps.

A: I found the solution myself. I needed Nested Views feature.
$view = View::make('home');
$view->nest('content', 'orders', array('orders' => $orders));

Refer to Laravel documentation for more information.


text:
Q: Updating tkinter label from module, what to search to learn how to do it A quick description to make clear what I am trying to ask as I may not be using the correct terminology.
I have made a basic gui that:
(1). gives an options menu (2). Has button that uses the options menu choice to call a module that performs a calculation that outputs a variable from the module onto the console. (3). Has a label that updates after pressing the button
However;
I would like to have a label update with a variable created from the module (rather than go to the console).
I have tried to use 'getattr' without success.
Project background - I am at the start of trying to learn my first language, I have tried and failed before, so this time I am trying to learn by creating my own project. The project is a bolted joint calculator; pick your bolt diameter from a drop-down menu, hit a button and then it will display the area as a label.
The Question: How do I call a variable that is calculated in a module?
import tkinter as tk
from tkinter import *
import pandas as pd
import boltMod2

def show(whatever):
   choice = variable.get()

def temp():
    temps = boltMod2.calcSize(variable.get())
    lab.config(text = "Area is " + variable.get())# i would like to read 'minA' variable from boltMod.calcsize instead

window =Tk()
window.geometry("300x200")

#oprtions for Dropdown menu
sizes = ['M6', 'M8', 'M10']
choice = sizes[0]
variable = StringVar()
variable.set(sizes[0])

#dropdown menu
popupMenu1 = OptionMenu(window,
                           variable,
                           *sizes,
                           command = show)
popupMenu1.grid(column=0, row=1)

#button
myButton = Button(window,
                  text ="Calculate",
                  command = temp)
myButton.grid(column=1, row=2)

lab = Label(window,
            text = "select bolt ")
lab.grid(column=0, row = 3)

window.mainloop()

then the module "boltMod" is:
def calcSize(metricsize):
    print(metricsize + " is your bolt size")
    minA= 3.142*(8/2)**2 #normally values read off csv files for the
selected bolt
    print("The area is ")
    print(minA)

A: what do you mean by calculated in a module? can you include your code?
here is some code that seems to do what you are saying (formula is just ^2 instead of whatever you are actually doing):
from tkinter import *
from tkinter import ttk

root = Tk() #create root GUI
root.title("Name") #Change window title
root.geometry('800x500') #Change window size

def ButtonClick(id, output):
    if id == "o1": #if opt 1
        output.config(text="output: {}".format(1**2)) #1^2
    elif id == "o2":
        output.config(text="output: {}".format(2**2))
    else:
        output.config(text="output: {}".format(3**2))

#Main Frame---------------------------------------------------------------------
frm = ttk.Frame(root, padding=225) #Create frame
frm.grid(row=0,column=0) #grid the frame
#Prompt-------------------------------
global output
output = ttk.Label(frm, text="output: ") #show prompt
output.grid(column=0, row=0)
#Buttons------------------------------
#opt1
o1 = ttk.Button(frm, text="Option 1") #add EOL directory button
o1.grid(row=1, column=0) #grid the button
o1.config(command=lambda output=output: ButtonClick("o1", output)) #reference button press function
#opt2
o2 = ttk.Button(frm, text="Option 2") #add EOL directory button
o2.grid(row=2, column=0) #grid the button
o2.config(command=lambda output=output: ButtonClick("o2", output)) #reference button press function
#opt3
o3 = ttk.Button(frm, text="Option 3") #add EOL directory button
o3.grid(row=3, column=0) #grid the button
o3.config(command=lambda output=output: ButtonClick("o3", output)) #reference button press function

root.mainloop() #execute

Also, you don't need the "output" to be an input to the ButtonClick() function it depends on the program's needs.


text:
Q: when i am trying to extracting 400Mb tar file using java code it's getting( java.io.IOException: open failed: ENOENT (No such file or directory) ) When I am trying to extract a 400Mb tar file using java code it's getting java.io.IOException: open failed: ENOENT (No such file or directory) and it is not extracting.
 private static void unTar(final File inputFile, final File outputDir){

       // LOG.info(String.format("Untaring %s to dir %s.", inputFile.getAbsolutePath(), outputDir.getAbsolutePath()));

        try {
            List<File> untaredFiles = new LinkedList<File>();
            InputStream is = new FileInputStream(inputFile);
            TarArchiveInputStream debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", is);
            TarArchiveEntry entry = null;
            while ((entry = (TarArchiveEntry)debInputStream.getNextEntry()) != null)
            {
                File outputFile = new File(outputDir, entry.getName());
                byte[] content = new byte[(int) entry.getSize()];
                if (entry.isDirectory())
                {
                    //LOG.info(String.format("Attempting to write output directory %s.", outputFile.getAbsolutePath()));
                    if (!outputFile.exists())
                    {
                        //LOG.info(String.format("Attempting to create output directory %s.", outputFile.getAbsolutePath()));
                        if (!outputFile.mkdirs())
                        {
                            throw new IllegalStateException(String.format("Couldn't create directory %s.", outputFile.getAbsolutePath()));
                        }
                    }
                } else
                {
                   // LOG.info(String.format("Creating output file %s.", outputFile.getAbsolutePath()));
                    FileOutputStream outputFileStream = new FileOutputStream(outputFile);
                    IOUtils.copy(debInputStream, outputFileStream);
                   // IOUtils.write(content, outputFileStream);
                    outputFileStream.close();
                }
                untaredFiles.add(outputFile);
            }
            debInputStream.close();

            //return untaredFiles;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ArchiveException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

I have followed the code here http://thinktibits.blogspot.in/2013/01/read-extract-tar-file-java-example.html
Can any one help me?


text:
Q: collinearity reduction methods I am fitting regression models using closely related and highly collinear critical variables.
I have used a few collinearity-reduction techniques, such as:

*

*PCA,

*variable selection.

Nevertheless, there is scope for further reduction.
Since my primary goal is to perform do inference on the variables, dimensionality reduction and variable selection are not the best options for me, because they make the variables and the models harder to interpret or even outright uninterpretable. Sadly, regularization is not an option for me given the specific type of regression model and the specific software package I am using.
Are there any other collinearity reduction methods that preserve as much information as possible while keeping the information contained in each of the critical variables distinct?

A: I am not sure what you mean by "collinearity reduction".  Scaling will not affect it. If you want to keep your original variables, then the usual methods of dealing with collinearity are to used some form of biased regression.
Ridge regression is, I think, the most usual tool for dealing with colinearity while keeping the original variables. It doesn't lower collinearity, per se (nothing can do that and keep the original variables) but it reduces the inflation of variance of the estimators that is one of the main negative consequences of collinearity.
Another option, of course, is to drop some variables. If the collinearity consists of a relation between two variables, then you could drop either.  If it consists in one variable being close to a linear combination of others, then you might want to drop the single variable.


text:
Q: Как не позволять клавиатуре закрыться при нажатии на кнопку назад или OK? Как не позволять клавиатуре закрыться, при нажатии на кнопку назад или OK ?
Я пробовал следующее действие:
EditText yourEditText= (EditText) findViewById(R.id.ed);
    InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

с данными вариантами:

*

*imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);

*imm.toggleSoftInputFromWindow( yourEditText.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);

*imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);

A: Если вам нужно, чтобы при нажатии кнопки "Назад" был совершен переход в предыдущее активити и на экране осталась клавиатура. То проще всего в onResume этого предыдущего активити заново показать клавиатуру.
EditText editText= (EditText) findViewById(R.id.ed);
InputMethodManager imm = (InputMethodManager) this.getSystemService(Service.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, 0);
editText.requestFocus();

А чтобы не нажимать кнопку "Назад" дважды, переопределите onBackPressed, чтобы почистить стек активностей и запустить нужную активность через интент.


text:
Q: Text logo to Image logo - Joomla 1.5 template Wonder if any of the good folks can assist..
I have installed a basic theme Joomla 1.5 template but looking to change the text writing of the site name to our image logo.
Here is the code in the source at the moment.

<a href="<?php echo $baseurl = JURI::base();?>"><?php echo $mainframe->getCfg('sitename');?>

Tried img src tag etc but no success...
What will be the right way of doing this create a custom html module and position there? Or is there an alternate php way one is missing?
Thanks for your assistance in advance.
Kof

A: If you need to change the site name go to joomla configuration and change it there
or you can modify the configuration.php file or
simply change the html code :

<a href="<?php echo $baseurl = JURI::base();?>"><?php echo JText::_('MY_NEW_SITE_NAME');?>

A: Currently your site is set up to display the site name in that div, that is controlled in the Global Configuration. If the text displays and you want to change it, look in Site > Global Configuration > Site > Site Settings > Site Name.
If the text name is not displaying, it is because the logo is being placed in to the div as a background image. You should look in your template CSS to see what you have defined for #logo. You can also use Chrome/Firefox, right click on the current logo and select inspect element. that should also show you the CSS for the element and tell you where the image is coming from.