text:
Q: C# 5 Async Await .Task.Factory.StartNew cancellation I have the async code that implements cancellation token. It's working but Im not pretty sure if this is the right way to do it so I just want feedback about it.
Here is the actual code:
    /// <summary>
    ///
    /// </summary>
    private async void SaveData() {

        if (GetActiveServiceRequest() != null)
        {
            var tokenSource = new System.Threading.CancellationTokenSource();

            this.ShowWizardPleaseWait("Saving data...");

            var someTask = System.Threading.Tasks.Task<bool>.Factory.StartNew(() =>
            {

                bool returnVal = false;

                // Set sleep of 7 seconds to test the 5 seconds timeout.
                System.Threading.Thread.Sleep(7000);

                if (!tokenSource.IsCancellationRequested)
                {
                    // if not cancelled then save data

                    App.Data.EmployeeWCF ws = new App.Data.EmployeeWCF ();
                    returnVal = ws.UpdateData(_employee.Data);
                    ws.Dispose();
                }

                return returnVal;

            }, tokenSource.Token);

            if (await System.Threading.Tasks.Task.WhenAny(someTask, System.Threading.Tasks.Task.Delay(5000)) == someTask)
            {
                // Completed
                this.HideWizardPleaseWait();
                if (someTask.Result)
                {
                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
                }
                else
                {
                    this.DialogResult = System.Windows.Forms.DialogResult.Abort;
                }
                btnOK.Enabled = true;
                this.Close();
            }
            else
            {
                tokenSource.Cancel();

                // Timeout logic
                this.HideWizardPleaseWait();
                MessageBox.Show("Timeout. Please try again.")
            }

        }
    }

Does async / await / cancellation code is well implemented?
Thanks and appreciate the feedback.

A: In general, you should use ThrowIfCancellationRequested. That will complete the returned Task in a canceled state, rather than in a "ran to completion successfully" state with a false result.
Other points:

*

*Avoid async void. This should be async Task unless it's an event handler.

*Prefer Task.Run over TaskFactory.StartNew.

*Use using.

*If you're just using CancellationTokenSource as a timeout, then it has special capabilities for that. Creating a separate task via Task.Delay and Task.WhenAny isn't necessary.

Here's what the updated code would look like:
private async Task SaveData()
{
    if (GetActiveServiceRequest() != null)
    {
        var tokenSource = new System.Threading.CancellationTokenSource(TimeSpan.FromSeconds(5));
        var token = tokenSource.Token;

        this.ShowWizardPleaseWait("Saving data...");

        var someTask = System.Threading.Tasks.Task.Run(() =>
        {
            // Set sleep of 7 seconds to test the 5 seconds timeout.
            System.Threading.Thread.Sleep(7000);

            // if not cancelled then save data
            token.ThrowIfCancellationRequested();
            using (App.Data.EmployeeWCF ws = new App.Data.EmployeeWCF())
            {
                return ws.UpdateData(_employee.Data);
            }
        }, token);

        try
        {
            var result = await someTask;

            // Completed
            this.HideWizardPleaseWait();
            if (result)
            {
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
            else
            {
                this.DialogResult = System.Windows.Forms.DialogResult.Abort;
            }
            btnOK.Enabled = true;
            this.Close();
        }
        catch (OperationCanceledException)
        {
            // Timeout logic
            this.HideWizardPleaseWait();
            MessageBox.Show("Timeout. Please try again.")
        }
    }
}


text:
Q: PHP Shopping Cart Script - When to empty cart? Im working on a shopping cart script in php and need some advice on how to handle the final process.
Once the customer has entered items into the cart, chosen shipping option, and then clicked the checkout button, they are then redirected to a paypal button which is dynamically generated using BMCreateButton.
My question is, when is the best time to empty the customers cart?
I have set up the auto return feature on paypal, which i was goin to use to then empty the cart, but its not very good as customers have to click a link in order to redirect.
So should i empty it when they click the checkout button just before the dynamic button?
I can also use these setting in php to prevent cach back button issues
// Date in the past
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
// Always modified
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
// HTTP/1.1
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
// HTTP/1.0
header("Pragma: no-cache");

What would to guys recommend?
cheers.

A: From Paypal website:
With Auto Return for PayPal Payments Standard, you can avoid making people click a button
to return to your website after they complete their payments with PayPal......NOTE: If you have turned on Auto Return and have chosen to turn on PayPal Account
Optional for new users, a new user will not be automatically directed back to your
website, but will be given the option to return.

Meaning, if you want to auto-redirect to work without the user clicking a link/button, you should disable the option: PayPal Account Optional for new users

A: As soon as you've updated/inserted to the database.
This is because if they go back and add more products, it'll have duplicate entries, and you don't want that.
as soon as you do your database inserting, and header() them off to Paypal etc, clear their cart.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to catch keypress without enter in Golang loop I've got a loop in which some things happen according to the state it runs in (manual/automatic/learning). I now want to be able to let the program switch between these states by pressing the accompanying letters on the keyboard ("m" for manual, "a" for automatic and "l" for learning).
So to do this I need to be able to catch a keypress during the loop and change the variable status accordingly. I now have the following, which can catch a keypress followed by an enter:
ch := make(chan string)
go func(ch chan string) {
    reader := bufio.NewReader(os.Stdin)
    for {
        s, _ := reader.ReadString('\n')
        ch <- s
    }
}(ch)

for {
    select {
        case stdin, _ := <-ch:
            fmt.Println("Keys pressed:", stdin)
        default:
            fmt.Println("Working..")
    }
    time.Sleep(time.Second)
}

But the fact that I need to hit the enter button is not acceptable.
Does anybody know a non-blocking way to catch a keypress of a normal letter (not a SIGINT) without the need to hit enter afterwards?

A: After reading about os.Stdin.Read() and finding this answer I created the following code:
package main

import (
    "fmt"
    "os"
    "time"
    "os/exec"
)

func main() {
    ch := make(chan string)
    go func(ch chan string) {
        // disable input buffering
        exec.Command("stty", "-F", "/dev/tty", "cbreak", "min", "1").Run()
        // do not display entered characters on the screen
        exec.Command("stty", "-F", "/dev/tty", "-echo").Run()
        var b []byte = make([]byte, 1)
        for {
            os.Stdin.Read(b)
            ch <- string(b)
        }
    }(ch)

    for {
        select {
            case stdin, _ := <-ch:
                fmt.Println("Keys pressed:", stdin)
            default:
                fmt.Println("Working..")
        }
        time.Sleep(time.Millisecond * 100)
    }
}

This works like a charm.

A: Because you're using ReadString which expects whichever parameter you give it, in your case - the return key.
According to the docs:

ReadString reads until the first occurrence of delim in the input,
  returning a string containing the data up to and including the
  delimiter.

This means that the method won't return until you hit the return key.
You can use the regular Read method instead, to read the characters you need.
See also this Stackoverflow question for reference.


text:
Q: Eclipse - jUnit Tests not working because of Ebean I'm trying to run the tests for my play 2.2.1 application from withing Eclipse. They are currently not working because of a weird Ebean error that occurs when I run the tests from eclipse.
The Tests are working perfectly fine when I run them from the command line with "play testOnly ...".
I've looked at another solution of that problem (see here) and I did already add -javaagent:C:\Java\play-2.2.1\repository\local\org.avaje.ebeanorm\avaje-ebeanorm-agent\3.2.1\jars\avaje-ebeanorm-agent.jar as a default VM argument in Eclipse. I verified that eclipse is in fact using that jar file since it complains when I point it to a non-existing jar file.
The error message in the eclipse console is: transform> cls: play/db/ebean/Model  msg: ... ignore field _ebean_intercept. The full error output is here.
This is the error message that junit displays:
Configuration error: Configuration error[Cannot register class [models.Game] in Ebean server]
at play.api.Configuration$.play$api$Configuration$$configError(Configuration.scala:92)
at play.api.Configuration.reportError(Configuration.scala:570)
at play.Configuration.reportError(Configuration.java:298)
at play.db.ebean.EbeanPlugin.onStart(EbeanPlugin.java:71)
at play.api.Play$$anonfun$start$1$$anonfun$apply$mcV$sp$1.apply(Play.scala:88)
at play.api.Play$$anonfun$start$1$$anonfun$apply$mcV$sp$1.apply(Play.scala:88)
at scala.collection.immutable.List.foreach(List.scala:318)
at play.api.Play$$anonfun$start$1.apply$mcV$sp(Play.scala:88)
at play.api.Play$$anonfun$start$1.apply(Play.scala:88)
at play.api.Play$$anonfun$start$1.apply(Play.scala:88)
at play.utils.Threads$.withContextClassLoader(Threads.scala:18)
at play.api.Play$.start(Play.scala:87)
at play.api.Play.start(Play.scala)
at play.test.Helpers.start(Helpers.java:359)
at play.test.WithApplication.start(WithApplication.java:18)
at models.GameTest.setUp(GameTest.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.VerifyError: Bad type on operand stack
Exception Details:
  Location:
    models/Game.validate()Ljava/lang/String; @4: invokevirtual
  Reason:
    Type 'models/Team' (current frame, stack[0]) is not assignable to 'models/Game'
  Current Frame:
    bci: @4
    flags: { }
    locals: { 'models/Game' }
    stack: { 'models/Team' }
  Bytecode:
    0000000: 2ab6 0059 b600 5d2a b600 60b6 005d a600
    0000010: 0612 26b0 01b0
  Stackmap Table:
    same_frame(@20)

    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at play.db.ebean.EbeanPlugin.onStart(EbeanPlugin.java:69)
    ... 36 more


text:
Q: What is "Solder Soaking"? I am reading "Advanced Thermal Management Solutions on PCBs for High Power Applications":
https://ats.net/wp-content/uploads/2014/04/Advanced-Thermal-Management-Solutions-on-PCBs-for-High-Power-Applications_APEX2014.pdf
And on page 4 is states that:

It can be seen that the thermal vias are situated in the extended
  thermal pads beside the pad, where the component will be placed. So,
  to avoid the well-known problem of solder soaking, it is not possible
  to place open thermal vias directly underneath a component.

I have never heard of "solder soaking", can someone please explain what the author means?
EDIT:
I found something called "Solder voiding" in another document which seems to be the same thing:

A: It has been mentioned in the comment by Manu But I'll elaborate here in an answer:
When placing thermal vias underneath a component with a thermal tab and these vias are open, then the solder will suck through the vias because of capillarity. When this happens, it can happen that's there's not enough solder left in order to make a reliable bond. The result is that the thermal enhancement effort makes things worse.
The solution is to close the vias through plugging, e.g. with silk screen (=tenting, not recommended as there are no guarantees) or dedicated plugging.


text:
Q: how to display per 2 items of all data with many different divs using jquery? I want to display 3 items per div, with many divs different from the action click on link load more.
my code as below:

        aaa

        bbb

        ccc

        ddd

        eee

        fff

Load more 1

        2_a

        2_b

        2_c

        2_d

        2_e

        2_f

Load more 2

javascipt code:
$(function () {
  $(".wadah__item").slice(0, 2).slideDown().css('display', 'flex');
  $(".LoadMore").on('click', function (e) {
      e.preventDefault();

      $(".wadah__item:hidden").slice(0, 2).slideDown().css('display', 'flex');

      if ($(".wadah__item:hidden").length == 0) {
          $(".LoadMore").fadeOut('slow');
      }

      $('html,body').animate({
          scrollTop: $(this).offset().top
      }, 2000);
  });
});

I want every link load more to be clicked, then the item that appears is 2 from each div.
Link Demo: https://jsfiddle.net/mrcrabs/5g9uao73/13/

A: You need to filter out wadah__item elements based on the clicked element. So get the parent of the clicked element and get hidden elements within that. To get first 2 child you can use :nth-child() pseudo-class selector with formula -n + 2 ( selects 2nd and 1st child).
$(function() {
  $(".wadah .wadah__item:nth-child(-n + 2)").slideDown().css('display', 'flex');
  $(".LoadMore").on('click', function(e) {
    e.preventDefault();

    $(this).parent().find(".wadah__item:hidden").slice(0, 2).slideDown().css('display', 'flex');

    if ($(this).parent().find(".wadah__item:hidden").length == 0) {
      $(this).fadeOut('slow');
    }

    $('html,body').animate({
      scrollTop: $(this).offset().top
    }, 2000);
  });
});

$(function() {

  $(".wadah .wadah__item:nth-child(-n + 2)").slideDown().css('display', 'flex');
  $(".LoadMore").on('click', function(e) {
    e.preventDefault();

    $(this).parent().find(".wadah__item:hidden").slice(0, 2).slideDown().css('display', 'flex');

    if ($(this).parent().find(".wadah__item:hidden").length == 0) {
      $(this).fadeOut('slow');
    }

    $('html,body').animate({
      scrollTop: $(this).offset().top
    }, 2000);
  });
});
.wadah {
  margin: 30px 0;
}

.wadah__item {
  border: 1px solid #ddd;
  border-top: none;
  padding: 1rem;
}

.wadah__item {
  display: none;
}

#loadMore {
  color: green;
  cursor: pointer;
}

#loadMore:hover {
  color: black;
}

#showLess {
  color: red;
  cursor: pointer;
  display: none;
}

#showLess:hover {
  color: black;
}

<!DOCTYPE html>

  <title></title>

    aaa

    bbb

    ccc

    ddd

    eee

    fff

Load more 1

    2_a

    2_b

    2_c

    2_d

    2_e

    2_f

Load more 2

UPDATE : You can even show first 2 elements by using CSS instead of jQuery code.
.wadah .wadah__item:nth-child(-n + 2){
   display : flex;
}

$(function() {

  $(".LoadMore").on('click', function(e) {
    e.preventDefault();

    $(this).parent().find(".wadah__item:hidden").slice(0, 2).slideDown().css('display', 'flex');

    if ($(this).parent().find(".wadah__item:hidden").length == 0) {
      $(this).fadeOut('slow');
    }

    $('html,body').animate({
      scrollTop: $(this).offset().top
    }, 2000);
  });
});
.wadah {
  margin: 30px 0;
}

.wadah__item {
  border: 1px solid #ddd;
  border-top: none;
  padding: 1rem;
}

.wadah__item {
  display: none;
}

#loadMore {
  color: green;
  cursor: pointer;
}

#loadMore:hover {
  color: black;
}

#showLess {
  color: red;
  cursor: pointer;
  display: none;
}

#showLess:hover {
  color: black;
}

.wadah .wadah__item:nth-child(-n + 2) {
  display: flex;
}

<!DOCTYPE html>

  <title></title>

    aaa

    bbb

    ccc

    ddd

    eee

    fff

Load more 1

    2_a

    2_b

    2_c

    2_d

    2_e

    2_f

Load more 2

A: You can use siblings() and only select from siblings of the button click
$(function () {
        $(".wadah__item").slice(0, 2).slideDown().css('display', 'flex');
        $(".LoadMore").on('click', function (e) {
            e.preventDefault();
          let sibs = $(this).siblings(".wadah__item:hidden");
            sibs.slice(0, 2).slideDown().css('display', 'flex');

            if (sibs.length == 0) {
                $(this).fadeOut('slow');
            }

            $('html,body').animate({
                scrollTop: $(this).offset().top
            }, 2000);
        });
    });


text:
Q: Need to construct DFA (deterministic finite automaton) I need to construct a DFA which recognises all the strings made solely from 0s and 1s, so that thay have an even number of zeros and number of ones divisible by 3. I found an automaton for the case of even number of 0s and even number of 1s:

I tried going from here by adding some states, changing branches, etc.. However I remained unsuccessful usually losing track of what's the automaton doing beacuse of branches and states I'd add. Any help would be greatly appreciated.

A: You need states which record the divisibility by 2 and by 3, which means you need 6 states. Just call them 0|0, 1|0, 0|1, 1|1, 0|2, 1|2. The first digit tells you that when you reach the state, you have an even or odd number of zeros, the 2nd digit tells you that when you reach the state, you have a number of 1s that, when divided by 3, give the given modulus.
Your state diagram contains:
0|x   --0-->   1|x
1|x   --0-->   0|x
y|0   --1-->   y|1
y|1   --1-->   y|2
y|2   --1-->   y|0

The start state is 0|0, which is also the only stop state.
The important bit to understand is that each state records the the modulus of the number of zeros or ones read when divided by 2, respectively 3. The 0|0 is then modulus 0 in both cases, which is the accepting criteria. This all works, because the number of different states to keep track of is finite. The name DFA tells us already that it would not work for an infinite number of states to track.

A: One way to view it is that the problem asks for the intersection of 2 languages: one containing an even number of zeroes and another having the number of ones divisible by 3. A way to approach this is to make DFAs for both the languages and then make another DFA which keeps track of the pair of states in each DFA when an input symbol is read.
I have used 'e' and 'o' to denote that the number of zeroes is even or odd respectively. The second digit in each of the states defines the remainder obtained by dividing the number of ones by 3.


text:
Q: Is it possible to specify localhost url in gmail contextual gadget - manifest file < Extension id="Demo Gadget" type="gadget" >
    < Name > Gmail contextual gadget < /Name >
    < Url > http://54.201.166.244:8080/xmlproject/Gadget.xml < /Url >
< Container name="mail" />

Is it possible to specify localhost url in url tag that refer to gadget.xml from gmail contextual gadget manifest file.

A: No. As per the instructions the gadget spec must be published on the public internet.


text:
Q: Store images(jpg,gif,png) in filesystem or DB?
Possible Duplicates:
Which is more secure: filesystem or database?
User images - database vs. filesystem storage
store image in database or in a system file ?

I can't decide which one I should follow. Can you guys give some opinions? Should I store my images in the file-system or DB? (I would like to prevent others from stealing my images)
When you answer this question, please include comparisons of the security, performances etc.
Thanks.

Exact Duplicate: User Images: Database or filesystem storage?
Exact Duplicate: Storing images in database: Yea or nay?
Exact Duplicate: Should I store my images in the database or folders?
Exact Duplicate: Would you store binary data in database or folders?
Exact Duplicate: Store pictures as files or or the database for a web app?
Exact Duplicate: Storing a small number of images: blob or fs?
Exact Duplicate: store image in filesystem or database?

A: It doesn't matter where you store them in terms of preventing "theft". If you deliver the bytestream to a browser, it can be intercepted and saved by anyone. There's no way to prevent that (I'm assuming you're talking about delivering the images to a browser).
If you're just talking about securing images on the machine itself, it also doesn't matter. The operating system can be locked down as securely as the database, preventing anyone from getting at the images.
In terms of performance (when presenting images to a browser), I personally think it'll be faster serving from a filesystem. You have to present the images in separate HTTP transactions anyway, which would almost certainly require multiple trips to the database. I suspect (although I have no hard data) that it would be faster to store the image URLs in the database which point to static images on the file system - then the act of getting an image is a simple file open by the web server rather than running code to access the database.

A: You're probably going to have to get a whole ton of "but the filesystem is a DB" answers.  This isn't one of them.
The filesystem option depends on many factors, for example, does the server have write premissisons to the directory?  (And yes, I have seen servers where apache couldn't write to DocumentRoot.)
If you want 100% cross-compatibility across platforms, then the Database option is the best way to go.  It'll also let you store image-related metadata such as a user ID, the date uploaded, and even alternate versions of the same image (such as cached thumbnails).
On the down side, you need to write custom code to read images from the DB and serve them to the user, while any standard web server would just let you send the images as they are.
When it comes to the bottom line, though, you should just choose the option that fits your project, and your server configuration.

A: Store them in FileSystem, store the file path in the DB.
Of course you can make this scalable and distributed, you just need to keep the images dirs synched between them (for JackM). Or use a shared storage connected to multiple web frontend servers.
Anyway, the stealing part was covered in your other question and is basically impossible. People that can access the images will always be able (with more or less work) to save them locally ... even if it means "print-screen" and paste into photoshop and saving.

A: It depends on how many images you expect to handle, and what you have to do with them. I have an application that needs to temporarily store between 100K and several million images a day. I write them in 2gb contiguous blocks to the filesystem, storing the image identifier, filename, beginning position and length in a database.
For retrieval I just keep the indices in memory, the files open read only and seek back and forth to fetch them. I could find no faster way to do it. It is far faster than finding and loading an individual file. Windows can get pretty slow once you've dumped that many individual files into the filesystem.
I suppose it could contribute to security, since the images would be somewhat difficult to retrieve without the index data.
For scalability, it would not take long to put a web service in front of it and distribute it across several machines.

A: Moving your images into a database and writing the code to extract the image may be more hassle than it's worth. It will all go back to the business requirements surrounding the need to protect the images, or the requirement for performance.
I'd suggest sticking to the tried and true system of storing the filepath or directory location in the DB, and keeping the files on disk. Here's why:

*

*A filesystem is easier to maintain. Some thought has to be put into the structure and organization of the images. i.e. a directory for each customer, and a subdirectory for each [Attribute-X] and another subfolder for each [Attribute-Y]. Keeping too many images in one directory will end up slowing down the file access (i.e. hundreds of thousands)

*If the idea of storing in a DB is a counter-measure against filesystem loss, (i.e. a disk goes down, or a directory is deleted by accident), then I'd counter with the suggestions that when you use source control, it's no problem to retrieve any lost/missing/delete files.

*If you ever need to scale and move to a content distribution scenario, you'd have to move out back to the filesystem or perform a big extract to push out to the providers.

*It also goes with the saying: "keep structured data in a database". Microsoft has an article on Managing Unstructured Data.

*If security is an issue to be addressed, the filesystem has a whole structure with ACLs. Reinventing the wheel on security may be out of scope in the business requirements.

A large amount of discussion for this topic is also found at:

*

*Question 3748

*Question 561447
Having your images stored as varbinary or a blob of some kind (depending on your platform), I'd suggest it's more hassle than it's worth. The effort that you'll need to extend means more code that you'll have to maintain, unit test, and defend against defects.
If your environment can support SQL Server 2008, you can have the best of both worlds with their new FileStream datatype in SQL 2008.

*

*An MSDN article is touting the FileStream datatype in SQL 2008 as high performance.

*SQL Skills has a great article with some SQL 2008 Filestream performance measurements.

*Here is an article addressing varbinary vs. FileStream and performance of both datatypes.

*If you are a SQL Mag subscriber, you can see a great article at SQL Mag on SQL 2008 FileStream.

*Microsoft Research article:To Blob or Not To Blob
I'd love to see studies in real-world scenarios with large user bases like Flickr or Facebook.
Again, it all goes back to your business requirements. Good luck!

A: If you want your application to be scalable, do not use a file system on the actual web servers. You can store the location of files in a persistent datastore such as a database or a NoSQL solution.
For an AWS solution to this for example you should:

*

*Store the images on S3

*Save the S3 key to the database

*Serve yourimages on S3 through cloudfront (Amazon CDN)

A: For a web application I look after, we store the images in the database, but make sure they're well cached in the filesystem.
A request from one of the web server frontends for an image requires a quick memcache
check to see if the image has changed in the database and, if not, serves it from the filesystem. If it has changed it fetches it from the central database and puts a copy in the filesystem.
This gives most of the advantages of storing them in the filesystem while keeping some
of the advantages of database - we only have one location for all the data which makes
backups easier and means we can scale across quite a few machines without issue. It
also doesn't put excessive load on the database.

A: Saving your files to the DB will provide a some security in terms that another user would need access to the DB in order to retrieve the files, but, as far as efficiency goes, a sql query for every image loaded, leaving all the load to the server side. Do yourself a favor and find a way to protect your images inside the filesystem, they are many.

A: The biggest out-of-the-box advantage of a database is that it can be accessed from anywhere on the network, which is essential if you have more than one server.
If you want to access a filesystem from other machines you need to set up some kind of sharing scheme, which could add complexity and could have synchronization issues.
If you do go with storing images in the database, you can still use local (unshared) disks as caches to reduce the strain on the DB. You'd just need to query the DB for a timestamp or something to see if the file is still up-to-date (if you allow files that can change).

A: If the issue is scalability you'll take a massive loss by moving things into the database. You can round-robin webservers via DNS but adding the overhead of both a CGI process and a database lookup to each image is madness. It also makes your database that much harder to maintain and your images that much harder to process.
As to the other part of your question, you can secure access to a file as easily as a database record, but at the end of the day as long as there is an URL that returns a file you have limited options to prevent that URL being used (at least without making cookies and/or javascript compulsory).

A: Store files in a file server, and store primitive data in a database. While file servers (especially HTTP-based) scale well, database servers do not. Don't mix them together.

A: If you need to edit, manage, or otherwise maintain the images, you should store it outside the database.
Also, the filesystem has many security features that a database does not.
The database is good for storing pointers (file paths) to the actual data.


text:
Q: Beyond Hilton-Milner Theorem for an Intersecting Family?  Hilton-Milner tells us about an intersecting family of $k$-size subsets $\mathcal{F}$ from $\binom{[n]}{k}$:
If $|\mathcal{F}| > \binom{n-1}{k-1}-\binom{n-k-1}{k-1}+1$, then all elements of $\mathcal{F}$ share at least 1 element of [n].
The theorem classifies the non-trivial $\mathcal{F}$ if equality occurs i.e. $|\mathcal{F}| = \binom{n-1}{k-1}-\binom{n-k-1}{k-1}+1$.
I was wondering if there are known results/literature to see on classifications with $|\mathcal{F}| < \binom{n-1}{k-1}-\binom{n-k-1}{k-1}+1$, particularly values very close to equality?
I am currently looking at the case of $n=7$, and $k=3$ to get an idea of this (i.e. what can be said about an intersecting family of size 12 < $\binom{6}{2}-\binom{3}{2}+1?)$.

A: There are at least three types of results that spring to mind. One is the Ahlswede-Khachatrian theorem ("the complete intersection theorem"), which for each $n$ and $k < n/2$ will give you tight upper bounds for $t$-intersecting families (families in which every two sets intersect in at least $t$ points). For example, if $k \leq n/3 + 1$ then a $2$-intersecting family has size at most $\binom{n-2}{k-2}$, and so if $|\mathcal{F}| > \binom{n-2}{k-2}$ then there are two sets $S,T \in \mathcal{F}$ such that $|S \cap T| = 1$. They also have a matching Hilton-Milner type result, in which the family is required to have empty intersection ("the complete non-trivial intersection theorem").
A second one is stability results. Such results show that if $|\mathcal{F}| = (1-\epsilon)\binom{n-1}{k-1}$ then there is an element belonging to a $1-O(\epsilon)$ fraction of the sets. One such result is due to Friedgut ("on the measure of intersecting families, uniqueness and stability"), another is due to Keevash ("shadows and intersections: stability and new proofs").
A third one is due to Dinur and Friedgut ("intersecting families are essentially contained in juntas"). For $k = cn$, they show that any intersecting family essentially depends on $O(1)$ points, where the constant depends on $c$. For $k = o(n)$, they can show that any intersecting family has an element common to all but $C \binom{n-2}{k-2}$ of the sets.


text:
Q: Is it possible to thread pool IMAP connections? From what I understand IMAP requires a connection per each user.  I'm writing an IMAP client (currently just gmail) that supports many (100s, 1000s maybe 10000s+) users at a time.  Obviously cutting down the number of open connections would be great.  I'm wondering if it's possible to use thread pooling on my side to connect to gmail via IMAP or if that simply isn't supported by the IMAP protocol.

A: IMAP typically uses SSL over TCP/IP. And a TCP/IP connection will need to be maintained per IMAP client connection, meaning that there will be many simultaneous open connections.
These multiple simultaneous connections can easily be maintained in a non-threaded (single thread) implementation without affecting the state of the TCP connections. You'll have to have some sort of a flow concept per IMAP TCP/IP connection, and store all of the flows in a container (a c++ STL map for instance) using the TCP/IP five-tuple (or socketFd) as a key. For each data packet received, lookup the flow and handle the packet accordingly. There is nothing about this approach that will affect the TCP nor IMAP connections.
Considering that this will work in a single-thread environment, adding a thread pool will only increase the throughput of the application, since you can handle data packets for several flows simultaneously (assuming its a multi-core CPU) You will just need to make sure that 2 threads dont handle data packets for the same flow at the same time, which could cause the packets to be handled out of order. An approach could be to have a group of flows per thread, maybe using IP pools or something similar.


text:
Q: Problems with FastICA, modifying an independent source changes all outputs I'm running into a problem when using sklearn FastICA. I'm trying to predict what the 'measured' variables (X in the code) would be if one of the predicted 'sources' was changing in a given way. I'm modifying this example.
I think the problem is that FastICA approximates the 'mixing' matrix but ica.mixing_ is very different from what I used to generate the data. I understand that the mixing matrix is undefined since the product np.dot(S, A.T) is what is relevant and changing S to S*a and A to A/a will yield the same result for all a != 0.
Any ideas? Thanks for reading and helping
Here is my code.
    # this is exactly how the example start
    np.random.seed(0)
    n_samples = 200
    time = np.linspace(0, 8, n_samples)

    s1 = np.sin(2 * time)  # Signal 1 : sinusoidal signal
    s2 = np.sign(np.sin(3 * time))  # Signal 2 : square signal
    s3 = signal.sawtooth(2 * np.pi * time)  # Signal 3: saw tooth signal

    S = np.c_[s1, s2, s3]
    S += 0.2 * np.random.normal(size=S.shape)  # Add noise

    S /= S.std(axis=0)  # Standardize data
    # Here I'm changing the example. I'm modifying the 'mixing' array
    # such that s1 is not mixed with neither s2 nor s3
    A = np.array([[1, 0, 0], [0, 2, 1.0], [0, 1.0, 2.0]])  # Mixing matrix
    # Mix data,
    X = np.dot(S, A.T)  # Generate observations

    # Compute ICA
    ica = FastICA()
    S_ = ica.fit_transform(X)  # Reconstruct signals
    A_ = ica.mixing_  # Get estimated mixing matrix

    # We can `prove` that the ICA model applies by reverting the unmixing.
    assert np.allclose(X, np.dot(S_, A_.T) + ica.mean_)

    # Here is where my real code starts,
    # Now modify source s1
    s1 *= 1.1
    S = np.c_[s1, s2, s3]
    S /= S.std(axis=0)  # Standardize data

    # regenerate observations.
    # Note that original code in the example uses np.dot(S, A.T)
    # (that doesn't work either). I'm using ica.inverse_transform
    # because it is what is documented but also because there is an
    # FastICA.mean_ that is not documented and I'm hoping
    # inverse_transform uses it in the right way.
    # modified_X =  np.dot(S, A.T)   # does not work either
    modified_X = ica.inverse_transform(S)

    # check that last 2 observations are not changed
    # The original 'mixing' array was defined to mix s2 and s3 but not s1
    # Next tests fail
    np_testing.assert_array_almost_equal(X[:, 1], modified_X[:, 1])
    np_testing.assert_array_almost_equal(X[:, 2], modified_X[:, 2])

A: I'm posting my findings in case it helps anyone.
I think there are 2 problems with the code I posted

*

*When fitting the ICA, the exact 'mixing' matrix is not found and the solution will be leaking source 1 into all measured outputs. The result should be small with lots of data but it should still be there. However, I don't see a change in behavior when increasing the amount of faked data nor when changing FastICA's max_iter or tol parameters.

*Order of sources is unpredictable, in the code I was assuming that found S_ was in the same order as S (which is wrong). Looping over all sources (after fit_transform), changing one at a time I see results that are close to what I expect. Two of the sources (1 and 2 for me) have impacts mostly on measured variables 2 and 3 and the 3rd source has most impact on measured variable 1 with some minor impact on variables 2 and 3.


text:
Q: ASP.NET web form Authentication Roles not returned I have an asp.net application which is only available if a user has access via Active Directory Group "Admin".  The app calls the Account/Login.aspx file if not authenticated.  I am having an issue where no roles are coming back from my Login after authentication.
Below is from my Web.Config
<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="10" path="/" />
</authentication>
<authorization>
  <allow roles="Admin"/>
  <deny users="*"/>
</authorization>

<membership defaultProvider="AspNetActiveDirectoryMembershipProvider">
  <providers>
    <add name="AspNetActiveDirectoryMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider,System.Web, Version=2.0.0.0, Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ADConnectionString" attributeMapUsername="sAMAccountName" connectionUsername="username" connectionPassword="password" connectionProtection="None" />
  </providers>
</membership>
<roleManager enabled="true"/>

I put some code in my site.Master which displays the user and if in the role.
    lblUserName.Text = "Hello " + Context.User.Identity.Name + ".";
    lblAuthType.Text = "Is Admin? " + Context.User.IsInRole("Admin").ToString();

Return value is Hello Name Is Admin? False
When logging it the edits work fine as far as incorrect ID and password if entered.  Also, when debugging I look in the Context.User for Roles and the value is Blank.
Any help is appreciated.

*Follow Up per Response: *
I plugged this in my web.config a
  <roleManager defaultProvider="WindowsProvider" enabled="true" cacheRolesInCookie="false">
      <providers>
        <add
          name="WindowsProvider"
          type="System.Web.Security.WindowsTokenRoleProvider" />
      </providers>
    </roleManager>

Code

lblAuthType.Text = "Is Admin? " + Context.User.IsInRole("Admin").ToString();

Error Message:
Method is only supported if the user name parameter matches the user name in the current Windows Identity.
Stack Trace
[ProviderException: Method is only supported if the user name parameter matches the user name in the current Windows Identity.]
   System.Web.Security.WindowsTokenRoleProvider.GetCurrentWindowsIdentityAndCheckName(String userName) +2256845
   System.Web.Security.WindowsTokenRoleProvider.GetCurrentTokenAndCheckName(String userName) +36
   System.Web.Security.WindowsTokenRoleProvider.GetRolesForUser(String username) +61
   System.Web.Security.RolePrincipal.IsInRole(String role) +9864880
   DelegatePager.SiteMaster.Page_Init(Object sender, EventArgs e) in c:\Source\IMS Web Internal\DelegatePager\DelegatePager\Site.Master.cs:55
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
   System.Web.UI.Control.OnInit(EventArgs e) +92
   System.Web.UI.UserControl.OnInit(EventArgs e) +83
   System.Web.UI.Control.InitRecursive(Control namingContainer) +134
   System.Web.UI.Control.InitRecursive(Control namingContainer) +290
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +489


text:
Q: Pass Session information from one website We have created a project using asp.net 3tire architecture (Farmer System web).  As the 2nd part of that project developed another website using Asp.net MVC4(Portal web). these projects are hosted separately. When the user login to the farmer system he can also use the portal.
when user navigate to the portal, i want to pass the logging session. please anyone tell me how do i do it?

A: Help from this post
Using ServiceStack ISession
ServiceStack has a new ISession interface backed by ICacheClient that lets you share  same ISession between MVC Controllers, ASP.NET base pages and ServiceStack's Web Services which share the same Cookie Id allowing you to freely share data between these web frameworks.
Note: ISession is a clean implementation that completely by-passes the existing ASP.NET session with ServiceStack's own components as described in ServiceStack's MVC PowerPack and explained in detail in the Sessions wiki page.
To easily make use of ServiceStack's Session (Cache & JSON Serializer) have your Controllers inherit from ServiceStackController (in MVC) or PageBase (in ASP.NET)
There is also new Authentication / Validation functionality added in ServiceStack which you can read about on the wiki:

*

*Authentication and authorization

*Validation
Using ASP.NET Session
Essentially ServiceStack is just a set of lightweight IHttpHandler's running on either an ASP.NET or HttpListener host. If hosted in IIS/ASP.NET (most common) it works like a normal ASP.NET request.
Nothing in ServiceStack accesses or affects the configured Caching and Session providers in the underlying ASP.NET application. If you want to enable it you would need to configure it as per normal in ASP.NET (i.e. outside of ServiceStack) see:
http://msdn.microsoft.com/en-us/library/ms178581.aspx
Once configured you can access the ASP.NET session inside a ServiceStack web service via the singleton:
HttpContext.Current.Session

Or alternatively via the underlying ASP.NET HttpRequest with:
var req = (HttpRequest)base.RequestContext.Get<IHttpRequest>().OriginalRequest;
var session = req.RequestContext.HttpContext.Session;

Although because of the mandatory reliance on XML config and degraded performance by default, I prefer to shun the use of ASP.NET's Session, instead opting to use the cleaner Cache Clients included with ServiceStack.
Basically the way Sessions work (ASP.NET included) is a cookie containing a unique id is added to the Response uniquely identifying the browser session. This id points to a matching Dictionary/Collection on the server which represents the browsers' Session.
The IRequiresSession interface you link to doesn't do anything by default, it simply is a way to signal to either a Custom Request Filter or base web service that this request needs to be authenticated (i.e. two places where you should put validation/authentication logic in ServiceStack).
Here's a Basic Auth implementation that looks to see if a web service is Secure and if so make sure they have authenticated.
Here's another authentication implementation that instead validates all services marked with an [Authenticate] attribute, and how to enable Authentication for your service by adding the Attribute on your Request DTO.
New Authentication Model in ServiceStack
The above implementation is apart of the multi-auth provider model included in the next version of ServiceStack. Here's the reference example showing how to register and configure the new Auth model in your application.
Authentication Strategies
The new Auth model is entirely an opt-in convenience as you can simply not use it and implement similar behaviour yourself using Request Filters or in base classes (by overriding OnBeforeExecute). In fact the new Auth services are not actually built-into ServiceStack per-se. The entire implementation lives in the optional ServiceStack.ServiceInterfaces project and implemented using Custom Request Filters.
Here are different Authentication strategies I've used over the years:

*

*Mark services that need authentication with an [Attribute]. Likely the most idiomatic C# way, ideal when the session-id is passed via a Cookie.

*Especially outside of a Web Context, sometimes using a more explicit IRequiresAuthentication interface is better as it provides strong-typed access to the User and SessionId required for Authentication.

*You can just have a 1-liner to authenticate on each service that needs it - on an adhoc basis. A suitable approach when you have very few services requiring authentication.


text:
Q: Wildfly datasource Enable is not working at runtime when configured through CLI We are migrating from jboss Eap 6.4 to Wildfly. During migration, as part of our application installation, we will configure different xa-datasources in domain.xml. This configuration will be done through jboss-cli.sh.
After configuring the data sources, when deploying the ears, (particularly at *-ejb.jar) we are getting an error saying that the 'persistent unit' is not available and the deployment is rolled back.
Loggers are showing the below:
WFLYCTL0180: Services with missing/unavailable dependencies" => ["jboss.persistenceunit.\"xxyy.ear/xxyy-ejb.jar#xxyyDBUnit\" is missing [jboss.naming.context.java.jboss.datasources.xxyyDS]"]
Post restart of the jboss service, the same deployment works fine. So, we believe that the datasources configured in the domain.xml is not activated or enabled (although we have set the attribute 'enabled=true' for the xa-datasource. We could see the following warning while adding the xa-datasource in jboss.
2021-09-21 16:57:48,308 INFO  [org.jboss.as.connector] (Host Controller Service Threads - 8) WFLYJCA0093: The 'enable' operation is deprecated. Use of the 'add' or 'remove' operations is preferred, or if required the 'write-attribute' operation can used to set the deprecated 'enabled' attribute
With this warning, we understood that the enable/disable operation has been removed in the jboss wildfly. Is there anyway we can make it enabled on the runtime without restart of the jboss service.
Below are the commands which we use to create the xa-datasource in wildfly.
/profile=full-ha/subsystem=datasources/xa-data-source=xxyyDS:add(use-java-context=true,use-ccm=false,driver-name=com.mysql,transaction-isolation=TRANSACTION_READ_COMMITTED,min-pool-size=15,max-pool-size=150,pool-prefill=true,flush-strategy=IdleConnections,valid-connection-checker-class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLValidConnectionChecker",stale-connection-checker-class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLValidConnectionChecker",exception-sorter-class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLExceptionSorter",set-tx-query-timeout=true,blocking-timeout-wait-millis=5000,idle-timeout-minutes=1,query-timeout=300,prepared-statements-cache-size=100,share-prepared-statements=true,jndi-name="java:jboss/datasources/xxyyDS",user-name=jboss,password="${VAULT::ds_MySqlDS::password::1}")
/profile=full-ha/subsystem=datasources/xa-data-source=xxyyDS/xa-datasource-properties=DatabaseName:add(value=xxyy_db)
/profile=full-ha/subsystem=datasources/xa-data-source=xxyyDS/xa-datasource-properties=ServerName:add(value=xx-cluster)
/profile=full-ha/subsystem=datasources/xa-data-source=xxyyDS/xa-datasource-properties=AutoReconnectForPools:add(value=true)
/profile=full-ha/subsystem=datasources/xa-data-source=xxyyDS/xa-datasource-properties=AutoReconnect:add(value=true)
/profile=full-ha/subsystem=datasources/xa-data-source=xxyyDS/xa-datasource-properties=useSSL:add(value=false)
/profile=full-ha/subsystem=datasources/xa-data-source=xxyyDS:enable

Any inputs on how to enable the xa-datasource on runtime would help us.

A: You can enable the datasource via the CLI:
/subsystem=datasources/xa-data-source=xxyyDS:write-attribute(name=enabled,value=true)
It might be required to reload:
:reload

A: After running through many trial and error method, we found that when adding the datasources by default it will be in enabled state. So no need to do explicitly enable when adding a datasource.
So we removed the below line from the list of CLIs.
/profile=full-ha/subsystem=datasources/xa-data-source=xxyyDS:enable
Post removing the line, the configuration of datasources through CLI and the deployment of ears went fine without issues. Posting this solution as it will be helpful for others who are facing similar kind of issue.
Finally our datasource CLIs will be like the ones below.

/profile=full-ha/subsystem=datasources/xa-data-source=xxyyDS:add(use-java-context=true,use-ccm=false,driver-name=com.mysql,transaction-isolation=TRANSACTION_READ_COMMITTED,min-pool-size=15,max-pool-size=150,pool-prefill=true,flush-strategy=IdleConnections,valid-connection-checker-class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLValidConnectionChecker",stale-connection-checker-class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLValidConnectionChecker",exception-sorter-class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLExceptionSorter",set-tx-query-timeout=true,blocking-timeout-wait-millis=5000,idle-timeout-minutes=1,query-timeout=300,prepared-statements-cache-size=100,share-prepared-statements=true,jndi-name="java:jboss/datasources/xxyyDS",user-name=jboss,password="${VAULT::ds_MySqlDS::password::1}")
/profile=full-ha/subsystem=datasources/xa-data-source=xxyyDS/xa-datasource-properties=DatabaseName:add(value=xxyy_db)
/profile=full-ha/subsystem=datasources/xa-data-source=xxyyDS/xa-datasource-properties=ServerName:add(value=xx-cluster)
/profile=full-ha/subsystem=datasources/xa-data-source=xxyyDS/xa-datasource-properties=AutoReconnectForPools:add(value=true)
/profile=full-ha/subsystem=datasources/xa-data-source=xxyyDS/xa-datasource-properties=AutoReconnect:add(value=true)
/profile=full-ha/subsystem=datasources/xa-data-source=xxyyDS/xa-datasource-properties=useSSL:add(value=false)


text:
Q: Using Android TabHost to populate parse data I am doing this application  where i need to populate a tabHost list with data from parse.com.
I already have the tabHost working with 2 tabs but i am having trouble calling the information from parse to display into those tabs.
I have already tried to use listView in each tab and used 2 different xml files but nothing is returned.
Any code examples (or examples of populating tabHost) i can use to get the information from parse?
my code so far (MainActivity with CustomAdapter.
public class MainActivity extends AppCompatActivity {

private CustomAdapter urgentTodosAdapter;
private ParseQueryAdapter<ParseObject> mainAdapter;
private ListView dininglist;

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

    TabHost tab = (TabHost) findViewById(R.id.tabHost);
    tab.setup();

    TabHost.TabSpec spec1 = tab.newTabSpec("CONFIRMED");
    spec1.setIndicator("CONFIRMED");
    spec1.setContent(R.id.layout);
    tab.addTab(spec1);

    TabHost.TabSpec spec2 = tab.newTabSpec("PENDING");
    spec2.setIndicator("PENDING");
    spec2.setContent(R.id.layout_two);
    tab.addTab(spec2);

    //Continue to put buttons and call their actions from here
    mainAdapter = new ParseQueryAdapter<ParseObject>(this,  "RestaurantDetail");
    urgentTodosAdapter = new CustomAdapter(this);
    dininglist = (ListView) findViewById(R.id.dining_list_view2);

    dininglist.setAdapter(urgentTodosAdapter);
    urgentTodosAdapter.loadObjects();

}
}

class CustomAdapter extends ParseQueryAdapter<ParseObject> {

public CustomAdapter(Context context) {

    super(context, new ParseQueryAdapter.QueryFactory<ParseObject>(){

        public ParseQuery create() {
            ParseQuery query  = new ParseQuery("RestaurantDetail");
          /* query.whereEqualTo("Name", true);*/
            return query;
        }
    });
}

@Override
public View getItemView(ParseObject object, View v, ViewGroup parent) {
    if (v == null) {

        v = View.inflate(getContext(), R.layout.layout1, null);
    }
    super.getItemView(object, v, parent);

    ParseImageView todoImage = (ParseImageView)          v.findViewById(R.id.icon);
    ParseFile imageFile = object.getParseFile("Logo");
    if (imageFile != null) {
        todoImage.setParseFile(imageFile);
        todoImage.loadInBackground();
    }

    TextView titleTextView = (TextView) v.findViewById(R.id.textView3);
    titleTextView.setText(object.getString("Name"));
    return v;
}
}

and activity_main.xml file.
<TabHost
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/tabHost"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true">

    <LinearLayout
        android:id="@+id/line"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        </TabWidget>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <include
                android:id="@+id/layout"
                layout="@layout/layout1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

            </include>

            <include
                android:id="@+id/layout_two"
                layout="@layout/layout2"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"></include>

        </FrameLayout>

    </LinearLayout>
</TabHost>


text:
Q: Passing data to Php with Jquery Ajax I want to pass two input data to PHP with JQuery ajax I read about json, serialize and similar but I couldn't quite get a grip around it. I got:

<input type="text" id="domain">

<input type="text" id="domain1">

<button id="order">Search</button>

And also what do I need on PHP file because I only got this.
$name=($_GET['']);
$surname =
echo($name) ;
endif;

A: function callAjax() {

    // Get values to send to server
    var domain = $('#domain').val();
    var domain1 = $('#domain1').val();

    $.ajax({
        type: "GET",
        cache: false,
        url: 'getip.php',
        data: {
            domain: domain,
            domain1: domain1
        }

And in php you'll get it as
$domain = $_GET['domain'];
$domain1 = $_GET['domain1'];

Docs: http://api.jquery.com/jQuery.ajax/

A: $.ajax({
    type: "GET",
    cache: false,
    url: 'getip.php',
    data = {
        'domain': $('#domain').val(),
        'domain1': $('#domain1').val()
        };
)};

And in you php file php you can get data with :
$domain = $_GET['domain'];
$domain1 = $_GET['domain1'];

A: Try this:-

<input type="text" id="domain" name = "domain">

<input type="text" id="domain1" name ="domain1">

<button id="order">Search</button>
function callAjax() {

$.ajax({
    type: "GET",
    cache: false,
    url: 'getip.php',
    data:{domain: $('#domain').val(),domain1: $('#domain1').val()}
});

In your php file get it like this:-
$domain = $_GET['domain'];
$domain1 = $_GET['domain1'];

Note:- Please try to read jquery a bit. It will help you.


text:
Q: Asyncpraw unclosed client session withing giving an client session object in logs I was able to implement asyncpraw and it works pretty well and faster but the issue I am facing right now is that I get en error in the logs. The error I get is
I was able to implement asyncpraw and it works pretty well and faster but the issue I am facing right now is that I get en error in the logs. The error I get is
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x15394a310>

I am getting all the text for all the hot comments and here is my code
class SubredditF:
 def __init__(self, token) -> None:
 self.reddit = asyncpraw.Reddit(
 client_id=environ.get("CLIENT_ID"),
 client_secret=environ.get("SECRET_ID"),
 user_agent="Trenddit/0.0.2",
 refresh_token=token,
 username=environ.get("USER_ID"),
 password=environ.get("PASSWORD"),
)
 self.token = token
 self.reddit.read_only = True

My code for getting detail of getting hot posts is
async def get_hot_posts(self, subredditName, num):
        res = []
        subreddit = await self.reddit.subreddit(subredditName)
        async for submission in subreddit.hot(limit=num):
            res.append({
                "title": submission.title,
                "author": str(submission.author),
                "nsfw": submission.over_18,
                "upvote_ratio": submission.upvote_ratio
            })

       return res

The code in which I call it for API endpoint is
@subreddit_routes.route("/subreddit_posts", methods=["GET"])
async def subreddit_get_posts():
    token = FirebaseC().get_token()
    sub = SubredditF(token)
    res = await (sub.get_hot_posts("Canada", 100))
    response = jsonify(authError=True, data={"data": res})
    return response


text:
Q: Using parents(), closest from $(this) function in Jquery I have checkbox like this:
<input class="checkField" onchange="freezeChildren()" type="checkbox" id ="tra"/>

and function to this:
function freezeChildren() {
    if (this !== null && $(this).is(":checked")) {
        var parent = $(this).closest("ul");
        var children = parent.find("input[type=checkbox]");
        children.prop("checked", false);
        children.prop("disabled", true);
    }
}

When I debug, problem is in this part:
$(this).closest("ul");

Jquery does not want to find up with parents/closest function from "this" - checkbox point. Context in visual studio is undifined.
Even this does not work:
$(this).parents('html');

Jquery works, because I checked this and worked:
$.find('html') or $.find('#tra').

I work on IE11. Can someone help?

A: What you want to do is pass event to the function, then use event.currentTarget to get the item that is being affected.
As you see here onchange="freezeChildren()" becomes onchange="freezeChildren(event)"
Then in the function we just utilize that property with event.currentTarget

function freezeChildren(event) {
  let target = event.currentTarget
  if (target !== null && $(target).is(":checked")) {
    var parent = $(target).closest("ul");
    var children = parent.find("input[type=checkbox]");
    children.prop("checked", false);
    children.prop("disabled", true);
  }
}

    <input class="checkField" onchange="freezeChildren(event)" type="checkbox" id="tra" />

The jQuery Way
What you should do is remove the code from the html and use all jquery

$(document).on('change', '.checkField', function(){
  let target = $(this)
  if (target.is(":checked")) {
    var parent = target.closest("ul");
    var children = parent.find("input[type=checkbox]");
    children.prop("checked", false);
    children.prop("disabled", true);
  }
})

    <input class="checkField" type="checkbox" id="tra" />

A: You need to send this to the onchange callback:
<input class="checkField" onchange="freezeChildren(this)" type="checkbox" id ="tra"/>

and then freezeChildren needs a little tweak:
function freezeChildren(elem) {
    if (elem !== null && $(elem).is(":checked")) {
        var parent = $(elem).closest("ul");
        var children = parent.find("input[type=checkbox]");
        children.prop("checked", false);
        children.prop("disabled", true);
    }
}

Here is a working JSBin:


text:
Q: How to return the average of the values stored in an Integer array? The instruction is

Implement the method public static double avg(int[][] a), which returns the average of the values stored in a.

So, I guess I have to write
public static double avg(int[][] a) { // two dimensional arrays?
  // some codes
  return a;
}

I don't understand the sentence "which returns the average of the values stored in a". When I don't even know the values stored in a, how can I get the average?

A: The function takes a 2d array as an argument. I believe you are supposed to do 2 for loops over a and sum each item and then divide by number of total items in the end (average). Then return your double (average) variable, not return a as your code shows.

A: yes I agree with David,
you will need 2 nested for loops to add all the values and return it.
something like...
public static double avg(int [][] a)
    {
        double sum = 0;
        int total = 0;
        for(int i = 0; i < a.length; i++){
            total += a[i].length;
            for (int j = 0; j < a[i].length; j++){
                sum+=a[i][j];
            }
        }
        return sum/total;
    }

and then divide the sum by number of elements.

A: With a double array you have to walkthrough all the items.
The program will count the amount of values in the array and sum all values.
To get the average you have to devide the total by the amount of values.
public static double avg(int[][] a)
{
    int amountOfValues = 0;
    int total = 0;
    for(int y = 0; y < a.length; y++)
    {
        for(int x = 0; x < a[y].length; x++)
        {
            total += a[y][x];
            amountOfValues++;
        }
    }
    return (double)(total)/(double)(amountOfValues);
}


text:
Q: Write Cache in php I need to store the content array in cache, using the provided key. Add current unix timestamp as array element 'created'. Can someone check my code if it is correct or not!
public function writeToCache($key, $content) {
    $this->cacheExtension = new DateTime;

    $file = fopen($this->cacheLocation . $key . $this->cacheExtension->format("y:m:d h:i:s"), "w") or die("Unable to open file!");
    fwrite($file, $content);
    fclose($file);
}

A: I solve the problem. I was dumb!
public function writeToCache($key, $content) {
$date = new DateTime();
$date = $date->format("yy-mm-dd");

$file = fopen($this->cacheLocation . $key . "_created_" . $date, "w") or die("Unable to open file!");
fwrite($file, json_encode($content));
fclose($file);}


text:
Q: Angular Paginator pagination page size option select is under page I'm using copied paginator in Mat
<mat-paginator #paginator
             [length]="dataSource?.data?.length"
             [pageIndex]="0"
             [pageSize]="3"
             [pageSizeOptions]="[3, 5, 10]">
</mat-paginator>

Table works correctly and paginator works correctly, but the page size option is under page. Where can be a problem?

datasource ts:

A: I know it may be late, but for the others - it looks like you didn't add angular material styling: ng add @angular/material. You can also add your own styling.


text:
Q: Yii2 Invalid CAPTCHA action ID in module I am getting the Invalid CAPTCHA action ID Exception in my custom contactus module. I managed to display the captcha but models validation rule throws the invalid action ID exception. Below is my code:
contactus/controllers/DefaultController.php
class DefaultController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => \yii\filters\AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['captcha','index'],
                        'allow' => true,
                    ],
                ]
            ]
        ];
    }

    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    public function actionIndex()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->contact(setting::ADMIN_EMAIL_ADDRESS)) {
            Yii::$app->session->setFlash('contactFormSubmitted');

            return $this->refresh();
        } else {
            return $this->render('index', [
                'model' => $model,
            ]);
        }
    }
}

contactus/models/ContactForm.php
public function rules()
{
    return [
        // name, email, subject and body are required
        [['name', 'email', 'subject', 'body','verifyCode'], 'required'],
        // email has to be a valid email address
        ['email', 'email'],
        // verifyCode needs to be entered correctly
        ['verifyCode', 'captcha','captchaAction'=>'default/captcha'],
    ];
}

contactus/views/default/index.php
 <?php $form = ActiveForm::begin(['id' => 'contact-form']); ?>
            <?= $form->field($model, 'name') ?>
            <?= $form->field($model, 'email') ?>
            <?= $form->field($model, 'subject') ?>
            <?= $form->field($model, 'body')->textArea(['rows' => 6]) ?>
            <?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
                'captchaAction' => 'default/captcha',
                'template' => '

{image}

{input}

',
            ]) ?>

                <?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'contact-button']) ?>

 <?php ActiveForm::end(); ?>

I get the below error:
Exception (Invalid Configuration) 'yii\base\InvalidConfigException' with message 'Invalid CAPTCHA action ID: default/captcha'in E:\wamp\www\yii-application\vendor\yiisoft\yii2\captcha\CaptchaValidator.php:81

Am I missing something?

A: You should modify your validation rule :
['verifyCode', 'captcha','captchaAction'=>'/contactus/default/captcha'],


text:
Q: set font .ttf to C# winform application I have font (.ttf) install to my computer,but when I release my application to another computer the font change. How can I force font not to change?
note: I can't download TFConvert because i have visual studio 2015 not 2010


text:
Q: ASP.NET IIS 10 service .svc error 406 Not Acceptable i have a service .svc hosted on a machine whit windows server 2019 on IIS 10,
im tryng to send a POST request whit postman sending a json whit the following headers:
Postman-Token:  calculated when request is sent>

Content-Lenght: calculated when request is sent

Host:           calculated when request is sent

Accept:         * / *

Content-Type:   application/json

and this in the body:

{

    "orderNumber": "12345",

    "idTransaction":"1",

    "authorization":"auth",

    "amount":"14.95",

    "paymentDate":"2020-01-01",

    "currency":"euro",

    "resultCode": "ok"

}

the service responds correctly and read the json but the status is "406 Not Accettable"

as you can see i have placed the Accept header whit value "* / *" that mean accept every kind of content-type and that is the response that i get
response headers:

Content-Type:   application/json; charset=utf-8

Server:         Microsoft-IIS/10.0

X-Powered-By:   ASP.NET

Date:           Mon, 04 Jan 2021 09:54:27 GMT

Content-Length: 69

response body

"Not found any payment whit numeroOrdine=12345."

the server/service read the json and respond corretly couse the number of order 12345 was an example and dosent exist,
but whit status code 406 not accetable,
i tryed also to add the header Accept-Charset: UTF-8 in the request but the situation dosent change,
i checked on iis on the server and after select on the mime type list i can that application/json is in the list,
Mime type IIS
maybe i have to enable it somewhere else? Specify the mime type in the web.config file?
or it could be something else?
thanks in advance


text:
Q: Congruences and GCDs I want to prove the following:

Theorem: For integers $a,b,x$ and integers $m,n>0$, if \begin{align*}
x&\equiv a \pmod{m} \newline
x&\equiv a \pmod{n} \newline
\gcd(m,n)&=1 \newline \end{align*}
Then $x\equiv a \pmod{m\cdot n}$

I tried using the fact that for some integers $l_1, l_2$ we have $x-a=ml_1, x-a=nl_2$. I wasn't able to manipulate this in any way that gives me $mn|x-a$.

A: For simplicity, let $y = x-a = m\ell_1 = n\ell_2$.
Since $m$ and $n$ are relatively prime, there are integers $s$ and $t$ such that $sm + tn = 1$. Then
$$
y
= (sm+tn)y = smy + tny
= sm \cdot n\ell2 + tn \cdot m\ell_1
= (s\ell_2 + t\ell_1)mn
$$
and so $mn$ divides $y$, i.e. $y \equiv 0 \bmod mn$.

A:
I tried using the fact that for some integers l1,l2 we have x−a=ml1,x−a=nl2. I wasn't able to manipulate this in any way that gives me mn|x−a.

But that would mean $ml_1 = nl_2$.
That means $m|nl_2$.  But $m,n$ are relatively prime so have no factors in common.
So $m|l_2$.  Write $l_2$ as $l_2 =ml_3$ and we have.... $x - a= nl_2 = nml_3$
So $x\equiv a \pmod nm$.

A: You have $ml_1 = nl_2$ and $\gcd(m,n) = 1$.  This gives $m \mid l_2$, so there is an integer $l_3$ such that $x - a = mnl_3$.  Therefore, $mn$ divides $x-a$.


text:
Q: CSS modal doesn't take parent's full height I want the popup modal to take full height, but it doesn't when there's some overflow.
The popup is shown once the user clicks a card. Below, there're images of the behaviors if the user clicks a cards when there's no scroll vs when there's scroll.
The parent section is set to relative and the child modal is set to absolute.
I'm using TailwindCSS and VueJS frameworks.
Parent

        ...

    <SummaryPopUp v-if="popup" @popUp="toggle_popup"/>

Child [Popup]

    <button type="button">
    </button>

Parent height vs Child modal height

Not scrolled vs Scrolled

A: Is there any reason you are not using position: fixed; instead of absolute ?
Since modal is a popup, there is no reason for it to be absolute to anything, since it will overlay the screen and in your case, cover everything.


text:
Q: Select com quantidade indefinidos de condições É o seguinte, eu tenho um campo de pesquisa, e quero pesquisar em locais distintos do que está cadastrados, tipo assim: tenis nike shox preto.
Eu coloco na pesquisa: tenis preto. Se eu usar um descrição like '%tenis preto%' ele não me retornara nada.
Eu teria que colocar descrição like '%tenis%' or descricao like '%preto%'.
Até ai tudo bem, eu coloco no SQL lá duas condições, porem e se ele quiser pesquisar com 3 ou mais palavras, vai variar a quantidade de where que eu preciso usar, tem como fazer isso?
Estou usando:

*

*PHP

*PostgreSQL

A: Não é necessário montar strings, o que aliás é má prática. Basta passar os parâmetros na forma de array com qualquer das duas sintaxes:
select *
from t
where descricao ilike any ('{"%tenis%", "%nike%", "%shox%", "%preto%"}')

select *
from t
where descricao ilike any (array['%tenis%', '%nike%', '%shox%', '%preto%'])

ilike é insensível à caixa. A lógica acima é de or. Se for necessário fazer and troca-se o any por all

A: Uma possibilidade com um resultado mais completo é usar o PHP para dividir a sua pesquisa em palavras separadas, e gerar a clausula WHERE pra você:
<?php

   $pesquisa = 'carro verde amassado ';

   // Aqui você pode juntar vários campos no concat.
   $campo = 'CONCAT( title, " ", description, " ", author)';
   // Ou usar um só, mas nesse caso talvez compense um LIKE tradicional
   // $campo = 'title';

   $palavras = explode( ' ', $pesquisa ); // dividindo as palavras pelo espaço
   $palavras = $array_filter($palavras); // eliminando ítens vazios

   $where = '';
   $cola = 'WHERE ';

   foreach ($palavras as $palavra) {
      $palavra = trim($palavra); //Removendo espaços em branco
      $palavra = mysql_real_escape_string($palavra); // Aqui você sanitiza de acordo com o DB
      $where .= $cola.campo.' LIKE "%'.$palavra.'%" ';
      $cola = 'AND ';
   }

   echo htmlentities( $where );
?>

E o resultado será:
WHERE
   CONCAT( title, " ", description, " ", author) LIKE "%carro%" AND
   CONCAT( title, " ", description, " ", author) LIKE "%verde%" AND
   CONCAT( title, " ", description, " ", author) LIKE "%amassado%"

(quebras de linha adicionadas para facilitar a leitura)
Desta forma a pesquisa encontrará todos esses resultados:
O carro amassado era verde
A carroceria foi atingida por abacates verdes amassados
Verde e amassado carro

Note que apesar de algumas linhas não terem resultados exatos, é melhor ter coisas a mais do que o usuário não encontrar o que precisa. Tenha em mente, no entanto, que o preço que se paga pela complexidade é uma pesquisa mais lenta. LIKE e índices não trabalham bem juntos.

A: Depende da complexidade da funcionalidade que você quer implementar e do tamanho da sua aplicação. Para uma aplicação pequena e simples você pode fixar até três campos, exigir que pelo menos o primeiro esteja preenchido e fazer três likes sendo que os likes dos campos não preenchidos seriam algo como LIKE "%".
Agora se você precisa de mais complexidade e uma aplicação maior sugiro você implementar uma tabela de tags e uma tabela de relacionamento entre tags e registros que você quer retornar.
Ao fazer uma busca tipo google o array de strings é enviado para a função que vai procurar registros que estejam relacionados àquelas tags.
Com um pouco mais de complexidade você pode implementar ranks de tags; ignorar as tags com menor ranks caso elas façam com que não haja um retorno mínimo; ignorar flexões de género, número e verbais; automatizar a extração de tags dos registros; etc
Implementei algo assim uma vez mas para MS-SQL e .Net pois apesar do SGBD ter ferramentas nativas para esse tipo de SELECT a hospedagem não permitia ativa-las (a menos que o servidor fosse dedicado, o que era caro).

A: Amigo. Existe uma solução simples para seu problema.
Estou utilizando o MySql, mas é de fácil alteração para seu caso.
Primeiramente, defina as colunas na qual você quer buscar o valor, imaginando que seja mais de uma.(Funciona para 1 ou N colunas).
/* Colunas da Tabela */
$aColumns = array (
        'ID',
        'PRODUTO',
        'DESCRICAO'
);

Em seguida monte o WHERE:
/* Filtros.. */
$sWhere = "";
if ($_GET ['sSearch'] != "") {
    $sWhere = "WHERE (";
    for($i = 0; $i < count ( $aColumns ); $i ++) {
        $sWhere .= $aColumns [$i] . " LIKE '%" . strtoupper ( mysql_real_escape_string ( $_GET ['sSearch'] ) ) . "%' OR ";
    }
    $sWhere = substr_replace ( $sWhere, "", - 3 );
    $sWhere .= ')';
}

Porém continuará o problema em questão, para a busca, caso seja procurado: Tenis Preto, só irá retornar os valores que contenham o intervalo total.
Como solução, pode-se utilizar o IMPLODE e o EXPLODE:
$busca  = "Tenis Nike Preto"; //Set GET ou POST..
$busca_explode =  explode(' ', $busca); //Desmonta String..
print_r($busca_explode) ; // Visualização como fica..
$busca_total = implode('%', $busca_explode); // Tenis%Nike%Preto
echo '<br>'.$busca_total;

Basta passar este valor para o WHERE acima em vez de buscar direto pelo $_GET ['sSearch'].


text:
Q: Store binary byte values from a FILE into C array I have a file with hexadecimals binary values and what I want is to read those values 2 by 2 byte by byte and store them into an array. I mean:
I have a file(This is not an ascii string,  I need an HEX editor to open this file)
00B011070000FF

and what I want is:
 ITA[0] = 00;
 ITA[1] = B0;
 ITA[2] = 11;
 ITA[3] = 07;
 ITA[4] = 00;
 ITA[5] = 00;
 ITA[6] = FF;

ITA is an unsigned int
How can I do this?
Thanks in advance.
Solution:
    FILE *pFile = fopen("/ita/hex", "r");

    if (!pFile) {
            printf("Error abriendo archivo\n");
        }

    fseek(pFile, 0, SEEK_END);
    int size = ftell(pFile);
    fseek(pFile, 0, SEEK_SET);
    printf("%i\n",size);
    unsigned int ITA[size];
    for (i = 0; i < size; i++) {
        char value;
        fread(&value, 1, 1, pFile);
        ITA[i] = (unsigned int) value;
    }
    fclose(pFile);
    printf(" ITA is : %X", crcFast2(ITA, size));// crcFAST2 calculates the crc of the hexadecimals

Thank you again!!

A: Since the file contains binary data and ITA is an unsigned int array:
#include <stdio.h>

void readBinary(char *const filename, unsigned int *const ITA, const int size) {
    FILE *pFile = fopen(filename, "r");
    for (int i = 0; i < size; i++) {
        char value;
        fread(&value, 1, 1, pFile);
        ITA[i] = (unsigned int) value;
    }
    fclose(pFile);
}

Parameter size should be 7 in the scenario you described.

A: If it is binary then you can just mmap() the file straight into memory
See this page for where I have shamelessly stolen the following code
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>

int fd, pagesize;
unsigned char *data; /* NB note char array not unsigned int as requested */

fd = open("foo", O_RDONLY);
pagesize = getpagesize();
data = mmap((caddr_t)0, pagesize, PROT_READ, MAP_SHARED, fd, pagesize);

Note that the octet data will be packed into a char array, which is a preferable way to store octet data but is not what was requested
Also this: http://www.gnu.org/software/libc/manual/html_node/Memory_002dmapped-I_002fO.html


text:
Q: How to store value and status of checkbox at pageload I wish to store the values of checkboxes along with their status at the time of page load. When I submit the form I want to check if the checkbox 'checked' earlier is 'unchecked'; if so I need to save the values in a string to be used as list in the query. I have tried the following but something is wrong with my syntax. Please help.
<input type="checkbox" name="Periods" value="25301601" />
<input type="checkbox" name="Periods" value="25301602"  checked />

<input type="button" id="buttonStore" value="Store">
<input type="button" id="buttonCompare" value="Compare">
$(document).ready(function() {
    $("#buttonStore").click(function () {
        // save status and value of all the checkboxes
        var periodCHK= [];
        $(":checkbox").each(function (){
            periodCHK["$(this).val()"]=($(this).is(':checked'));//does not store
             alert($(this).is(':checked'));
            alert($(this).val());
        });
        alert(periodCHK);//nothing
        });

     $("#buttonCompare").click(function () {
        var periodstring;
        $(":checkbox").each(function () {
            if (!$(this).is(':checked'))
                //if $(":checkbox").not(':checked')
            {
                //if this one was checked before, grab it and make a string
                if (periodCHK["$(this).val()"])
                {
                    periodstring+=["$(this).val()"] + ",";
                }
            }
            alert(periodstring); // does not loop
        });
    });
});

A: Use $(this).val() without quotes in the following statement. if used with quotes it will be treated as string.
periodCHK[$(this).val()]


text:
Q: Some divs not responding properly in Bootstrap V3 I have a question that has been annoying me for some time.  It should be simple I just cant figure it out.
Basically, on Chrome, most of the divs created on the page http://loveireland.evolvedublin.com/tours/ resize properly when changing the browser size, but there are a couple that overlap eachother.  Between 768px and 991px (so the media queries) the post for National Wax Museum overlaps with Dublin Zoo.  This happens further down the page with a couple of other posts, but the majority of the page is fine.
This is not an issue in Firefox.
Also, when the screen is below 767px, most of the divs then overlap eachother vertically.
I have tried adding in

 in various locations.  I have tried differing variations of col-**-4 which has not helped and I have also tried amending floats but cant seem to get anything to work.
Sample of post HTML:

Dublin Zoo

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed mattis semper lorem, in volutpat mi adipiscing se

                    VIEW TOUR

CSS Used:
.tour-thumb{
margin: 0 0 30px 0;
}

.tour-frame{
border: 1px solid #e5e5e5;
background-color:#ffffff;
height:100%;
}

.tour-thumb-text{
padding: 0 10px 20px 10px;}

.tour-thumb a{
text-decoration:none;}

@media(max-width:767px){}
@media(min-width:768px){.tour-thumb{max-width: 357px !important; height: 390px;}}
@media(min-width:992px){.tour-thumb{max-width: 233px !important; height: 350px;}}
@media(min-width:1200px){.tour-thumb{max-width: 290px !important; height: 350px;}}

.tour-thumb h2{
font-size:12px;
font-weight:bold;
text-transform: uppercase;}

.tour-thumb h2 a{
color: #000000;
letter-spacing:2px;}

.tour-thumb h2 a:hover{
text-decoration:underline;}

.tour-thumb p{
font-size:14px;
letter-spacing:1px;}

.tour-thumb-img{
position:relative;}

.tour-thumb-price{
background: rgb(255,255,255);
background: rgba(255,255,255,0.9);
/*box-shadow: 0px 0px 10px #999999;*/
border: 1px solid #e5e5e5;
border-top: none;
position: absolute;
top:0;
right: 10px;
text-align:center;
padding: 10px;}

.tour-thumb-price h3{
font-size:18px;
font-weight:bold;
color:#8ac736;
padding: 0 0 0 0;
margin: 0 0 0 0;}

.tour-thumb-price p{
font-size:8px;
font-weight:bold;
padding: 0 0 0 0;
margin: 0 0 0 0;}

.thumb-footer{
display:block;
padding-top:10px;}

.tour-thumb .social{
display:inline-block;
float:left;
padding: 6px 0 6px 0;}

.tour-thumb .social img{
border:none;
margin-right:10px;}

.tour-thumb .social a{
color: #ffffff;}

.tour-thumb .green-btn{
float:right;
position:absolute;
right:20px;
/*margin-top:13px;*/}

.tour-thumb .tripadvisor{
/*margin-bottom:30px;*/
float:left;}

.tripadvisor img.trip-icon{
display:inline-block;
margin-top:4px;
float:left;}

.TA_cdsratingsonlynarrow{
display:inline-block;
float:left;}

.tour-detail .cdsROW.narrow{
text-align:left !important;
background-color:#fafafa; !important}

.tour-thumb .cdsROW.narrow{
text-align:left !important;
background-color:#ffffff; !important}

As mentioned, this works in Firefox, although, when the screen is smaller that 767px, the columns do not actually resize which is also an issue does not happen in Chrome oddly enough!
Hopefully someone can help as I am very stuck.
Cheers

A: In the link you post there are css inline in the div adding position:absolute and left and top values, remove it or try to override it with:
@media (min-width: 768px){
    .tour-thumb {
      position: relative !important;
      left: auto !important;
      top: auto !important;
      float: left;
    }
}

A: With help from @Miktown, I added the following to my css which solved the issue:
@media (min-width: 768px) and (max-width: 991px){
    .tour-thumb {
       width:50% !important;
    }

}
@media (max-width: 767px){
    .tour-thumb {
     width:96% !important;
    }

}


text:
Q: Epson PLQ-30M (Matrix) using Olivetti emulation Mode won't print text I'm trying to make a C# program to print to an Epson  PLQ-30M using serial (it has to be serial, sorry) and ESC commands with some reporting, but without success.
Well, first I did use EPSON Mode (Emulation) and ESC codes and all worked good, but the problem is... it won't report problems from printer (besides a response of 10 or 13 (generic error and "ready"), and I need some reporting like "has paper", "cover opened", "end of printing", etc...
    that leads me to change to Olivetti mode which has all this responses I needed and works really well using ESC PR2 codes.
The main problem now is: I can't print any text. Any idea why?
Sending ASCII text and LF Command won't print anything.
Another test I did was to switch to USB and make a simple notepad print, don't print anything only when I'm using Olivetti emulation, other emulations print okay. Any clues?
serialport1 = new SerialPort("COM4", 9600, Parity.Even, 8, StopBits.One);
serialport1.Encoding = Encoding.GetEncoding(28605);  //iso-8859-15  Latin 9 (ISO)
serialport1.DtrEnable = true;
serialport1.RtsEnable = true;
serialport1.Open();
SendEscapeCharacter("" + (char)27 + (char)48); // 1B 30(HEX)  (INIT PRINTER)
SendEscapeCharacter("" + (char)27 + (char)46); // 1B 2E(Automatic operation mode)
SendEscapeCharacter("" + (char)27 + (char)81 + (char)50 + (char)50 + (char)50 + (char)27 + (char)90); // (Line unit page length setting)

serialport1.Write("testing");  // tRYING TO Print "Testing"
SendEscapeCharacter("" + (char)27 + (char)10); //LF
// READY LED IS BLINKING(orange) AND NO PRINTING!


text:
Q: how to get value of input type from dynamic table using jquery I am working on ecommerce website.
My table gets value from session.
It looks like :

On Checkout I want to get all the values of table.
I have used jquery for this.
Here is my code:
<script>
$('#chhk').on('click',function(e) {
                    e.preventDefault();
                    alert('click');
                var table = $("#tbl tbody");

                 table.find('tr').each(function (i, el) {
                    var $tds = $(this).find('td'),
                        product = $tds.eq(2).text(),
                        price = $tds.eq(3).text(),
                        quantity = $tds.eq(4).attr('value'),
                        total = $tds.eq(5).text();

                     alert('Row ' + (i + 1) + ':\nProduct: ' + product
                          + '\nPrice: ' + price
                           + '\nQuantity: ' + quantity
                          + '\nTotal: ' + total);
                });

            });
</script>

Here
'#chhk' is checkout button id
'#tbl' is my table id
I am getting blank value of quantity by this script as it is input field

Any help would be appreciated..

A: Try replace this:
                    quantity = $tds.eq(4).attr('value');

with:
                    quantity = $tds.eq(4).val();

As .attr('value') gives the value at the start, while .val() gives current property.
More info:
jQuery .val() vs .attr("value")

A: replace this:
 quantity = $tds.eq(4).attr('value'),

with
quantity = $tds.eq(4).find("input").val(),

A: well I tried to do it separately and am getting expected result.
$('#chhk').on('click',function(e) {
                e.preventDefault();
                alert('click');
            var table = $("#tbl tbody");

             table.find('tr').each(function (i, el) {
                var $tds = $(this).find('td'),
                    product = $tds.eq(2).text(),
                    price = $tds.eq(3).text(),
                    total = $tds.eq(5).text();
                    var qty = $(this).find('td input:first').val();

                 alert('Row ' + (i + 1) + ':\nProduct: ' + product
                      + '\nPrice: ' + price
                      + '\nTotal: ' + total
                      +'\n Qua:' + qty);
            });

        });

Have dealed quantity separately.


text:
Q: Postman regexp - SyntaxError: Invalid or unexpected token I'm trying to write Postman test and validate personal identification number with regexp. I have validated regexp: \b((([0-2]{1}[0-9]{1}|[3]{1}[0-1]{1})[0-9]{1}[0-9]{1}[0-9]{1}[0-9]{1}(.|\n|\t|)[0-9]{5})|[3]{1}[2]{1}[0-9]{4}(.|\n|\t|)[0-9]{5})\b
Postman test script:
    var req = JSON.parse(pm.request.body.raw);
    pm.expect(req.personnumber).to.match( \b((([0-2]{1}[0-9]{1}|[3]{1}[0-1]{1})[0-9]{1}[0-9]{1}[0-9]{1}[0-9]{1}(.|\n|\t|)[0-9]{5})|[3]{1}[2]{1}[0-9]{4}(.|\n|\t|)[0-9]{5}\b), "wwww" );
});

Postman returns following error while trying to execute test script:
There was an error in evaluating the test script:  SyntaxError: Invalid or unexpected token

A: This error SyntaxError: Invalid or unexpected token comes from that you forgot about / in the beginning and end of regexp:
pm.expect(req.personnumber).to.match( /\b((([0-2]{1}[0-9]{1}|[3]{1}[0-1]{1})[0-9]{1}[0-9]{1}[0-9]{1}[0-9]{1}(.|\n|\t|)[0-9]{5})|[3]{1}[2]{1}[0-9]{4}(.|\n|\t|)[0-9]{5}\b)/, "wwww" );


text:
Q: How to Create function in go lang on Azure dev-ops to list and create work-items anyone have luck trying to create and list work items in dev ops with go lang
I've tried going through the docs but without any look, I need some kind of guidance how to get startet just some simple listing work items in a area and creating a work item
so far i can list items and that is just that
i need a function to create work items or copy current work-items and list them in a specific area, my issue is that my skills in go lang istn so good yet so i difficult to understand the docs on the azure site?
package main

import (
    "context"
    "log"
    "net/http"

    "github.com/google/uuid"
    "github.com/microsoft/azure-devops-go-api/azuredevops"
    "github.com/microsoft/azure-devops-go-api/azuredevops/core"
)

type GetBacklogArgs struct {
    // (required) Project ID or project name
    Project *string
    // (required) Team ID or team name
    Team *string
    // (required) The id of the backlog level
    Id *string
}

type ClientImpl struct {
    Client azuredevops.Client
}

func main() {
    organizationUrl := "<org url>"                       // todo: replace value with your organization url
    personalAccessToken := "<token>" // todo: replace value with your PAT

    // Create a connection to your organization
    connection := azuredevops.NewPatConnection(organizationUrl, personalAccessToken)

    ctx := context.Background()

    // Create a client to interact with the Core area
    coreClient, err := core.NewClient(ctx, connection)
    if err != nil {
        log.Fatal(err)
    }

    // Get first page of the list of team projects for your organization
    responseValue, err := coreClient.GetProjects(ctx, core.GetProjectsArgs{})
    if err != nil {
        log.Fatal(err)
    }

    index := 0
    for responseValue != nil {
        // Log the page of team project names
        for _, teamProjectReference := range (*responseValue).Value {
            log.Printf("Name[%v] = %v", index, *teamProjectReference.Name)
            index++
        }

        // if continuationToken has a value, then there is at least one more page of projects to get
        if responseValue.ContinuationToken != "" {
            // Get next page of team projects
            projectArgs := core.GetProjectsArgs{
                ContinuationToken: &responseValue.ContinuationToken,
            }
            responseValue, err = coreClient.GetProjects(ctx, projectArgs)
            if err != nil {
                log.Fatal(err)
            }
        } else {
            responseValue = nil
        }
    }
}


text:
Q: Is there a modern free-born file system working equally good in Ubuntu and Windows? Is there a modern (I mean excluding Ext2/3 as they are obsolete for general usage when there is Ext4 today) free-born (I mean excluding FAT and NTFS) file system working equally good in Ubuntu and Windows (maybe after installing some extra drivers) (or any active project of such)?

A: There's the Universal Disk Format.
But Ubuntu/Gnome/udev doesn't support it much outside of DVDs. And Windows might not run it from ordinary partitions either without helper tools. But at least there is sufficient kernel support for it be useable as interchange filesystem.
Since it's an ISO standard I'm assuming it's free from discriminatory software-patents.


text:
Q: Strip post_tags from list of returned taxonomy terms Thanks to GhostToast for helping me on my way with this post.
Now I am successfully able to echo out all of the taxonomy associated terms dynamically.
However, this unfortunately also seems to spit out all the site's post_tags too.
So how can I use the following code, but not show the standard post_tags (I'd like to keep the post_tags available for use, just not show them as a result of this query)
// taxonomy term archives
$post_type = get_post_type();
$taxonomies = get_object_taxonomies($post_type);
if(!empty($taxonomies)){
foreach($taxonomies as $taxonomy){
    $terms = get_terms($taxonomy);
    if(!empty($terms)){
        echo "
";
        foreach ( $terms as $term ) {
            echo '
slug, $taxonomy).'">'.     $term->name . "
";
        }
        echo "
";
    }
}
}

A: Use this function to determine if Taxonomy is hierarchical or not:
Function Reference/is taxonomy hierarchical « WordPress Codex
Example:
// taxonomy term archives
$post_type = get_post_type();
$taxonomies = get_object_taxonomies($post_type);
if(!empty($taxonomies)){
foreach($taxonomies as $taxonomy){
    // only want hierarchical -- no tags please
    if(is_taxonomy_hierarchical($taxonomy)){
        $terms = get_terms($taxonomy);
        if(!empty($terms)){
            echo "
";
            foreach ( $terms as $term ) {
                echo '
slug, $taxonomy).'">'.     $term->name . "
";
            }
            echo "
";
        }
    }
}

} // this was missing

A: Not sure what you mean by "I'd like to keep the post_tags available for use" but I see two options here:
$post_type = get_post_type();
$taxonomies = get_object_taxonomies($post_type);
$taxonomies = array_diff($taxonomies,array('post_tag'));
// and then your Loop

Or ...
$post_type = get_post_type();
$taxonomies = get_object_taxonomies($post_type);
if(!empty($taxonomies)){
  foreach($taxonomies as $taxonomy){
    if ('post_tag' === $taxonomy) continue;
    $terms = get_terms($taxonomy);
    if(!empty($terms)){
        echo "
";
        foreach ( $terms as $term ) {
            echo '
slug, $taxonomy).'">'.     $term->name . "
";
        }
        echo "
";
    }
  }
}


text:
Q: Why Api Platform doesnt find anything by uuid SearchFilter I searched for hours now i cant figure out why api-platform SearchFilter doesnt find anything when searching for uuid.
At first the entity:
#[ApiResource]
#[ApiFilter(SearchFilter::class, properties: ['uuid' => 'exact', 'price' => 'exact', 'name' => 'partial'])]
#[ORM\Entity(repositoryClass: ProductRepository::class)]

class Product
{
  use UuidTrait;

  public function __construct()
  {
    $this->uuid = Uuid::v4();
  }
  //other entity Stuff here
}

trait UuidTrait
{
  #[ORM\Id]
  #[ORM\Column(type: 'uuid', unique: true, nullable: false)]
  private ?Uuid $uuid = null;

  public function getUuid(): ?Uuid
  {
      return $this->uuid;
  }

  public function getUuidBase32(): ?string
  {
      return $this->uuid?->toBase32();
  }
}

the endpoint api/products/31343512-3456-7123-4567-123456712345 gives me the exact result. But when i now search by /api/products?uuid[]=31343512-3456-7123-4567-123456712345 to search for more uuid's there are 0 results.
What is the reason for this behavior and how to fix it?


text:
Q: Sorting String Array by Last Name from a File I have a .txt file which contains pairs FirstName LastName, like this:

*

*Sam Foster

*Jack White

*John Abner

*Mike Briggs

*Sarah Mills

(No bullets, of course) The delimiter is space. Task is to sort this file, in java, by last names, so it looks like this:

*

*John Abner

*Mike Briggs

*Sam Foster

*Sarah Mills

*Jack White

I've searched and searched, but found no explanation I can understand. Is there an easy way of doing this?

A: Make sure there is no middle name and there is no suffix like Jr in the end.
Read file into a list:
Scanner s = new Scanner(new File("filepath"));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext())
    list.add(s.next());
s.close();

Define a custom comparator:
static class LastNameComparator implements Comparator<String> {
    public int compare(String b1, String b2) {
        String[] arr1 = b1.split(" ");
        String[] arr2 = b2.split(" ");
        if (arr1.length > 1 && arr2.length > 1)
            return arr1[arr1.length-1].compareTo(arr2[arr2.length-1]);
        else
            return 0;
    }
}

Sort the list using custom comparator:
Collections.sort(list, new LastNameComparator());

Write it back to file:
FileWriter writer = new FileWriter("outFile.txt");
for(String str: list) {
  writer.write(str);
}
writer.close();

A: Just write a Comparator which get the second word in your String and compare them.
public class StringComparator implements Comparator<String> {
  public int compare(String b1, String b2) {
      return b1.split(" ")[1].compareTo(b2.split(" ")[1]);
  }
}

then you can use Arrays.sort(array, new StringComparator());


text:
Q: How to exclude ToolBar from the composite I have created a User Interface in SWT and I have a text box and a ToolItem in my composite. I am able to exclude the text box from the UI by using GridData.exclude and setVisible method of Text control when I select Disable Text box SWT button by using the below code.
buttonOne.addSelectionListener(new SelectionAdapter() {
    public void widgetSelected(SelectionEvent e) {
        GridData griddata = (GridData) txtInput.getLayoutData();
        griddata.exclude = state;
        txtInput.setVisible(!state);
        txtInput.getParent().layout(false);
    }
});

But I am not able to do the same with ToolBar. Now I have to make the Toolbar vanish/exclude which contains the tool item PUSH item from the user interface when I select the Disable ToolItem SWT button and bring it back If I select another SWT button.