text:
Q: How can i fix POST methods issue in redirect URLs for APIs in android and retrofit? I am using some url for my apis which redirect to other one but i have some  problem about POST methods ..
It gives me this message in the log:
405 Method Not Allowed

I am using retrofit in my app ..
How can i fix it to accept POST methods also?
This is my code:
public static Retrofit getClient() {
        pref = getContext().getSharedPreferences(getContext().getPackageName(), 0);
        languageSetting = pref.getString("languageSetting", null);

        if (retrofit == null) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();

            logging.setLevel(HttpLoggingInterceptor.Level.BODY);

            OkHttpClient.Builder httpClient = new OkHttpClient.Builder()

                    .connectTimeout(5, TimeUnit.MINUTES)
                    .readTimeout(5, TimeUnit.MINUTES);

            httpClient.addInterceptor(logging);
//            httpClient.followRedirects(false);

            httpClient.addInterceptor(chain -> {

                        Request original = chain.request();
                        Request request = original.newBuilder()
                                .header("Content-Type", "application/x-www-form-urlencoded")
                                .header("Accept", "application/json")
                                .header("Lang", languageSetting != null ? languageSetting : "EN")
                                .header("TokenKey", Constants.TOKEN)
                                .method(original.method(), original.body())
                                .build();

                        return chain.proceed(request);
                    }
            );
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .client(httpClient.build())
                    .build();
        }
        return retrofit;
    }

I have tried it on post man and same issue but when i activate this option, it works fine :

The question now how to activate Follow Original HTTP method in android & Retrofit?


text:
Q: How do I change the font on the login screen? I want to change the font in the login screen - where is the configuration for that?

A: I will recommend the two best ways to change the default font of lightdm.
Open terminal and run the command pkexec lightdm-gtk-greeter-settings
if it doesn't work for you, you need to install it manually using the command sudo apt install lightdm-gtk-greeter-settings and after installation , run  pkexec lightdm-gtk-greeter-settings.A window will appear where you can configure the lightdm.

Another method is to change edit the conf using the dconf-editor.
Open dconf-editor and search greeterfrom the search box
.
Click on the first option that appears and configure all your lightdm settings there.
If you don't have dconf-editor installed , install it by sudo apt install dconf-editor
This is not the answer for question asked 8 years ago but for the current users who are facing this problem.

A: Start by opening up a terminal, start typing "terminal" in your unity dash to see the option or press ctrl+alt+t
Lets go to the correct directory:
cd /etc/lightdm

Now lets make a backup of the file before we make any changes:
sudo cp unity-greeter.conf unity-greeter.conf.bak

Now we need to open up this file and see whats changed, type/copy this:
gksu gedit /etc/lightdm/unity-greeter.conf

The file should look like below:
#
# background = Background file to use, either an image path or a color (e.g. #772953)
# logo = Logo file to use
# theme-name = GTK+ theme to use
# font-name = Font to use
# xft-antialias = Whether to antialias Xft fonts (true or false)
# xft-dpi = Resolution for Xft in dots per inch (e.g. 96)
# xft-hintstyle = What degree of hinting to use (hintnone, hintslight, hintmedium, or hintfull)
# xft-rgba = Type of subpixel antialiasing (none, rgb, bgr, vrgb or vbgr)
#
[greeter]
background=/usr/share/backgrounds/warty-final-ubuntu.png
logo=/usr/share/unity-greeter/logo.png
theme-name=Ambiance
icon-theme-name=ubuntu-mono-dark
font-name=Ubuntu 11
xft-antialias=true
xft-dpi=96
xft-hintstyle=hintslight
xft-rgba=rgb

Then save and log out.

A: In case you want to customize your Display manager lightdm may not be the ideal choice.
I would replace it with mdm (themability, graphical configuration tools, etc) , which is a bit more bloated but you won't notice any difference except it's running on a 12 year old notebook.
Instructions to do so can be found here:
How can I replace LightDM with MDM?

A: You can try the method mentioned here: https://askubuntu.com/a/224060. This command will complain "No protocol specified" but should work (omit exclamation mark in the end of the command). Though it changes only the font of the top panel in greeter.
Also you can get the list of other settings which can be adjusted with this method:
sudo -u lightdm dbus-launch gsettings list-keys com.canonical.unity-greeter

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular2 testing: What's the difference between a DebugElement and a NativeElement object in a ComponentFixture? I'm currently putting together some best practices for testing Angular 2 apps on a component level.
I've seen a few tutorials query a fixture's NativeElement object for selectors and the like, e.g.

it('should render "Hello World!" after click', async(() => {
    builder.createAsync(HelloWorld).then((fixture: ComponentFixture<HelloWorld>) => {
        fixture.detectChanges();
        let el = fixture.nativeElement;
        el.querySelector('h1').click();
        fixture.detectChanges();

        expect(el.querySelector('h1')).toHaveText('Hello World!');
    });
}));

However, in juliemr's Angular 2 test seed she accesses the NativeElement through a parent DebugElement object.

it('should render "Hello World!" after click', async(() => {
    builder.createAsync(HelloWorld).then((fixture: ComponentFixture<HelloWorld>) => {
      fixture.detectChanges();
      let compiled = fixture.debugElement.nativeElement;
      compiled.querySelector('h1').click();
      fixture.detectChanges();

      expect(compiled.querySelector('h1')).toHaveText('Hello World!');
    });
}));

Are there any specific cases you'd use a fixture's debugElement.nativeElement over its nativeElement?

A: .nativeElement() returns DOM tree whereas debugElement returns a JS object (debugElement tree). debugElement is a Angular's method.
.nativeElement() is Browser specific API that returns or give access to DOM tree. But what if application is running on non-browser platform (such as server or web-worker), in that case .nativeElement() may throw error.

If we are sure that our application will run on browser only, then
  unhesitantly we can use let el = fixture.nativeElement. But if we
  are not sure about the platform then to be on safer side use let le =
  fixture.debugElement because it returns a plain JS Object.

A: *

*nativeElement returns a reference to the DOM element

*DebugElement is an Angular2 class that contains all kinds of references and methods relevant to investigate an element or component (See the source of DebugNode and DebugElement

A: to add on to what has been mentioned already :
  abstract class ComponentFixture {
  debugElement;       // test helper
  componentInstance;  // access properties and methods
  nativeElement;      // access DOM
  detectChanges();    // trigger component change detection
}

source: https://github.com/angular/angular/blob/a7e9bc97f6a19a2b47b962bd021cb91346a44baa/modules/angular2/src/testing/test_component_builder.ts#L31

A: Take a look at Angular discussion about this topic and related PR.
Mainly:
fixture.componentInstance == fixture.debugElement.componentInstance;
fixture.nativeElement == fixture.debugElement.nativeElement;


text:
Q: What is the overhead of using shipped production server in docker? I'm new to containerization and I'm facing some inner questions.
I saw some examples of docker images which are shipping apache2/wgsi with the django application. Is this the best way to procede ? Each container should have their own production server ? I guess this creates a lot of overhead on the host system.
Is there a way to use the host system production server to host different images ?


text:
Q: fs.mkdir vs child_process.exec(mkdir) which one is more efficient I need to create a dir in nodejs using the 'fs' module but at same time the directory can be created using child_process.exec.
I tried looking in the fs.mkdir code and it went down to node_file.cc and I guess it creates a new v8 environment. I am not sure how this works internally.
And looking at nodejs fs docs  - it creates a subshell - which I guess is fork + exec call.
Was not sure which one is more efficient ?

A: You should always prefer the in-language version.  I am certain that it does not create a shell just to run mkdir() on common platforms.


text:
Q: How to check if a radio button is checked to display a button to continue I have two radio buttons to select a shipping method upon checkout. I want to check with jquery if one of these radio buttons checked, then the button to process with checkout will appear, otherwise, it will be hidden.

HTML/PHP

<form method="get">

   <input type="radio" name="dm_shipping_option" id="tttm_courier" value="1" onclick="getCourier(1);" />
   <?php echo $shipping_costs; ?>€ <?php echo getValue('name','banners',3); ?>
   <?php echo "
"; ?>
   <?php echo getValue('content','banners',3); ?>

   <input type="radio" name="dm_shipping_option" id="client_courier" value="0" onclick="getCourier(0);" />
   <?php echo getValue('name','banners',2); ?>
   <?php echo "
"; ?>
   <?php echo getValue('content','banners',2); ?>

</form>

Jquery

A: You can try this:
if (!isCheckedTTCourier) {
    $("#submit-btn").hide();
} else {
    $("#submit-btn").show();
}

A: Try this! I have made a sample snippet for you which works as expected. you can toggle the button based on condition.

function getCourier(id) {
  var isCheckedTTCourier = $('#tttm_courier').prop('checked');

  var isCheckedCourier = $('#client_courier').prop('checked');

  $("#submit-btn").toggle(isCheckedTTCourier || isCheckedCourier);
};
#submit-btn {
  display: none;
}

<form method="get">
   Radio Button 1
   <input type="radio" name="dm_shipping_option" id="tttm_courier" value="1" onclick="getCourier(1);" />

    Radio Button 2
   <input type="radio" name="dm_shipping_option" id="client_courier" value="0" onclick="getCourier(0);" />

    <button id="submit-btn">Submit</button>
</form>

A: Just a little change to your code, hope it helps.
if($('#tttm_courier').attr('checked', true)){
    $("#submit-btn").css('display','block');
}else {
    $("#submit-btn").css('display','none');
}

A: You can use .toggle(condition):
$("#submit-btn").toggle(isCheckedTTCourier || isCheckedCourier);

A:
$(#id).is(':checked')

This will give whether a particular button is checked or not


text:
Q: how to add a new table entry in surefire reports I am new to maven. So finding it difficult to cope it with. I have two questions:

*

*Is there any way to add new contents in the maven surefire report
plugin like new table etc. I want to customize the reports according
to my need.

*I am using buildnumber plugin to get the unique run id
for each run but this id is not getting reflected in the reports. Is
buildnumber plugin only works with subversion?

The pom is;
<build>
<finalName>${project.artifactId}-${project.version}-r${buildNumber}</finalName>
  <plugins>
    <plugin>
     <groupId>org.codehaus.mojo</groupId>
        <artifactId>buildnumber-maven-plugin</artifactId>
        <version>1.0-beta-3</version>
        <executions>
          <execution>
            <phase>validate</phase>
            <goals>
              <goal>create</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <doCheck>true</doCheck>
          <doUpdate>false</doUpdate>
          <format>${project.version}.{0,number}</format>
          <items>
           <item>buildNumber</item>
          </items>
        </configuration>
      </plugin>
  </plugins>
</build>

I have one more query:
3-> If i make batch file or an exe file of the complete test suites can i run it on many JVM simultaneously for example with an eclipse i am running one JVM. But if am not using eclipse and just running the testsuite batch file directly can JRE instantiate many JVM instances. And if it is possible, do i need to associate each test suite with .m2 repository.

A: To get to your first question: Unfortunately not. You can use them as they are or you need to write your own maven-surefire-report-plugin. But the question is what you exactly want to customize.
To you second question: The build-number-plugin is used to create a build number which usually is used during creation of MANIFEST.MF files etc. Furthermore the buildNumber plugin works also with Git, Hg etc. But the question is what you like to achieve in this case. The most important information in Maven are the groupId, artifactId and the version.
Update: BTW. Update the buildnumber-plugin version (1.0).
Update: Take a look here: http://maven.apache.org/plugins/maven-surefire-report-plugin/usage.html


text:
Q: how to save a binary output of a Process and save it to file I'm running an exe file through Process, which generates binary data, and I want to save that data into a file.
while using usual proposed methods of doing so (Sync and async) I've ran across couple of hurdles, and I hope you can help me out.
I've run the commands through code, and through prompt, and here are my observations
1) When using sync methods, the file is by default encoded with UTF-8 (File ends up larger than the prompt one
2) when changing the encoding method to ASCII/default the encoding seems to be handled properly and file seems to be similar in size to the prompt one, unfortunately the process designed to read that file considers it "errored"
3) using async method and saving using BinaryWriter creates a seemingly accurate file, but still cant be read by output. I believe my error might be how I append "new line"
below is my code for async method. While sync one just has "Output.ReadToEnd()" between start/stop.
code:
        private void createOCTree()
    {
        //Create process
        var cmd = @"oconv.exe";                         //OUTPUT IS C++ binary
        var arguments = @" C:\RadianceGeometry.rad";
        var outputFile = @"C:\test.oct";
        var workingDir = m_FileData.TemporaryFilesFolder;

        ProcessStartInfo cmdStartInfo = new ProcessStartInfo();
        cmdStartInfo.RedirectStandardInput = false;
        cmdStartInfo.RedirectStandardError = false;
        cmdStartInfo.RedirectStandardOutput = true;
        cmdStartInfo.UseShellExecute = false;
        cmdStartInfo.CreateNoWindow = true;
        cmdStartInfo.FileName = cmd;                    ////file name
        cmdStartInfo.Arguments = arguments;             ////arguments
        cmdStartInfo.WorkingDirectory = @"C:\";         ////working dir

        using (StreamWriter writer = new StreamWriter("C:\\testStream.oct"))
        {
        }

        var process = new Process();
        process.StartInfo = cmdStartInfo;

        process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
        process.Start();
        process.BeginOutputReadLine();
        process.WaitForExit();
    }

    private void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
    {
        try
        {
            byte[] bytes = Encoding.Default.GetBytes(outLine.Data);
            byte[] newLine = Encoding.Default.GetBytes("\n");
            AppendData("C:\\testStream.oct", bytes);
            AppendData("C:\\testStream.oct", newLine);     ////otherwise all is in one line
        }
        catch { }   ////possibly last line is not properly handled
    }

    private static void AppendData(string filename, byte[] bits)
    {
        using (var fileStream = new FileStream(filename, FileMode.Append, FileAccess.Write, FileShare.None))
        using (var bw = new BinaryWriter(fileStream))
        {
            bw.Write(bits);
        }
    }

my suspicion is that either I'm missing something with my "Try/Catch", or that newlines should be parsed differently.
Set all paths to c:\ just to make it easier to read (instead of using variables, or actual paths).
edit:addition; I've noticed when comparing prompt output with the one from code, and they are the same, except that first char of some lines "output" is "?" instead of random "glyphs" in the working file.
edit: added comparison screen shots.
code comparison:
with newline: https://ibb.co/HpztQ0Q
without newline: https://ibb.co/Lvcr9pH

A: the way I Got it to work is use cmd as the command, and
in the argument field, I used /c" flag as described here: What does cmd /C mean?
    String exeFileName = @"cmd.exe";
    String Arguments = @"/c oconv.exe C:\test\radgeom.rad > c:\test\scene.oct";


text:
Q: Git: How can I jump back to a previous commit, thus undoing recent changes I've made? I've made 4 commits in my branch and pushed to Github. The last 3 of those commits contain changes that should not have been made. I want to 'jump back' to the first commit, removing all my un-wanted changes from the branch completely.
So far I have tried
git reset --hard 6b9b9baa6758598ca2ed48d5e029b4b5a2a7f194

and
git revert <SHA>

but these seem to do nothing - the unwanted changes remain in my pull request.
Does anyone know how I could go about this?
UPDATE:
I need to go back to commit 6b9b9baa6758598ca2ed48d5e029b4b5a2a7f194. Log looks like:
commit 0a90687022fb458de36ac3ff3b3fd3f3920f6b0d
Author: Me
Date:   Thu May 31 10:04:36 2018 +1000

    Removed svg

commit 7dbcceb6e294572a531d84837753f5698bf192f6
Author: Me
Date:   Thu May 31 10:02:12 2018 +1000

    Removed icon from icons directory

commit 97cfd16c87ea280a4e6a7570272157e86195542e
Author: Me
Date:   Wed May 30 17:27:55 2018 +1000

     Added icons

commit 6b9b9baa6758598ca2ed48d5e029b4b5a2a7f194
Author: Me
Date:   Wed May 30 16:27:33 2018 +1000

    Updated css

A: You need to push to Github after reset or revert.
To remove commits in the remote branch, you will need to push using force flag (*) after resetting.
Another option if to revert all 3 commits and push. Note that the bad commits will remain in the remote branch history.
(*) Not recommended if you do not know the consequences.

A: You need to push after reset or revert
1) in case of reset you need to push force (because you are changing remote history) as below:
git push origin <branch name> -f

2) in case of revert need simple push as below:
git push origin <branch name>

It is always better to user revert in place of reset.
As it will create extra(reverse) commits of your commit and it will not resetting history of git.


text:
Q: Convert mongoDB Aggregation Query to Spring data mongo template Aggregation I am fairly new to MongoDb and Spring-data-Mongo.
After doing a lot of research I was able to get the desired result in MongoDB using the below query, but now I am finding it very difficult to implement the same logic in the Spring-data-Mongo template.
The logic is pretty simple:
I have 2 date fields and 2 integer fields in the document.
expireLastModifiedD (Integer Represents Days), expireLastUsedD: (Integer, Represents days), lastModified: (Date type), lastUsed: (Date Type).
I need to find Documents that satisfy the below expression.
lastModified+expireLastModifiedD < NOW && lastUsed + expireLastUsedD < NOW

I have created a MongoDB Query as under.
[
  {
    $project: {
      expireLastModifiedD: 1,
      expireLastUsedD: 1,
      lastModified: 1,
      lastUsed: 1,
      NowSubtractLastModified: {
        $toInt: {
          $divide: [
            {
              $subtract: [
                new ISODate(),
                "$lastModified"
              ]
            },
            1000 * 60 * 60 * 24
          ]
        }
      },
      NowSubtractLastused: {
        $toInt: {
          $divide: [
            {
              $subtract: [
                new ISODate(),
                "$lastUsed"
              ]
            },
            1000 * 60 * 60 * 24
          ]
        }
      }
    }
  },
  {
    $project: {
      expireLastModifiedD: 1,
      expireLastUsedD: 1,
      lastModified: 1,
      lastUsed: 1,
      NowSubtractLastModified: 1,
      NowSubtractLastused: 1,
      isExpireLastModifiedDLTNowSubtractLastModified: {
        $lt: [
          "$expireLastModifiedD",
          "$NowSubtractLastModified"
        ]
      },
      isExpireLastUsedDLTNowSubtractLastused: {
        $lt: [
          "$expireLastUsedD",
          "$NowSubtractLastused"
        ]
      }
    }
  },
  {
    $match: {
      isExpireLastModifiedDLTNowSubtractLastModified: true,
      isExpireLastUsedDLTNowSubtractLastused: true
    }
  }
]

I need help creating the above MongoDb query in Spring-data Mongo Template using Aggregation.

A: After Lot of Research, I figured it out.
    Instant now = Instant.now();
    Timestamp current = Timestamp.from(now);

    ProjectionOperation projectionOperation = Aggregation.project("lastUsed", "expireLastUsedD", "lastModified", "expireLastModifiedD")
            .andExpression("([0] - lastModified)", current).divide(24 * 60 * 60 * 1000).as("lastModifiedFromNowD")
            .andExpression("([0] - lastUsed)", current).divide(24 * 60 * 60 * 1000).as("lastUsedFromNowD");

    ProjectionOperation projectionOperation1 = Aggregation.project("lastUsed", "expireLastUsedD", "lastModified", "expireLastModifiedD", "lastModifiedFromNowD", "lastUsedFromNowD")
            .andExpression("expireLastModifiedD < lastModifiedFromNowD").as("isExpLstModLTLastModFromNowD")
            .andExpression("expireLastUsedD < lastUsedFromNowD").as("isExpLstUsdLtLstUsdFromNowD");

    MatchOperation matchOperation = Aggregation.match(new Criteria().andOperator(
            Criteria.where("isExpLstModLTLastModFromNowD").is(true), Criteria.where("isExpLstUsdLtLstUsdFromNowD").is(true)));

    TypedAggregation<UrlMap> agg = Aggregation.newAggregation(UrlMap.class,
            projectionOperation, projectionOperation1, matchOperation);


text:
Q: C# iTextSharp: How to specify Spot Colors I am using iTextSharp to add text to PDF files.
The Text Color is usually specified as CMYK, but will require the need to specify spot/special colors.
There is an example here
In the Line:
PdfSpotColor spotColour = new PdfSpotColor("PANTONE 100 CV", 0.5f, new GrayColor(0.9f));

Does anyone know the description and meaning of the paramaters
so we have (string name, float tint, Color altcs)
I assume the name is the Color Separation Name. Not 100% sure what tint is or its range, is that some kind of alpha/transaparency value? and is the altcs a display color, rather than the separation layer used for actual printing?

A: I just pulled up somiTextSharp code I had and my method parameters are different for the PdfSpotColor.  I only have 2 parameters, and there are no overloads.  The example you gave is from the original java project.  I think that is why they are different.
Here is what I have:
var color = new PdfSpotColor("spotColorName", new BaseColor(50, 50, 50));

... where the numbers are the red, green blue.  The BaseColor constructor has overloads, so you can even give it a .NET Color if you want.
Unfortunately, I don't know much else about this class.  Hope that helps!


text:
Q: If $m(A) \to 0,$ then $\int_A f\,dx \to 0$
Let $f$ be an integrable non-negative function defined on a measurable set $E.$
  Then, for $A \subset E,$ if $m(A) \to 0,$ then $$\int_A f\,dx \to 0$$

Very intuitively (cause I'm thinkng of a bounded function defined on a closed domain) I beleive i understand what I'm being asked to prove: If the area of the domain is smaller and smaller, then the integral wil be smaller and smaller, until the interval is just a point, and so the function would also be a point, so the area underneath would be zero.
But formally, I don't know how to use and reason with the hipothesis $m(A) \to 0.$ In the other excercises that I'm supposed to solve, I should use some convergence thoerems available. I have looked at the proofs about some of them, like the monotone convergence theorem, Fatou's Lemma, Lebesgue Convergence theorem, and none of them use explicitly something like the domain is tending to zero. They are using properties about pointwise convergence, or seem to be dealing mainly with images of the functions.
Convergence in measure uses something like: $m\{x : |f(x) -f_n(x)| \ge \epsilon\} < \epsilon .$
Definition: A sequence $<f_n>$ of measurable functions is said to converge to $f$ in measure if, given $\epsilon > 0,$ there is an $N$ such that for all $n \ge N$ we have $m\{x : |f(x) -f_n(x)| \ge \epsilon\} < \epsilon .$
Then, Fatou's Lemma or Monotone Convergence theorem are valid for convergence in measure (it is a proposition, but I have not proved it), and so maybe that is a way to involve a the measure in the domain converging to zero and and integral converging to a funcion $f = 0.$
More overly Im talking to much because it is not clear to me how to relate $m(A) \to 0$ with an integral converging to zero.
I would appreciate some help...

A: Hint: This is clear if $f$ is also bounded. But given $\epsilon>0,$ there exists a bounded $g\in L^1(E)$ such that $\int_E |f-g| < \epsilon.$

A: Say $(A_n)_n \subseteq E$ satisfy $m(A_n) \downarrow 0$. Suppose for some $\epsilon > 0$, $\int_{A_n} f > \epsilon$ for all large $n$. Take a subsequence $(n_k)_k$ so that $\sum_k m(A_{n_k}) < \infty$. Then if $A = \limsup_k A_{n_k}$, $\int_A f > \epsilon$ but $m(A) = 0$ by Borel Cantelli. This is a contradiction.
The motivation for the proof above comes from the fact that $v(A) := \int_A f$ is a measure which is absolutely continuous with respect to $m$. It is a general fact that for measures $v_1,v_2$, if $v_1 \ll v_2$, then for all $\epsilon > 0$ there is a $\delta > 0$ so that if $v_2(A) < \delta$,
then $v_1(A) < \epsilon$, which is your problem statement.

A: By Lebesgue Dominated Convergence Theorem we have
\begin{align*}
\int|f|1_{|f|\geq n}dx\rightarrow\int|f|1_{|f|=\infty}dx=0
\end{align*}
since $m(\{|f|=\infty\})=0$ and the convention that $\infty\cdot 0=0$. Or we can consider the sequence $\left(|f|1_{|f|\leq n}\right)$ and apply Monotone Convergence Theorem to get the convergence to $\displaystyle\int|f|dx$, and then we do the subtraction. Given $\epsilon>0$, we have some $n_{0}\in{\bf{N}}$ such that
\begin{align*}
\int|f|1_{|f|\geq n_{0}}dx<\epsilon.
\end{align*}
For any measurable set $A$ with $m(A)<\epsilon n_{0}^{-1}$ then we have
\begin{align*}
\int|f|1_{A}dx&=\int|f|1_{A\cap\{|f|\geq n_{0}\}}dx+\int|f|1_{A\cap\{|f|<n_{0}\}}dx\\
&<\epsilon+\int|f|1_{A\cap\{|f|<n_{0}\}}dx\\
&\leq\epsilon+n_{0}\int 1_{A}dx\\
&=\epsilon+n_{0}m(A)\\
&<2\epsilon.
\end{align*}


text:
Q: Rubymine 6.0.3 Startup Error on Ubuntu I am installing RubyMine on Ubuntu 15.10. I downloaded the .exe file and installed it using Wine installer. The installation gone pretty well.
But when I tried to run the RubyMine, I am getting an error. I am attaching the screenshot of the error.
I tried searching, I got answers related to Mac Os to remove the .jar extensions. But I couldn't find any regarding Ubuntu.
Anyhelp is appreciated.Thank you.


text:
Q: How to Share a document with Read Permission Level? We are creating SharePoint Groups right now, and we have a lot of people in a group called Readers with the Read Permission Level. I have noticed that they are unable to share documents. When they click on the ellipses and click "Share" we get this message

I have noticed that the only way to get this functionality is if you have full control permission.
Is there anyway around this?
Thank you in advance

A: this is default behavior. two things you can do it.

*

*Create the another permission level copied from Read Permissions level and add Manage Permissions. this will allow the user to share the doucments but it will give them the ability to share withfull control.

*other way is enable the "allowing the Access Requests" will be the best options.

https://social.technet.microsoft.com/Forums/en-US/72ca5f71-1826-4056-b506-a30b5b99adca/only-a-limited-set-of-people-are-allowed-to-share-this-content-sharepoint-2013

A: Usually the way I would get around this is assign an administrator (really Edit Rights) to a power user that will use this the most, or someone that is a SharePoint savvy user. Also, make it known on SharePoint that "User A" has the keys to that document library. That way it falls out of your hands, and gives the users drive to use the company's intranet/extranet.
Any person that needs access to the document library has to send a request to "User A" in order for him/her to grant access to that user. A workflow can even be set up if you want to be fancy, that will allow a user to fill out a form of the document library that he/she is trying to access, and will email the correct person in charge of granting rights.


text:
Q: How can I setup simple audio player with background and notification support in flutter I am using Flutter sound package to play a single audio from a URL and also show notification media controller.
I have tried the demo app on their documentation but its not clear to understand.
The background audio player somehow worked fine but I want to remove the recording system and make it to play audio from URL
Here is the demo app

A: Here is the example of the how to do the above question.
you will have many errors if you haven't enabled null safety which is just changing  your flutter sdk in the Pub.yaml
 environment:
  sdk: ">=2.12.0 <3.0.0"

to the following if you are using flutter above 2.12 otherwise check on how to migrate flutter project to null safety
    import 'dart:async';
    import 'dart:math';

    import 'package:audio_service/audio_service.dart';
    import 'package:flutter/material.dart';
    import 'package:rxdart/rxdart.dart';
    import 'package:flutter/foundation.dart';
    import 'package:just_audio/just_audio.dart';
    import 'package:rxdart/rxdart.dart';

    // You might want to provide this using dependency injection rather than a
    // global variable.
    late AudioHandler _audioHandler;

    Future<void> main() async {
      _audioHandler = await AudioService.init(
        builder: () => AudioPlayerHandler(),
        config: const AudioServiceConfig(
          androidNotificationChannelId: 'com.ryanheise.myapp.channel.audio',
          androidNotificationChannelName: 'Audio playback',
          androidNotificationOngoing: true,
        ),
      );
      runApp(MyApp());
    }

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Audio Service Demo',
          theme: ThemeData(primarySwatch: Colors.blue),
          home: MainScreen(),
        );
      }
    }

    class MainScreen extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('Audio Service Demo'),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // Show media item title
                StreamBuilder<MediaItem?>(
                  stream: _audioHandler.mediaItem,
                  builder: (context, snapshot) {
                    final mediaItem = snapshot.data;
                    return Text(mediaItem?.title ?? '');
                  },
                ),
                // Play/pause/stop buttons.
                StreamBuilder<bool>(
                  stream: _audioHandler.playbackState
                      .map((state) => state.playing)
                      .distinct(),
                  builder: (context, snapshot) {
                    final playing = snapshot.data ?? false;
                    return Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        _button(Icons.fast_rewind, _audioHandler.rewind),
                        if (playing)
                          _button(Icons.pause, _audioHandler.pause)
                        else
                          _button(Icons.play_arrow, _audioHandler.play),
                        _button(Icons.stop, _audioHandler.stop),
                        _button(Icons.fast_forward, _audioHandler.fastForward),
                      ],
                    );
                  },
                ),
                // A seek bar.
                StreamBuilder<MediaState>(
                  stream: _mediaStateStream,
                  builder: (context, snapshot) {
                    final mediaState = snapshot.data;
                    return SeekBar(
                      duration: mediaState?.mediaItem?.duration ?? Duration.zero,
                      position: mediaState?.position ?? Duration.zero,
                      onChangeEnd: (newPosition) {
                        _audioHandler.seek(newPosition);
                      },
                    );
                  },
                ),
                // Display the processing state.
                StreamBuilder<AudioProcessingState>(
                  stream: _audioHandler.playbackState
                      .map((state) => state.processingState)
                      .distinct(),
                  builder: (context, snapshot) {
                    final processingState =
                        snapshot.data ?? AudioProcessingState.idle;
                    return Text(
                        "Processing state: ${describeEnum(processingState)}");
                  },
                ),
              ],
            ),
          ),
        );
      }

      /// A stream reporting the combined state of the current media item and its
      /// current position.
      Stream<MediaState> get _mediaStateStream =>
          Rx.combineLatest2<MediaItem?, Duration, MediaState>(
              _audioHandler.mediaItem,
              AudioService.position,
                  (mediaItem, position) => MediaState(mediaItem, position));

      IconButton _button(IconData iconData, VoidCallback onPressed) => IconButton(
        icon: Icon(iconData),
        iconSize: 64.0,
        onPressed: onPressed,
      );
    }

    class MediaState {
      final MediaItem? mediaItem;
      final Duration position;

      MediaState(this.mediaItem, this.position);
    }

    /// An [AudioHandler] for playing a single item.
    class AudioPlayerHandler extends BaseAudioHandler with SeekHandler {
      static final _item = MediaItem(
        id: 'https://s3.amazonaws.com/scifri-episodes/scifri20181123-episode.mp3',
        album: "Science Friday",
        title: "A Salute To Head-Scratching Science",
        artist: "Science Friday and WNYC Studios",
        duration: const Duration(milliseconds: 5739820),
        artUri: Uri.parse(
            'https://media.wnyc.org/i/1400/1400/l/80/1/ScienceFriday_WNYCStudios_1400.jpg'),
      );

      final _player = AudioPlayer();

      /// Initialise our audio handler.
      AudioPlayerHandler() {
        // So that our clients (the Flutter UI and the system notification) know
        // what state to display, here we set up our audio handler to broadcast all
        // playback state changes as they happen via playbackState...
        _player.playbackEventStream.map(_transformEvent).pipe(playbackState);
        // ... and also the current media item via mediaItem.
        mediaItem.add(_item);

        // Load the player.
        _player.setAudioSource(AudioSource.uri(Uri.parse(_item.id)));
      }

      // In this simple example, we handle only 4 actions: play, pause, seek and
      // stop. Any button press from the Flutter UI, notification, lock screen or
      // headset will be routed through to these 4 methods so that you can handle
      // your audio playback logic in one place.

      @override
      Future<void> play() => _player.play();

      @override
      Future<void> pause() => _player.pause();

      @override
      Future<void> seek(Duration position) => _player.seek(position);

      @override
      Future<void> stop() => _player.stop();

      /// Transform a just_audio event into an audio_service state.
      ///
      /// This method is used from the constructor. Every event received from the
      /// just_audio player will be transformed into an audio_service state so that
      /// it can be broadcast to audio_service clients.
      PlaybackState _transformEvent(PlaybackEvent event) {
        return PlaybackState(
          controls: [
            MediaControl.rewind,
            if (_player.playing) MediaControl.pause else MediaControl.play,
            MediaControl.stop,
            MediaControl.fastForward,
          ],
          systemActions: const {
            MediaAction.seek,
            MediaAction.seekForward,
            MediaAction.seekBackward,
          },
          androidCompactActionIndices: const [0, 1, 3],
          processingState: const {
            ProcessingState.idle: AudioProcessingState.idle,
            ProcessingState.loading: AudioProcessingState.loading,
            ProcessingState.buffering: AudioProcessingState.buffering,
            ProcessingState.ready: AudioProcessingState.ready,
            ProcessingState.completed: AudioProcessingState.completed,
          }[_player.processingState]!,
          playing: _player.playing,
          updatePosition: _player.position,
          bufferedPosition: _player.bufferedPosition,
          speed: _player.speed,
          queueIndex: event.currentIndex,
        );
      }
    }

    class PositionData {
      final Duration position;
      final Duration bufferedPosition;
      final Duration duration;

      PositionData(this.position, this.bufferedPosition, this.duration);
    }

    class SeekBar extends StatefulWidget {
      final Duration duration;
      final Duration position;
      final Duration bufferedPosition;
      final ValueChanged<Duration>? onChanged;
      final ValueChanged<Duration>? onChangeEnd;

      SeekBar({
        required this.duration,
        required this.position,
        this.bufferedPosition = Duration.zero,
        this.onChanged,
        this.onChangeEnd,
      });

      @override
      _SeekBarState createState() => _SeekBarState();
    }

    class _SeekBarState extends State<SeekBar> {
      double? _dragValue;
      bool _dragging = false;
      late SliderThemeData _sliderThemeData;

      @override
      void didChangeDependencies() {
        super.didChangeDependencies();

        _sliderThemeData = SliderTheme.of(context).copyWith(
          trackHeight: 2.0,
        );
      }

      @override
      Widget build(BuildContext context) {
        final value = min(
          _dragValue ?? widget.position.inMilliseconds.toDouble(),
          widget.duration.inMilliseconds.toDouble(),
        );
        if (_dragValue != null && !_dragging) {
          _dragValue = null;
        }
        return Stack(
          children: [
            SliderTheme(
              data: _sliderThemeData.copyWith(
                thumbShape: HiddenThumbComponentShape(),
                activeTrackColor: Colors.blue.shade100,
                inactiveTrackColor: Colors.grey.shade300,
              ),
              child: ExcludeSemantics(
                child: Slider(
                  min: 0.0,
                  max: widget.duration.inMilliseconds.toDouble(),
                  value: min(widget.bufferedPosition.inMilliseconds.toDouble(),
                      widget.duration.inMilliseconds.toDouble()),
                  onChanged: (value) {},
                ),
              ),
            ),
            SliderTheme(
              data: _sliderThemeData.copyWith(
                inactiveTrackColor: Colors.transparent,
              ),
              child: Slider(
                min: 0.0,
                max: widget.duration.inMilliseconds.toDouble(),
                value: value,
                onChanged: (value) {
                  if (!_dragging) {
                    _dragging = true;
                  }
                  setState(() {
                    _dragValue = value;
                  });
                  if (widget.onChanged != null) {
                    widget.onChanged!(Duration(milliseconds: value.round()));
                  }
                },
                onChangeEnd: (value) {
                  if (widget.onChangeEnd != null) {
                    widget.onChangeEnd!(Duration(milliseconds: value.round()));
                  }
                  _dragging = false;
                },
              ),
            ),
            Positioned(
              right: 16.0,
              bottom: 0.0,
              child: Text(
                  RegExp(r'((^0*[1-9]\d*:)?\d{2}:\d{2})\.\d+$')
                      .firstMatch("$_remaining")
                      ?.group(1) ??
                      '$_remaining',
                  style: Theme.of(context).textTheme.caption),
            ),
          ],
        );
      }

      Duration get _remaining => widget.duration - widget.position;
    }

    class HiddenThumbComponentShape extends SliderComponentShape {
      @override
      Size getPreferredSize(bool isEnabled, bool isDiscrete) => Size.zero;

      @override
      void paint(
          PaintingContext context,
          Offset center, {
            required Animation<double> activationAnimation,
            required Animation<double> enableAnimation,
            required bool isDiscrete,
            required TextPainter labelPainter,
            required RenderBox parentBox,
            required SliderThemeData sliderTheme,
            required TextDirection textDirection,
            required double value,
            required double textScaleFactor,
            required Size sizeWithOverflow,
          }) {}
    }

    class LoggingAudioHandler extends CompositeAudioHandler {
      LoggingAudioHandler(AudioHandler inner) : super(inner) {
        playbackState.listen((state) {
          _log('playbackState changed: $state');
        });
        queue.listen((queue) {
          _log('queue changed: $queue');
        });
        queueTitle.listen((queueTitle) {
          _log('queueTitle changed: $queueTitle');
        });
        mediaItem.listen((mediaItem) {
          _log('mediaItem changed: $mediaItem');
        });
        ratingStyle.listen((ratingStyle) {
          _log('ratingStyle changed: $ratingStyle');
        });
        androidPlaybackInfo.listen((androidPlaybackInfo) {
          _log('androidPlaybackInfo changed: $androidPlaybackInfo');
        });
        customEvent.listen((dynamic customEventStream) {
          _log('customEvent changed: $customEventStream');
        });
        customState.listen((dynamic customState) {
          _log('customState changed: $customState');
        });
      }

      // TODO: Use logger. Use different log levels.
      void _log(String s) => print('----- LOG: $s');

      @override
      Future<void> prepare() {
        _log('prepare()');
        return super.prepare();
      }

      @override
      Future<void> prepareFromMediaId(String mediaId,
          [Map<String, dynamic>? extras]) {
        _log('prepareFromMediaId($mediaId, $extras)');
        return super.prepareFromMediaId(mediaId, extras);
      }

      @override
      Future<void> prepareFromSearch(String query, [Map<String, dynamic>? extras]) {
        _log('prepareFromSearch($query, $extras)');
        return super.prepareFromSearch(query, extras);
      }

      @override
      Future<void> prepareFromUri(Uri uri, [Map<String, dynamic>? extras]) {
        _log('prepareFromSearch($uri, $extras)');
        return super.prepareFromUri(uri, extras);
      }

      @override
      Future<void> play() {
        _log('play()');
        return super.play();
      }

      @override
      Future<void> playFromMediaId(String mediaId, [Map<String, dynamic>? extras]) {
        _log('playFromMediaId($mediaId, $extras)');
        return super.playFromMediaId(mediaId, extras);
      }

      @override
      Future<void> playFromSearch(String query, [Map<String, dynamic>? extras]) {
        _log('playFromSearch($query, $extras)');
        return super.playFromSearch(query, extras);
      }

      @override
      Future<void> playFromUri(Uri uri, [Map<String, dynamic>? extras]) {
        _log('playFromUri($uri, $extras)');
        return super.playFromUri(uri, extras);
      }

      @override
      Future<void> playMediaItem(MediaItem mediaItem) {
        _log('playMediaItem($mediaItem)');
        return super.playMediaItem(mediaItem);
      }

      @override
      Future<void> pause() {
        _log('pause()');
        return super.pause();
      }

      @override
      Future<void> click([MediaButton button = MediaButton.media]) {
        _log('click($button)');
        return super.click(button);
      }

      @override
      Future<void> stop() {
        _log('stop()');
        return super.stop();
      }

      @override
      Future<void> addQueueItem(MediaItem mediaItem) {
        _log('addQueueItem($mediaItem)');
        return super.addQueueItem(mediaItem);
      }

      @override
      Future<void> addQueueItems(List<MediaItem> mediaItems) {
        _log('addQueueItems($mediaItems)');
        return super.addQueueItems(mediaItems);
      }

      @override
      Future<void> insertQueueItem(int index, MediaItem mediaItem) {
        _log('insertQueueItem($index, $mediaItem)');
        return super.insertQueueItem(index, mediaItem);
      }

      @override
      Future<void> updateQueue(List<MediaItem> queue) {
        _log('updateQueue($queue)');
        return super.updateQueue(queue);
      }

      @override
      Future<void> updateMediaItem(MediaItem mediaItem) {
        _log('updateMediaItem($mediaItem)');
        return super.updateMediaItem(mediaItem);
      }

      @override
      Future<void> removeQueueItem(MediaItem mediaItem) {
        _log('removeQueueItem($mediaItem)');
        return super.removeQueueItem(mediaItem);
      }

      @override
      Future<void> removeQueueItemAt(int index) {
        _log('removeQueueItemAt($index)');
        return super.removeQueueItemAt(index);
      }

      @override
      Future<void> skipToNext() {
        _log('skipToNext()');
        return super.skipToNext();
      }

      @override
      Future<void> skipToPrevious() {
        _log('skipToPrevious()');
        return super.skipToPrevious();
      }

      @override
      Future<void> fastForward() {
        _log('fastForward()');
        return super.fastForward();
      }

      @override
      Future<void> rewind() {
        _log('rewind()');
        return super.rewind();
      }

      @override
      Future<void> skipToQueueItem(int index) {
        _log('skipToQueueItem($index)');
        return super.skipToQueueItem(index);
      }

      @override
      Future<void> seek(Duration position) {
        _log('seek($position)');
        return super.seek(position);
      }

      @override
      Future<void> setRating(Rating rating, [Map<String, dynamic>? extras]) {
        _log('setRating($rating, $extras)');
        return super.setRating(rating, extras);
      }

      @override
      Future<void> setCaptioningEnabled(bool enabled) {
        _log('setCaptioningEnabled($enabled)');
        return super.setCaptioningEnabled(enabled);
      }

      @override
      Future<void> setRepeatMode(AudioServiceRepeatMode repeatMode) {
        _log('setRepeatMode($repeatMode)');
        return super.setRepeatMode(repeatMode);
      }

      @override
      Future<void> setShuffleMode(AudioServiceShuffleMode shuffleMode) {
        _log('setShuffleMode($shuffleMode)');
        return super.setShuffleMode(shuffleMode);
      }

      @override
      Future<void> seekBackward(bool begin) {
        _log('seekBackward($begin)');
        return super.seekBackward(begin);
      }

      @override
      Future<void> seekForward(bool begin) {
        _log('seekForward($begin)');
        return super.seekForward(begin);
      }

      @override
      Future<void> setSpeed(double speed) {
        _log('setSpeed($speed)');
        return super.setSpeed(speed);
      }

      @override
      Future<dynamic> customAction(String name,
          [Map<String, dynamic>? extras]) async {
        _log('customAction($name, extras)');
        final dynamic result = await super.customAction(name, extras);
        _log('customAction -> $result');
        return result;
      }

      @override
      Future<void> onTaskRemoved() {
        _log('onTaskRemoved()');
        return super.onTaskRemoved();
      }

      @override
      Future<void> onNotificationDeleted() {
        _log('onNotificationDeleted()');
        return super.onNotificationDeleted();
      }

      @override
      Future<List<MediaItem>> getChildren(String parentMediaId,
          [Map<String, dynamic>? options]) async {
        _log('getChildren($parentMediaId, $options)');
        final result = await super.getChildren(parentMediaId, options);
        _log('getChildren -> $result');
        return result;
      }

      @override
      ValueStream<Map<String, dynamic>> subscribeToChildren(String parentMediaId) {
        _log('subscribeToChildren($parentMediaId)');
        final result = super.subscribeToChildren(parentMediaId);
        result.listen((options) {
          _log('$parentMediaId children changed with options $options');
        });
        return result;
      }

      @override
      Future<MediaItem?> getMediaItem(String mediaId) async {
        _log('getMediaItem($mediaId)');
        final result = await super.getMediaItem(mediaId);
        _log('getMediaItem -> $result');
        return result;
      }

      @override
      Future<List<MediaItem>> search(String query,
          [Map<String, dynamic>? extras]) async {
        _log('search($query, $extras)');
        final result = await super.search(query, extras);
        _log('search -> $result');
        return result;
      }

      @override
      Future<void> androidSetRemoteVolume(int volumeIndex) {
        _log('androidSetRemoteVolume($volumeIndex)');
        return super.androidSetRemoteVolume(volumeIndex);
      }

      @override
      Future<void> androidAdjustRemoteVolume(AndroidVolumeDirection direction) {
        _log('androidAdjustRemoteVolume($direction)');
        return super.androidAdjustRemoteVolume(direction);
      }
    }

    void showSliderDialog({
      required BuildContext context,
      required String title,
      required int divisions,
      required double min,
      required double max,
      String valueSuffix = '',
      // TODO: Replace these two by ValueStream.
      required double value,
      required Stream<double> stream,
      required ValueChanged<double> onChanged,
    }) {
      showDialog<void>(
        context: context,
        builder: (context) => AlertDialog(
          title: Text(title, textAlign: TextAlign.center),
          content: StreamBuilder<double>(
            stream: stream,
            builder: (context, snapshot) => Container(
              height: 100.0,
              child: Column(
                children: [
                  Text('${snapshot.data?.toStringAsFixed(1)}$valueSuffix',
                      style: const TextStyle(
                          fontFamily: 'Fixed',
                          fontWeight: FontWeight.bold,
                          fontSize: 24.0)),
                  Slider(
                    divisions: divisions,
                    min: min,
                    max: max,
                    value: snapshot.data ?? value,
                    onChanged: onChanged,
                  ),
                ],
              ),
            ),
          ),
        ),
      );
    }

A: I recommend just_audio with audio_service.
As the plugin name says just_audio is just for audio and to create notification you have to use audio_service.


text:
Q: Link to a component in React/Semantic UI with onClick I need a modal to open with onClick, the variable calling the modal  is nested between Translation keys. Here's some of the code. When clicking the link text, I currently have this error message: Cannot read property 'modaleNouvelleOeuvre' of undefined :-/
modaleNouvelleOeuvre(ouvert = true) { /*Ouvert means Open*/
this.setState({ modaleOeuvre: ouvert })
}

{t('flot.split.tableaudebord.vide.indication')}
 { e.preventDefault(); this.modaleNouvelleOeuvre() }}>
{t('flot.split.tableaudebord.vide.indication-lien')}

There's a button elsewhere on the page to open the same modal:
<Modal
open={this.state.modaleOeuvre}
onClose={() => { this.modaleNouvelleOeuvre(false); if (this.state.audio) this.state.audio.stop() }}
size="large"
closeIcon
closeOnDimmerClick={false}
>

A: That's because you're invoking this.modaleNouvelleOeuvre() inside the .

modaleNouvelleOeuvre(e) {
  e.preventDefault()
  this.setState({ modaleOeuvre: !this.state.ouvert })
}

Note: e or event is implicit.


text:
Q: 802.3at PoE power splitter design - how to pass the actual Ethernet signal along I'm researching the design of a PoE splitter. I understand the actual 802.3at portion of things, and have some confidence in being able to get the 48 VDC out (TPS2378).
The question I have is... I've got the center tapped 1:1 transformers on the incoming pairs. That's fine. But what do I do with the secondaries of the transformers such that I can just connect up to an RJ45 intended to be the jack for the target device?
Is it just simply wiring the secondaries to the output jack?

A: This schematic appears to answer the question: the output of the secondary of the magnetics appears to go directly to the outgoing RJ45 jack.


text:
Q: Monitor Specific WiFi Traffic with Wireshark or Python? I'm looking to capture specific WiFi traffic data on a network in a household.
What I would like to collect is the volume of data, the timings and the devices involved. This is for a study of mine, looking to monitor WiFi traffic in terms of collecting volume of data (maybe packets per second or packet lengths), the times and the devices (so if the device is a laptop, mobile phone or desktop PC using the WiFi).
However, for ethical reasons, I want to filter out certain details that WireShark would typically collect (for example, I don't want to capture DNS information or any detailed information about what a user is doing).
Does WireShark allow for configuration of what it captures? Or, if not, would it be possible to run a Python script which sort of 'cleans up' the data captured by WireShark so I am only collecting what I want?
Alternatively, I've looked into running a Python script to collect the network traffic (using scapy) but not sure this allows me to collect WiFi traffic or the devices involved (which is ideally what I am looking for).
Does anybody have any suggestions about an approach, or can recommend out of my options about which is most sensible/feasible/easiest?
Thank you

A: Wireshark allows you to filter before outputting to the current capture Capture Options -> Capture Filter.  The filter can include a plethora of options and will ensure that only the packets that match are saved.

On a small note i'd suggest to look at tshark. Wireshark comes with tshark (although it is bundled as separate packages on some distros/OSes).  tshark is pretty much a command line wireshark.
By default tshark outputs to STDOUT in a format that tries to by human readable (not the PCAP format).
If all you need is the number of packets of a certain kind you can just filter with tshark and count on the fly, and never save the packets themselves.  For example:
counter=1;
tshark tcp src port 80 2>/dev/null |
while read x; do
    counter=$((counter + 1));
    echo $counter;
done

Will output the number of TCP packets that originate from port 80 from the moment the script starts until you interrupt it.
(tshark uses the same filter syntax as wireshark)


text:
Q: Calendar changes time when I add an item manually I open the calendar app and click on a day. A window pops up where I type the name of the event. Out of habit, instead of pressing "edit details" I press "add" because in another app I used to use this would show a window asking for details. The issue I'm describing does not happen if you press "edit details". So what I get is an event marked as "all day". I edit it to not be all day and set up the start time (18:00) and leave the end time to its default (19:00) and press "Done". What shows up is the time 1 hour later, i.e. starting at 19:00 and ending at 20:00.
This is similar but distinct from this question, Timezone issue Gnome calendar, since I have this issue when adding items manually. In fact in all discussion online I've seen, the issue being reported is when items are imported from other calendars or files.
On the other hand, I have in fact imported events from my google account in the past, which included events both in WEST and CEST...
Since I suppose this is a bug, let me know if I should report it somewhere.
It's the calendar app that comes preinstalled in Ubuntu and has this logo:

Also, I'm on Ubuntu 20.04.2 LTS


text:
Q: Need to reset PinchZoom.js plugin after a click creating a mobile website using PinchZoom.js plugin to zoom in and zoom out on a map. It also has a search feature that highlights areas on the map.
When the map is zoomed in, and someone searches, I want pinchzoom.js to reset back to the zoomed out view. I can achieve this by removing the style on the Zoom Container through jquery. but when I tap back on the map, it starts zooming from the original zoomed in location, before the search.
How would I go about resetting the pinchzoom.js plugin back to its original onload scale from a jQuery click function?
<script type="text/javascript">
jQuery(function ($) {
    $(function reset() {
       $('div.pinch-zoom').each(function () {
          new RTP.PinchZoom($(this), {
                maxZoom: 10
          });
       });
    })
 });

</script>

<script>
jQuery(function ($) {
  $(document).ready(function() {
     $('#contactlink').click(function(){
       $('#formbox').slideToggle('fast');

       $('.pinch-zoom .activeLocation').removeClass('activeLocation');
     });
 });
   $(document).ready(function() {
      $('#formbox').click(function(){
         $('#formbox').slideToggle('fast');
      });
   });
})
</script>

<script type="text/javascript">
jQuery(document).ready(function (){
    jQuery('#E1').click(function() {
       jQuery('.pinch-zoom').empty();
       jQuery('.E1').addClass("activeLocation");
    });
});
</script>

A: In my case I need to reset zoom image.So save old image src of zoom image in one variable and create new html element i.e. image with same id and set old image src which we saved in temporary variable.With orientation change we can use same solution.
In your case save your value of zoom element and delete it and recreate html element and assign old value.
May be it is not proper solution.But it works for me.


text:
Q: Possible memory leak in simple batch file processing function in c# I'm running a very simple function that reads lines from a text file in batches. Each line contains an sql query so the function grabs a specified number of queries, executes them against the SQL database, then grabs the next batch of queries until the entire file is read. The problem is that over time with very large files the process starts to slow considerably. I'm guessing there is a memory leak somewhere in the function but can't determine where it may be. There is nothing else going on while this function is running. My programming skills are crude at best so please go easy on me. :)
    for (int x = 0; x<= totalBatchesInt; x++)
    {
    var lines = System.IO.File.ReadLines(file).Skip(skipCount).Take(batchSize).ToArray();
    string test = string.Join("\n", lines);
    SqlCommand cmd = new SqlCommand(test.ToString());
        try
        {
            var rowsEffected = qm.ExecuteNonQuery(CommandType.Text, cmd.CommandText, 6000, true);
            totalRowsEffected = totalRowsEffected + rowsEffected;
            globalRecordCounter = globalRecordCounter + rowsEffected;
            fileRecordCounter = fileRecordCounter + rowsEffected;
            skipCount = skipCount + batchSize;
            TraceSource.TraceEvent(TraceEventType.Information, (int)ProcessEvents.Starting, "Rows
            progress for " + folderName + "_" + fileName + " : " + fileRecordCounter.ToString() + "
            of " + linesCount + " records");
        }
        catch (Exception esql)
        {
            TraceSource.TraceEvent(TraceEventType.Information, (int)ProcessEvents.Cancelling, "Error
            processing file " + folderName + "_" + fileName + " : " + esql.Message.ToString() + ".
            Aborting file read");
        }
    }

A: There are many things wrong with your code:

*

*You never dispose your command. That's a native handle to an ODBC driver, waiting for the garbage collector to dispose it is very bad practice.

*You shouldn't be sending those commands individually anyway. Either send them all at once in one command, or use transactions to group them together.

*This one is the reason why it's getting slower over time: File.ReadLines(file).Skip(skipCount).Take(batchSize) will read the same file over and over and ignore a growing amount of lines every attempt, and so growing slower and slower as the number of lines ignored (but processed) gets larger and larger.
To fix #3, simply create the enumerator once and iterate it in batches. In pure C#, you can do something like:
using var enumerator = File.ReadLines(file).GetEnumerator();

for (int x = 0; x<= totalBatchesInt; x++)
{
    var lines = new List<string>();
    while(enumerator.MoveNext() && lines.Count < batchSize)
        list.Add(enumerator.Current);
    string test = string.Join("\n", lines);
    // your code...
}

Or if you're using Morelinq (which I recommend), something like this:
foreach(var lines in File.ReadLines(file).Batch(batchSize))
{
    // your code...
}


text:
Q: Regex on htaccess file gives INTERNAL REDIRECT error I'm trying to create a redirect rule that matches the following urls:
en/property/rotterdam/apartment/lorem-ipsum-dolor-sit-amet/v-9/
en/property/rotterdam/apartment/lorem-ipsum-dolor-sit-amet/9/
en/property/rotterdam-centrum/appartment/lorem-ipsum-dolor-sit-amet/9
en/property/lorem-ipsum-dolor-sit-amet-9/
en/property/lorem-ipsum-dolor-sit-amet/v9/
en/property/lorem-ipsum-dolor-sit-amet/v-9/
en/property/lorem-ipsum-dolor-sit-amet/v-9
en/property/rotterdam/apartment/branch/lorem-ipsum-dolor-sit-amet-9/
en/property/rotterdam/lorem-ipsum-dolor-sit-amet-9/
en/property/rotterdam/lorem-ipsum-dolor-sit-amet-9434343/
en/property/rotterdam/apartment/lorem-ipsum-dolor-sit-amet/v-243249/
en/property/rotterdam/apartment/lorem-ipsum-dolor-sit-amet/v2342349/
en/property/rotterdam/apartment/lorem-ipsum-dolor-sit-amet/243249/
en/property/rotterdam/apartment/lorem-ipsum-dolor-sit-amet/v-9/
en/property/rotterdam/apartment/lorem-ipsum-dolor-sit-amet/v-9/?test=1
en/property/rotterdam/apartment/lorem-ipsum-dolor-sit-amet/v-9/test/one/?success=3
en/property/rotterdam/apartment/2-rooms/lorem-ipsum-dolor-sit-amet/v-9/blah/1234/blahh/55555/?sass=123
en/property/rotterdam/appartment/lorem-ipsum-dolor-sit-amet/9234234
en/property/rotterdam/lorem-ipsum-dolor-sit-amet/9234234
en/property/lorem-ipsum-dolor-sit-amet/9234234
en/property/9234234
en/property/rotterdam/appartment/lorem-ipsum-dolor-sit-amet/9/test/132?algo=123

All urls that need to be match can be seen here
https://regex101.com/r/4TPEhy/1
I'm facing two issues, first one is that two urls are not matching:
en/property/rotterdam/apartment/2-rooms/lorem-ipsum-dolor-sit-amet/v-9/blah/1234/blahh/55555/?sass=123
en/property/9234234

And the second one, something on that regex is causing an interal redirect error.
This is my regex (the best case that I got so far)
^(en\/)?property\/[A-Яa-я0-9\-_\/]+?([\d]+)(.*)$

And this is my rewrite rule
RewriteRule ^(en\/)?property\/[A-Яa-я0-9\-_\/]+?([\d]+)(.*)$ $1properties/property/$2$3&%{QUERY_STRING} [NC,L]

The regex seems to be working fine on the tool (regex101), but as soon as a try to refresh the page applying that rule I get a 500 - Internal Server Error.
I need to match all the cases, I've tried different combinations for hours, but I'm missing something that's causing those issues.
On the .htaccess the groups that I need are $2 and $3, since $2 contains the property ID which I'm using on my script and $3 is all the rest of the URL like any other extra parameter or the query string.
The reason for so many different configurations is that users can set their own URL format, but limited to the options listed above.
This is an extract from the apache logs when this URL is requested
https://localhost/en/property/rotterdam/apartment/lorem-ipsum-dolor-sit-amet/v-9/test/132?blah=123

Logs
php74         | [Mon May 31 12:19:12.375537 2021] [rewrite:trace3] [pid 64] mod_rewrite.c(483): [client 172.18.0.1:63664] 172.18.0.1 - - [localhost/sid#7fd3d4ab1958][rid#7fd3d29d73c0/initial/redir#10] [perdir /var/www/html/] add per-dir prefix: en/properties/property/9/test/132&blah=123&blah=123&blah=123&blah=123&blah=123&blah=123&blah=123&blah=123&blah=123&blah=123&blah=123 -> /var/www/html/en/properties/property/9/test/132&blah=123&blah=123&blah=123&blah=123&blah=123&blah=123&blah=123&blah=123&blah=123&blah=123&blah=123

A: You may try this rewrite rule:
RewriteEngine On

RewriteRule ^(en/)?property/(?:\S*?[-/v])?(\d+)(/.*)?$ $1properties/property/$2$3 [NC,L]

Updated RegEx Demo
We are capturing property ID after a - or / or v characters.


text:
Q: how to get field names if results is empty? [PHP-Codeigniter] I was able to take the field name from the table using array_keys()
but if the query results are empty, array_keys() can not be used.

is there any other way that I can take the name of the field even if the result is empty?

Query i used:
SELECT m.nama_user, m.nama_login, m.email, m.tgl_expired, m.password_web, gu.ucode_grp, gu.nama_grp_user
FROM tb_m_user m
LEFT OUTER JOIN tb_m_grp_user gu
ON m.ucode_grp=gu.ucode_grp
WHERE id_user=10

A: In Codeigniter you can use...
$field_names = $this->db->list_fields('name_of_your_table');

name_of_your_table is the name of the Database Table you want the field list from.
$field_names will be an array with the field names
For more Details, Refer to https://www.codeigniter.com/userguide3/database/db_driver_reference.html?highlight=field%20names#CI_DB_driver::list_fields

A: Try this,
For eg.
$query_string = 'select name, role from sampledata';
$this->db->query($query_string)->list_fields();
o/p is, Array ( [0] => name [1] => role)

A: Get the query result object
$result = $this->db->get(); // OR $this->db->query()

and simply use it's methods to get all the data you need:
$return = array();
$return['list_fields'] = $result->list_fields();
$return['data'] = $result->result_array();
$return['num_rows'] = $result->num_rows();


text:
Q: How to change font and lollipop size? I want to increase the width of the sticks on my lollipop graph, and increase the size of the font of my y-labels. How would I go about doing that?
   df_graph2 <- data.frame(
   parameters = c("Cut back spending on food",
            "Used up all or most saving",
            'Increased credit card debt',
            'Took money out of long-term savings',
            'Borrowed money from family or friends',
            'Pawned or sold possessions'),
  values <- c(34.40,26.00,25.50,14.40,12.70,11.30))
 df_graph2 %>%
 ggplot() + aes(x=parameters, y=values) +
 geom_segment( aes(x=parameters, xend=parameters, y=0, yend=values), color="gray82") +
 geom_point( color="darkorange", size=4.2, alpha=0.9) +
 geom_text(aes(label = paste(values,"%")), hjust = -.3,size=3.8,family="Arial") +
 expand_limits(y = 100)+
 theme_light() +
coord_flip() +
theme(
plot.margin = margin(1, 1, 4, 1.1, "cm"),
panel.grid.major.y = element_blank(),
axis.text.y = element_text(color = 'black'),
panel.border = element_blank(),
axis.ticks.y = element_blank(),
axis.ticks.x = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.text.x = element_blank(),
panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank()
)

A: Change the y axis label size using the size parameter inside the element_text call of theme(axis.text.y and change the line width of the lollipops with size =  inside geom_segment
ggplot(df_graph2, aes(parameters, values)) +
  geom_segment(aes(xend = parameters, y = 0, yend = values),
               size = 2, color = "gray82") +
  geom_point(color = "darkorange", size = 4.2, alpha = 0.9) +
  geom_text(aes(label = paste(values,"%")), hjust = -.3, size=3.8) +
  expand_limits(y = 100) +
  coord_flip() +
  theme_void() +
  theme(plot.margin = margin(1, 1, 4, 1.1, "cm"),
        axis.text.y = element_text(color = 'black', size = 12, hjust = 1))


text:
Q: Types are incomplete due to include guards I am trying to get a project to compile, and I am running into a problem with incomplete types. Here is the output from make:
In file included from ../common/ClientCommunication.h:13,
                 from EchoService_stub.h:9,
                 from EchoService_stub.cpp:1:
../common/Naming_stub.h:16: error: field 'clientCommunication' has incomplete type
In file included from EchoService_stub.h:9,
                 from EchoService_stub.cpp:1:
../common/ClientCommunication.h:20: error: field 'serverEndpoint' has incomplete type
make: *** [EchoService_stub.o] Error 1

Here are my header files in question:
In Naming_stub.h:
ifndef NAMING_STUB_H__
#define NAMING_STUB_H__

#include <string>
#include <string.h>
#include "Naming.h"

class ClientCommunication;

class Naming_stub : public Naming {

private:
  ClientCommunication clientCommunication;

protected:
  // Protected Methods Here.

public:
  // Public Methods Here.
};
#endif

In Naming.h
#ifndef NAMING_H__
#define NAMING_H__

#include "Remote.h"
#include "../util/RemoteException.h"

class Naming {
private:
protected:
public:

  virtual Remote* lookup(std::string lookupURL) throw (RemoteException);

  virtual void bind() throw (RemoteException);

  ~Naming();
};

#endif // NAMING_H__

Finally, there is the ClientCommunication.h file:
#ifndef CLIENT_COMMUNICATION_H__
#define CLIENT_COMMUNICATION_H__

#include <iostream>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "../util/RemoteTypes.h"
#include "Naming_stub.h"

struct Endpoint;

class ClientCommunication {
private:
  int socket_fd;
  struct Endpoint serverEndpoint;

protected:

public:
  ClientCommunication(const struct Endpoint& serverEndpoint_in);
  struct Buffer send(struct Buffer& callBuffer);
  ~ClientCommunication();
};

#endif // CLIENT_COMMUNICATION_H__

Sorry that this is so long, but there is one more header file. The Endpoint struct is declare in RemoteTypes.h, which looks like the following:
#ifndef REMOTE_EXCEPTION_H__
#define REMOTE_EXCEPTION_H__

#include <netinet/in.h>

struct Endpoint {
  int port;
  char* service_id;
  char* server_ip;
  struct sockaddr_in host_name;
};

struct Buffer {
  char* contents;
  int size;
};

#endif

Thanks!

A: You cannot declare a field using an incomplete type. You have to declare a pointer instead.
private:
  ClientCommunication clientCommunication; // requires #include
  ClientCommunication *clientCommunication; // works with incomplete type

Otherwise, you have to include the client communication header in the first header.
ifndef NAMING_STUB_H__
#define NAMING_STUB_H__

#include "ClientCommunication.h"

A: ClientCommunication should be fully declared in Naming_stub.h before the declaration of Naming_stub, or its clientCommunication member should become a pointer/reference. Only those work with incomplete types. Similar advice applies to Endpoint in ClientCommunication.h.

A: As far as I can tell, you don't have #include "ClientCommunication.h" or #include "RemoteTypes.h" anywhere
So, #include "RemoteTypes.h" in ClientCommunication.h and #include "ClientCommunication.h" in Naming_stub.h


text:
Q: .Select exclude item if item.x = null I need to create a new object and add it to a list but if one of the fields is null I don't want to include it in my list.
Is there a way to not select the item if item.Group.Label is equal to null
var search = Db.*******.Find(accountId);
var suggestions = Db.*******.Where(
                           x => x.Name.Contains(search.Name)
                             && x.EntityId != accountId)
                           .ToList()
                           .Select(item => new {
                                                  id = item.GroupId,
                                                  text = item.Group.Label
                                               });

return Json(suggestions, JsonRequestBehavior.AllowGet);

A: Include that condition in your Where function?
var suggestions = Db.*******
     .Where(x => x.Name.Contains(search.Name) &&
         x.EntityId != accountId && x.Group.Label != null)
     .ToList()
     .Select(item => new { id = item.GroupId, text = item.Group.Label});


text:
Q: I want to use learned weights with a tensor flow I trained my neural network with a tensorflow and I learned 1,000,000 times.
Three files have been created in "C / folder". (meta, index and data files).
I would like to load only the my weight and bias.
Please look following code.
c_dim = 1
scale = 3
im = Image.open('test.bmp')
#shape of im is(256, 256, 3)
image_size_width, image_size_height = im.width, im.height
img = im.convert('YCbCr')
# I need only Y channel
# shape of img is (256, 256, 3)

arr_img = np.asarray(img)
arr_img = arr_img[:, :, 0]
#shape of arr_img is (256, 256)
arrimg = np.expand_dims(arr_img, 0)
arrimg = np.expand_dims(arrimg, 3)
# Tensorflow needs... [?, 256, 256, 1] so, i expand dimention of 'arrimg'

images = tf.placeholder(tf.float32, [None, image_size_width, image_size_height, c_dim], name='images')
# I define plachholder
w1 = tf.Variable(tf.random_normal([9, 9, 1, 64], stddev=1e-3), name='w1')
w2 = tf.Variable(tf.random_normal([1, 1, 64, 32], stddev=1e-3), name='w2')
w3 = tf.Variable(tf.random_normal([5, 5, 32, 1], stddev=1e-3), name='w3')
# I define weight
b1 = tf.Variable(tf.zeros([64]), name='b1')
b2 = tf.Variable(tf.zeros([32]), name='b2')
b3 = tf.Variable(tf.zeros([1]), name='b3')
# I define bias

conv1 = tf.nn.relu(tf.nn.conv2d(images, w1, strides=[1,1,1,1], padding='VALID') + b1)
conv2 = tf.nn.relu(tf.nn.conv2d(conv1, w2, strides=[1,1,1,1], padding='VALID') + b2)
result = tf.nn.conv2d(conv2, w3, strides=[1,1,1,1], padding='VALID') + b3
# After restoring the saved my weights, I want to put it into the calculation graph I want.

sess = tf.Session()
saver = tf.train.Saver()
saver.restore(sess, 'C:/folder/my.model-1000000')
saver.restore(sess, tf.train.latest_checkpoint('C:/folder/'))
#I restore my weight and bias

sess.run(tf.global_variables_initializer())
aa = sess.run(result, {images : arrimg})

#aa = aa[0,:,:,0]
print(type(aa))
# this is numpy array
print(np.shape(aa))
# (1, 244, 244, 1)
# I can not change this(shape of (1, 244, 244, 1)) to image!

aa = np.reshape(aa, (244, 244))
# so i change shape

resultimage = Image.fromarray(aa, 'L')
resultimage.save('C:/SRCNN/result.bmp')

However, there is only meaningless black and white image.
The tensorflow must have rank 4 for graph computation.
So I changed the dimensions of the original RGB image (256, 256, 3) at will.
Is it because I made a mistake in image processing?
Or did i make a mistake in how to restore weights and bias?


text:
Q: How to remove search and refresh fields from W2UI grid toolbar? The W2UI Grid component has an option to turn on a toolbar.  Unfortunately it contains two fields that I don't want and take up space that I don't have.  The two fields are the search and refresh.  You can see them here.
How do you turn them off?  I've tried removing the "searches" items from the w2grid definition options, but yet the search field remains.  Has anyone figured out how to hide those two fields?

A: Those toolbar elements can be hidden via grid.show.
To remove the search drop-down set toolbarSearch to false.
To remove the search input field set toolbarInput to false.
To remove the refresh button set toolbarReload to false.
Here's the modified show property based on the demo you've linked:
    show: {
        toolbar: true,
        footer: true,
        toolbarAdd: true,
        toolbarDelete: true,
        toolbarSave: true,
        toolbarEdit: true,
        toolbarSearch: false,
        toolbarInput: false,
        toolbarReload: false,
    },

grid.show documentation can be found here: http://w2ui.com/web/docs/1.5/w2grid.show
Fiddle: http://jsfiddle.net/g5ebyqdv/


text:
Q: Android 2.1 programmatically unmount SDCard I have an application that writes important data to the SDCard and encrypts it using AES, which later will be used by a desktop application. I have noticed that if I do not unmount the SDCard from the Settings menu sometimes the files don't get written at all, or are corrupted.
Is there anyway in Android 2.1 that I can unmount the SDCard programmatically? Because I'm pretty sure that from time to time the users will forget to do this, and I'll be the one fixing  the problems and I really don't want this.
If this is not possible,what Linux command should I use to unmount the SDCard? Since the application will run on some tablets that have a rooted OS.

A: You should unmount what's using the sdcard in the proper order, for example
umount /mnt/sdcard/.android_secure
umount /mnt/sdcard

or, probably synchronizing the buffers with the filesystem would be enough
sync; sync


text:
Q: How can I modify cookies' lifetimes with Chrome (Mac)? In Safari, when I wanted to avoid Cookies to expire (e.g. in order to stay logged in to MediaWiki for longer than 4 weeks), i could open the cookies file in a text editor and just change the expiry date.
Any idea how to do this with Chrome (on a Mac)?
The cookie file (http://stackoverflow.com/questions/4528208/google-chrome-cookie-storage) does not read very nice in a text editor...

A: Could you not install an extension to help you out like this one: https://chrome.google.com/webstore/detail/fngmhnnpilhplaeedifhccceomclgfbg?hl=en-GB


text:
Q: Perl Loop not filtering right results Why does my while loop seem to be missing some match values?
This result output is not returning all the possible values after reading the files. There are some missing values.
# str_1,2,3,4 are my search strings

while ($line = <$fh>) {

    if ( $line !~ /$str_1/ && $line =~ /$str_2/ ) {
        open($fh, '>>report.txt');
        print $fh "$file : $line";
        close $fh;
    }

    if ( $line !~ /$str_3/ && $line =~ /$str_4/ ) {
        open($fh, '>>report.txt');
        print $fh "$file : $line";
        close $fh;
    }
}

output:
Number of Attendance = 1 INFO:21
Number of Attendance = 2 INFO:21
Number of Attendance = 1 INFO:21

# There are results such as Number of Attendance = 8 INFO:21 which my code is not able to search.

For example:
     #my log file which is the input
    Number of Attendance = 1 from XYZ FACI     INFO:21
    Number of Attendance = 0 from UZQ BLAH     INFO:21
    Number of Attendance = 8 from WZW BLAH     INFO:21
    Number of Attendance = 0 from WZW BLAH     INFO:21
    Number of Attendance = 0 from WZW BLAH     INFO:21
    Number of Attendance = 0 from WZW BLAH     INFO:21

   so here my str1 = /Number of Attendance = 0/
              str2 = /INFO:21/

   #So output for my code now is only

    Number of Attendance = 1 from XYZ FACI     INFO:21

  #But,Expected output should be

   Number of Attendance = 1 from XYZ FACI     INFO:21
   Number of Attendance = 8 from WZW BLAH     INFO:21

I think its only reading all my files only once and returning the first output value instead  of returning all the possible values.

A: You are closing the filehandle that you are trying to iterate over!
If you had use warnings; in your code, perl would have warned you:
readline() on closed filehandle $fh at /home/felix/abdc/foo.pl line 9.
Always use warnings; and use strict;
Rewrite your while loop like this:
open my $fh, "<$file" or die "Unable to open '$file' : $!";
open my $out, ">output_log" or die "Unable to open 'output_log' : $!";

while (my $line = <$fh>) {
    if ( ... ) {
        print $out $line;
    }
    ...
}
close $out or die "Unable to finish writing output_log : $!";


text:
Q: Jackson custom Instant deserialization from ISO8601 String without Z I need to deserialize a ISO 8601 value into an Instant, but the string is without the trailing Z character.
E.g.
2022-03-01T15:42:23.800

instead of
2022-03-01T15:42:23.800Z

These are my tests:
public class JacksonParsingTests {
private static ObjectMapper objectMapper;

@BeforeClass
public static void setUp(){
    objectMapper = new ObjectMapper();

    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    objectMapper.registerModule(new Jdk8Module());
    objectMapper.registerModule(new JavaTimeModule());
}

@Test
public void testInstantSerializationFormat(){
    try {
        String instantJSON = objectMapper.writeValueAsString(Instant.now());

        System.out.println("Instant JSON:");
        System.out.println(instantJSON);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
}

@Test
public void testInstantDeserialization() {

    try {
        String iso8601JSON = "\"2022-03-01T15:42:23.800Z\"";
        Instant now = objectMapper.readValue(iso8601JSON, Instant.class);

        System.out.println("Zulu ISO8601 deserialization:");
        System.out.println(now);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Test
public void testCustomInstantDeserialization(){
    try {
        String customISO8601JSON = "\"2022-03-01T15:42:23.800\"";
        Instant now = objectMapper.readValue(customISO8601JSON, Instant.class);

        System.out.println("No Zulu ISO8601 deserialization:");
        System.out.println(now);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}
How can I define a custom deserializer for the Instant class and register it with the ObjectMapper?
I tried with
public class ISO8601InstantDeserializer extends InstantDeserializer<Instant> {
    public ISO8601InstantDeserializer() {
        super(InstantDeserializer.INSTANT, new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
            .optionalStart().appendOffset("+HH:MM", "+00:00").optionalEnd()
            .optionalStart().appendOffset("+HHMM", "+0000").optionalEnd()
            .optionalStart().appendOffset("+HH", "Z").optionalEnd()
            .toFormatter());
    }
}

and
@BeforeClass
public static void setUp(){
    objectMapper = new ObjectMapper();

    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    objectMapper.registerModule(new Jdk8Module());
    objectMapper.registerModule(new JavaTimeModule().addDeserializer(Instant.class, new ISO8601InstantDeserializer()));
}

but without success.
The error I get is:
com.fasterxml.jackson.databind.JsonMappingException: Failed to deserialize java.time.Instant: (java.time.DateTimeException) Unable to obtain Instant from TemporalAccessor: {},ISO resolved to 2022-03-01T15:42:23.800 of type java.time.format.Parsed
 at [Source: "2022-03-01T15:42:23.800"; line: 1, column: 1]
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:277)
    at com.fasterxml.jackson.datatype.jsr310.deser.JSR310DeserializerBase._rethrowDateTimeException(JSR310DeserializerBase.java:82)
    at com.fasterxml.jackson.datatype.jsr310.deser.InstantDeserializer.deserialize(InstantDeserializer.java:208)
    at com.fasterxml.jackson.datatype.jsr310.deser.InstantDeserializer.deserialize(InstantDeserializer.java:48)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3814)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2858)
    at eu.config.jackson.JacksonParsingTests.testCustomInstantDeserialization(JacksonParsingTests.java:60)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: java.time.DateTimeException: Unable to obtain Instant from TemporalAccessor: {},ISO resolved to 2022-03-01T15:42:23.800 of type java.time.format.Parsed
    at java.time.Instant.from(Instant.java:378)
    at com.fasterxml.jackson.datatype.jsr310.deser.InstantDeserializer.deserialize(InstantDeserializer.java:203)
    ... 27 more
Caused by: java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: InstantSeconds
    at java.time.format.Parsed.getLong(Parsed.java:203)
    at java.time.Instant.from(Instant.java:373)
    ... 28 more


text:
Q: Showing Posts of Specific Custom Post Type and Display post name and post taxonomy i found the solution wand completed the code, here's the final code for use " Display List of Posts of Custom Post type, and display Post Title with It's first taxonomy name " :
<?php
$args = array(
  'numberposts'     => -1,
  'post_type'       => 'custom-post-type',
  'orderby'         => 'title',
  'order'       => 'ASC',
        array(
            'taxonomy' => 'post-type-taxonomy-name',
            'field'    => 'slug',
        ),
);
$myposts = get_posts($args);

if($myposts):
    foreach ($myposts as $mypost):
    // get terms
    $terms = get_the_terms( $mypost->ID, 'post-type-taxonomy-name' );
    // showing only first category of post
    $onecategory = $terms[0];
    $category_link = get_category_link($onecategory->term_id);
?>

 //trimmed the title to only 20 Characters, you can change it or remove it
        <a style="color:white;" href="<?php echo get_permalink($mypost->ID); ?>"> <?php  ?> <?php echo $trimmed = mb_strimwidth( get_the_title($mypost->ID), 0, 20, ); ?> - <?php echo $onecategory->name; ?>

    <?php endif; endforeach; wp_reset_postdata(); ?>
<?php endif; ?>


text:
Q: finding an annihilator of ideal in the ring $\mathbb{Z}_{20}$ as follows Here's the complete problem.
Let $I$ be an ideal of the commutative ring $R$. Define the annihilator of $I$ to be the set
$Ann(I) = \lbrace r\in R \mid ra = 0 \ for \ all \ a \in I \rbrace$.
Let $\mathbb{Z}_{20}$ be a ring and $I=\lbrace \overline{n} \mid n \ is \ even \rbrace$. Prove that $I$ is ideal in $\mathbb{Z}_{20}$. Find $Ann(I)$.
My answer:
Since $\overline{0} \in I, I \neq \emptyset$. Let $s,t \in I$. That is,
$s = \overline{n_1}$ and $t = \overline{n_2}$, for some even integers $n_1,n_2$. Then, $s-t = \overline{n_1} - \overline{n_2} = \overline{n_1-n_2} \in I$.
Now, for $r \in \mathbb{Z}_{20}$, we have $rs = r\overline{n_1} \in I$ and $sr = \overline{n_1}r \in I$
since the result of the product of an arbitrary integer with an even integer is always even. Hence, $I$ is ideal in $\mathbb{Z}_{20}$.
Next, we must find some elements in $\mathbb{Z}_{20}$, say $r$, such that for all $a \in I, ra = 0$. I found that $Ann(I) = \lbrace \overline{0}, \overline{10} \rbrace$, since for all $n \in I$ and $m\in Ann(I), mn = \overline{0}$.
Is my answer above overall corect?
Please correct me if I wrong. Thanks in advanced.


text:
Q: what to change "2 days ago" to the date "september 24, 2022" in blog posts meta in home page the date meta of posts is showing "1 day ago" i want to change that to the actual date it was posted like "September 24, 2022"
enter image description here


text:
Q: $3D$ rotation matrix uniqueness Given a $3D$ rotation matrix $R$ in a basis $B$. Can we consider $R$ as being unique in $B$? Is there any other $3D$ rotation matrix $R'$ representing the same $3D$ rotation in $B$? How could I prove that?
Note: I do not consider the rotation matrix $R'$ with inverted axis and angle as being the same as $R$.

A: Let's assume the matrix $R$ for a given rotation is not unique and there exists another matrix $Q\neq R$ which performs the exact same rotation. This means
$\forall \mathbf{v}\in\mathbb{R}^n:\quad Q\mathbf{v}=R\mathbf{v}$
and thus
$\forall \mathbf{v}\in\mathbb{R}^n:\quad (Q-R)\mathbf{v}=\mathbf{0}$
This means, that the null-space of $M=(Q-R)$ (the sub-space of all vectors whose image is the zero-vector) has to consist of the whole $\mathbb{R}^n$ (and therefore has a dimension of $n$, of course). The rank-nullity-theorem now states, that the rank of $M$ is the difference of its dimension and the dimension of its null-space, in this case $0$. But then again, only the zero matrix has a rank of $0$.
This means the above equation only holds for $(Q-R)=O$ (with $O$ being the $n\times n$ zero matrix), which in turn implies $Q=R$. This contradicts the assumption. So each rotation (in fact any linear transformation) in $\mathbb{R}^n$ corresponds to a unique $n\times n$ matrix (for a given base $B$, of course). Moreover each orthogonal matrix $R\in\mathbb{R}^{n\times n}$ with $\det R=1$ represents a unique rotation in $\mathbb{R}^n$ (again for a given base $B$ of $\mathbb{R}^n$).
In fact the matrix representation is even more unique than the axis-angle or quaternion representation (not to speak of the ambiguities of Euler angles), since because of the periodicity of the $\sin$ and $\cos$ used in the matrix representation you don't have the angle ambiguity, because $R(\theta)=R(\theta+2\pi k)$. And you don't even have the ambuigity of negated axis and angle (or negated quaternion) being the same rotation (which you especially outruled in your question), because their matrix represntations are in fact the same.

A: I think it is important to state that, althouth the rotation matrix $\mathbf{R}$ is unique for all vectors $\mathbf{v}$, for a given tuple of vectors, $\bar{\mathbf{v_A}}$ and $\mathbf{v_A}$, an infinite number of rotation matrixes $\mathbf{R}_i$ can be found that satisfies:
$ \mathbf{v_A} =\mathbf{R}_i \bar{\mathbf{v_A}} $
being $\mathbf{v_A}$ the position vector of a certain point, $A$, in the 3D space in a global frame, $\bar{\mathbf{v_A}}$ the position vector of the same point, $A$ in a local frame, and  $\mathbf{R}_i$ the rotation matrix between both reference systems.
This statement is fundamental if the requirement is to obtain that rotation matrix from the tuple of arrays as it would lead to an infinity number of solutions if not considered.
For calculating $\mathbf{R}_i$ an overdetermined system of equations (with at least three tuples of arrays) must resolved using, for example, least squared methods to finally obtain that unique rotation matrix.


text:
Q: Tooltip for a ListPlot I have the following values:
DataACT1;(* Being a list of countries - a column in my dataset*)
DataACT2; (* Being a list of happiness scores - a column in my dataset*)
DataACT3; (*List of GDPs - a column in my dataset*)

Then I combined DataACT2 and DataACT3 to generate a listplot:
    DataACT2Combination = Transpose[{DataACT2, DataACT3}];
ListPlot [Tooltip [DataACT2Combination, DataACT1],AxesLabel -> {"Happiness Score", "GDP (per capita)"},PlotLabel -> "GDP (per capita) and Happiness Score",PlotRange -> {{1, 10}, {1, 120000}} ] // Framed

Which gives me to this Plot, with the respective tooltip when going over the dots with the mouse:

The problem is that I want the tooltip to show me just one country per dot (the respective entry of DataACT1 for the combination of the respective DataACT2Combination. Right now Mathematica is giving me the entire entry of DataACT1. How can I change this?

A: You should generate a single tooltip for each country; Tooltip will not automatically thread over the list.
Let's generate some data:
SeedRandom[20200106]
listOfCountries =
  WolframAlpha["countries world", {{"Result", 1}, "Output"},
    InputAssumptions -> {"*MC.%7E-_*DataType-"},
    PodStates -> {"Result__More", "Result__More"}] // ReleaseHold;
happiness = RandomInteger[{0, 10}, Length[listOfCountries]];
gdp = RandomReal[{0, 140000}, Length[listOfCountries]];

Then generate the pairs (Transpose) and associate the name of the country with its data (MapThreading an appropriate Tooltip):
annotated = MapThread[
    Tooltip[#1, #2] &,
    {Transpose@{happiness, gdp}, listOfCountries}
 ];
ListPlot[annotated]

This will generate a plot with each dot annotated with the name of the country it represents:

You could also form an association from your data and then let ListPlot deal with the annotations itself: it will generate some labels as well as all the tooltips you seek. This is perhaps more direct, but I find that it gives you less control on the presentation:
ListPlot@AssociationThread[listOfCountries -> Transpose@{happiness, gdp}]


text:
Q: How do we define what is "External" force or "Internal" force in the context of momentum conservation? I know that without presence of any "External" force momentum is always conserved. But how do we distinguish between "External" force and "Internal" force where all are "Force"?

A: You define a system which you are interested in.
If there is no net external force acting on the system then linear momentum is conserved.
You can identify internal forces as they must occur in equal in magnitude but opposite in direction pairs - Newton's third law.
So you find a force in the system $\:\mathbf{f}_{12}\:$ which is the force on part $1$ of the system due to part $2$ of the system which has its equal in magnitude opposite in direction twin, $\:\mathbf{f}_{21}\:$ force on part $2$ of the system due to part $1$ of the system.
There is no such pairing of forces within the system for external forces which are forces on the system due to something outside the system so their Newton's third law pair would be a force on something outside the system due to force produced by system.

A: For physical systems  the external forces include
1.  Applied Forces
2.  Normal force of reaction
3.  Force due to strings(tension)
4.  Frictional forces between surfaces in contact
    Etc.
Whereas internal force include
1.Force due to gravity between masses
2.Magnetic force between magnetic bodies
3.Electrical force
4 spring force  etc.
To identify force as internal and external one must define the system and its surrounding and then go for classification.
If parts of the same system exert forces on each other ,then they form pairs of internal forces
Internal forces operate such that the overall mechanical energy of a system does not change .
If we have a mechanical system the external forces  are those which applies between part of a system and its surrounding/environment.
Some illustrations:
A batsman hits a cricket ball- the particles of the ball holding together are due to internal forces but the bat forcing the ball through a hit is external force on the ball.
If motion of a lift is our system then a person jumping or playing a ball, doing some exercises inside the lift is due to internal force only .
A vehicle is moving and parts of the vehicle are applying internal forces but the force of friction being applied by the road is external force on the vehicle.
similarly the push of the vehicle   on surface of the road and the normal reaction on it are external force .
It is a misnomer to look for internal force using Newton's third law of action and reaction . As the pair of these forces act on different bodies and are external to them individually.


text:
Q: ¿Cómo puedo comprobar si existe un activity? Estoy haciendo una aplicación android en la que cuando doy logout por ejemplo, me manda a login pero obviamente no tengo que poder regresar al main activity, mi problema es que debido a unas animaciones tengo que cerrar las activity desde la siguiente con un getInstance(), eso lo he puesto en el onTransitionEnd(), pero si una de las activity que cierro nunca ha sido abierta tiene errores, no sé cómo hacer una condición para que solo cierre las que han abierto.
Así se cierran las Activity:
explode.addListener(new Transition.TransitionListener() {
        @Override
        public void onTransitionStart(Transition transition) {

        }

        @Override
        public void onTransitionEnd(Transition transition) {
            MainActivity.getInstance().finish();
            ChangePassActivity.getInstance().finish();
            TermsConditionsActivity.getInstance().finish();
        }

        @Override
        public void onTransitionCancel(Transition transition) {

        }

        @Override
        public void onTransitionPause(Transition transition) {

        }

        @Override
        public void onTransitionResume(Transition transition) {

        }
    });

A: Puedes validar si la instancia es diferente de null, en base a esto proceder a cerrarla
if(MainActivity.getInstance() !=  null){
  MainActivity.getInstance().finish();
}
if(ChangePassActivity.getInstance() !=  null){
   ChangePassActivity.getInstance().finish();
}
if(TermsConditionsActivity.getInstance() !=  null){
   TermsConditionsActivity.getInstance().finish();
}