text:
Q: How can I use a UNION statement or an OR statement inside psql's UPDATE command? I have an app that vends a 'code' to users through an api. A code belongs to a pool of codes that when a user hits an endpoint, he/she will get a code from this 'pool'. At the moment there is only 1 'pool' of codes where a code can be vended. That idea is best expressed below in the following sql.
<<-SQL
    UPDATE codes SET vended_at = NOW()
      WHERE id = (
        SELECT "codes"."id"
        FROM "codes"
        INNER JOIN "code_batches" ON "code_batches"."id" = "codes"."code_batch_id"
        WHERE "codes"."vended_at" IS NULL
          AND "code_batches"."active" = true
        ORDER BY "code_batches"."end_at" ASC
        FOR UPDATE OF "codes" SKIP LOCKED
        LIMIT 1
      )
    RETURNING *;
 SQL

So basically, when the end point is pinged, I am returning a code that is active and its vended_at field is NULL.
Now what I need to do is to build off of this sql so that a user can get a code from this pool or from a second pool. So for example, lets say that if the user couldn't get a code from this pool (we will call it A represented by the above sql), I need to vend a code from another pool (we will call it B).
I looked up the documentation of postgresql and I think what I want to do is to either 1). Use a UNION somehow to combine pools A and B into one megapool to vend a code or if I can't vend a code through pool A, use postgresql's OR clause to select from pool B.
The problem is that I can't seem to be able to use either of these syntaxes. I've tried something along the lines like this, tweaking it with different variations.
<<-SQL
    UPDATE codes SET vended_at = NOW()
      WHERE id = (
        SELECT "codes"."id"
        FROM "codes"
        INNER JOIN "code_batches" ON "code_batches"."id" = "codes"."code_batch_id"
        WHERE "codes"."vended_at" IS NULL
          AND "code_batches"."active" = true
        ORDER BY "code_batches"."end_at" ASC
        FOR UPDATE OF "codes" SKIP LOCKED
        LIMIT 1
      ) UNION (
          ######## SELECT SOME OTHER STUFF #########
      )
    RETURNING *;
 SQL

or
<<-SQL
    UPDATE codes SET vended_at = NOW()
      WHERE id = (
        SELECT "codes"."id"
        FROM "codes"
        INNER JOIN "code_batches" ON "code_batches"."id" = "codes"."code_batch_id"
        WHERE "codes"."vended_at" IS NULL
          AND "code_batches"."active" = true
        ORDER BY "code_batches"."end_at" ASC
        FOR UPDATE OF "codes" SKIP LOCKED
        LIMIT 1
      ) OR (
          ######## SELECT SOME OTHER STUFF USING OR #########
      )
    RETURNING *;
 SQL

So far the syntax is off and I'm starting to wonder if I can even use this approach for what I'm trying to do. I can't determine if my approach is wrong or if maybe I am using UNION, OR, and SUB-SELECTS wrong. Does anyone have any advice I can try to accomplish my goal? Thank you.
####### EDIT ########
To illustrate and make the concept even easier, I essentially want to do this.
<<-SQL
    UPDATE codes SET vended_at = NOW()
      WHERE id = (
        CRITERIA 1
      )
      OR/UNION
      (
        CRITERIA 2
      )
    RETURNING *;
 SQL

A: Use one table to store both pools.
Add a pool_number column to the codes table to indicate which pool the code is in, then just add
ORDER BY pool_number

to your existing query.


text:
Q: C# SDL.NET, when trying to SetVideoMode using OpenGL nothing happens. What can I be doing wrong? I am trying to create an application that will need to use double buffering (for purpose of Vsync). I am using SDL.NET. From what I understood, in order to have double buffering, I have to SetVideoMode with OpenGl = true.
Here's the code:
        Video.Initialize();

        Video.GLSetAttribute(OpenGLAttr.DoubleBuffer, 1);
        Video.GLSetAttribute(OpenGLAttr.SwapControl, 1);
        Video.GLSetAttribute(OpenGLAttr.RedSize, 8);
        Video.GLSetAttribute(OpenGLAttr.GreenSize, 8);
        Video.GLSetAttribute(OpenGLAttr.BlueSize, 8);
        Video.GLSetAttribute(OpenGLAttr.DepthSize, 16);

        Video.SetVideoMode(VideoInfo.ScreenWidth, VideoInfo.ScreenHeight, false, true, true, true);

If 4th parameter (bool opengl) is false, it works - a new fullscreen window is created and displayed (but I assume, the OpenGLAttr's set above are meaningless in this case).
If 4th parameter is true, nothing happens - a new window gets created (at least, it appears in the list of open windows) but I cannot alt+tab into it.
What am I doing wrong?

A: Okay, I see that the problem was, I didn't output anything on the screen - doing Video.GLSwapBuffers() made the black screen appear.

redpajama_set_name: RedPajamaStackExchange


text:
Q: jquery plugin confirmOn use with live() I have some code. When I clicked on the button, this code returned confirm windows. All work.
But, when I want to click button, which load with ajax, confirm window doesn't return.
Please help me fix  this code.
 $('.button').confirmOn({
            questionText: 'Do you have a car?',
            textYes: 'Yes',
            textNo: 'No'
        },'click', function(e, confirmed) {
            if(confirmed){
               alert('You clicked "Yes"');
            }
        });

A: I don't know how you have written your ajax function, but I am assuming that you are using jQuery for that. If yes then you can move your function into some wrapper function for eg.
function attachConfirmation() {
  $('.button').confirmOn({
        questionText: 'Do you have a car?',
        textYes: 'Yes',
        textNo: 'No'
    },'click', function(e, confirmed) {
        if(confirmed){
           alert('You clicked "Yes"');
        }
    });
}

And call this function on page load for the ".button" class which is not loaded by ajax load.
And again call this function on ajax success so that it will attach with ".button" which is rendered by ajax call.
But in this approach you need to be carefull since you are again calling this function on ajax success it will attach 2 events on previously rendered ".button".
For resolving this issue you can first remove the already attached even then attach it again in ajax success.For eg.
$.ajax({
   url: "some url",
   success: function() {
     $(".button").off("click");
     attachConfirmation();
   }
})

hope this may helps you.


text:
Q: Почему не отрисовывается изображение? Скачиваю изображения через WorkManager и возвращаю пути до них в директории, проблема в том, что не отрисовывается изображение, хотя метод вызывается, и я получаю логи элементов списка. Вот код:
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val downloadRequest = OneTimeWorkRequestBuilder<DownloadWorker>()
            .setConstraints(
                Constraints.Builder()
                    .setRequiredNetworkType(
                        NetworkType.CONNECTED
                    )
                    .build()
            )
            .build()
        val workManager = WorkManager.getInstance(applicationContext)
        setContent {
            MyApplicationTheme {
                // A surface container using the 'background' color from the theme
                Surface(color = MaterialTheme.colors.background) {
                   val navcontroller = rememberNavController()
                    val workInfos = workManager
                        .getWorkInfosForUniqueWorkLiveData("download")
                        .observeAsState()
                        .value
                    val downloadInfo = remember(key1 = workInfos) {
                        workInfos?.find { it.id == downloadRequest.id }
                    }
                        val downloadUri = downloadInfo?.outputData?.getStringArray(WorkerKeys.IMAGE_URI)
                            ?.toList()
                    NavHost
                    if (!(downloadInfo?.state?.name == "SUCCEEDED")) {
                        CircularProgressIndicator()
                    }else{
                        maket(
                            downloadUri, workManager = workManager,
                            downloadInfo = downloadInfo, downloadRequest = downloadRequest
                        )
                    }
                    workManager
                        .beginUniqueWork(
                            "download",
                            ExistingWorkPolicy.KEEP,
                            downloadRequest
                        )
                        //.then(colorFilterRequest)
                        .enqueue()

                }

            }
        }

        }

    @Composable
    fun maket(liveData: List<String>? = null, workManager : WorkManager,
    downloadInfo : WorkInfo?, downloadRequest : OneTimeWorkRequest){
        LazyColumn(
            modifier = Modifier.fillMaxSize(),
        ) {
            //list?.let { list ->
            //if (liveData != null) {
                items(liveData!!) {
                    // Log.d("fsf", it)
                    Row(modifier = Modifier.fillMaxSize()) {
                       //liveData?.let {
                           Image(
                               painter = rememberImagePainter(
                                   data = it.toUri()//imageUri
                               ),
                               contentDescription = null
                           )
                           Log.d("fsfds", it.toString())
                           Image(
                               painter = rememberImagePainter(data = it.toUri()),
                               contentDescription = null
                           )
                       }
                 //   }

                }

          //  }

                //}
              }
            }

А вот workManager:
class DownloadWorker(
    private val context: Context,
    private val workerParams: WorkerParameters
) : CoroutineWorker(context, workerParams) {
    private suspend fun startForegroundService() {

            ForegroundInfo(
                Random().nextInt(),
                NotificationCompat.Builder(context, "download_channel")
                    .setSmallIcon(R.drawable.ic_launcher_background)
                    .setContentText("Downloading...")
                    .setContentTitle("Download in progress")
                    //.setChannelId("download_channel")
                    .build()
            )

    }
    override suspend fun doWork(): Result {
        var response : retrofit2.Response<List<String>>
        //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService()
       // }
        //ResuldDownload.Success
        delay(5000L)
        return withContext(Dispatchers.IO) {
            var id = 0
            val ListImageUri = mutableListOf<String>()
            var ListUrl = listOf<String>()
            Log.d("dfgfd", ListUrl.toString())
            response = ImageApi.instance.downloadImageUrl()
            Log.d("gdfgfd", response.code().toString())
            response.body()?.let {
                ListUrl = it
                Log.d("dfgfd", ListUrl.toString())
            }
            for (i in ListUrl) {
                id++
                var responseImage : retrofit2.Response<ResponseBody>
                try {
                    responseImage = ImageApi.instance.downloadImages(i)
                }catch (e : ConnectException){
                    continue
                }
                  //  delay(2000L)
                //Log.d("sfsd", "sdfsd")
                if (!responseImage.code().toString().startsWith("4")
                    && !responseImage.code().toString().startsWith("5")) {
                    Log.d("sdfsdf", responseImage.code().toString())
                    val file = File(context.cacheDir, "image$id.jpg")
                    val outputStream = FileOutputStream(file)
                    outputStream.use { stream ->
                        try {
                            stream.write(responseImage.body()?.bytes())
                            Log.d("fsfsd", stream.toString())
                        } catch (e: IOException) {
                            return@withContext Result.failure(
                                workDataOf(
                                    WorkerKeys.ERROR_MSG to e.localizedMessage
                                )
                            )
                        }
                    }
                    ListImageUri.add(file.toURI().toString())
                    WorkerKeys.LIST_URI = ListImageUri.toTypedArray()
                }
            }
           // WorkerKeys.ISDOWNLOAD = false
            Result.success(
                workDataOf(WorkerKeys.IMAGE_URI to WorkerKeys.LIST_URI)
                //workDataOf(
                    //WorkerKeys.IMAGE_URI to WorkerKeys.LIST_URI)

                )

        }
        if(!response.isSuccessful) {
            if(response.code().toString().startsWith("5")) {
                return Result.retry()
            }
            return Result.failure(
                workDataOf(
                    WorkerKeys.ERROR_MSG to "Network error"
                )
            )
        }
        return Result.failure(
            workDataOf(WorkerKeys.ERROR_MSG to "Unknown error")
        )

    }
}

A: У меня была подобная проблема. Я получал данные с api, и у меня никак не отрисовывались картинки. После проведенных исследований я увидел, что url картинок был с http протоколом (пример: http://forkify-api.herokuapp.com/images/best_pizza_dough_recipe1b20.jpg). Мне пришлось прописать это в своём application в манифесте чтоб разрешить соединение через http:
android:usesCleartextTraffic="true"

P.S. Не судите строго если ответ будет неправильным. Я новичок, но хотел помочь.


text:
Q: How to measure Down time for VM migration I am using KVM with virt-manager to migrate the virtual machines from one system to another.
VM Migraiton is successfully done and migration time is measured correctly. Now, I am stuck for how to measure downtime.

A: It is not easy to see when a system is stopped but dmesg -w will show something when you resume your system.
The best way might be having a logger running ind a console:
while : ; do sleep 1 ; date +%FT%T >> downtime.log ; done

and then look for missing logging.
You can also calculate downtime at the same time:
while : ; do sleep 1 ; NEW=$(date +%s) ; echo $(date +%FT%T) $((NEW-LST)) >> downtime.log ; LST=$NEW ; done

It is a bit longer so use a script:
#! /bin/bash
LST=$(date +%s)
while : ; do
  sleep 1
  NEW=$(date +%s)
  echo $(date +%FT%T) $((NEW-LST)) >> downtime.log
  LST=$NEW
done


text:
Q: Error when deserializing JSON object "Unexpected character encountered while parsing value: <. Path '', line 0, position 0." I am trying to stream a large JSON file and deserialize item by item during the streaming.
I am using for this test https://github.com/ysharplanguage/FastJsonParser/blob/master/JsonTest/TestData/fathers.json.txt.
This is my code:
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;

namespace AMServices.Controllers
{
    public class FathersData
    {
        public Father[] fathers { get; set; }
    }

    public class Someone
    {
        public string name { get; set; }
    }

    public class Father : Someone
    {
        public int id { get; set; }
        public bool married { get; set; }
        // Lists...
        public List<Son> sons { get; set; }
        // ... or arrays for collections, that's fine:
        public Daughter[] daughters { get; set; }
    }

    public class Child : Someone
    {
        public int age { get; set; }
    }

    public class Son : Child
    {
    }

    public class Daughter : Child
    {
        public string maidenName { get; set; }
    }

    public class StreamerController : ApiController
    {
        static readonly JsonSerializer _serializer = new JsonSerializer();
        static readonly HttpClient _client = new HttpClient();

        [HttpPost]
        [Route("streamer/stream")]
        public async Task<IHttpActionResult> stream()
        {
            string apiUrl = "https://github.com/ysharplanguage/FastJsonParser/blob/master/JsonTest/TestData/fathers.json.txt";

            using (var stream = await _client.GetStreamAsync(apiUrl).ConfigureAwait(false))
            using (var reader = new StreamReader(stream))
            using (var json = new JsonTextReader(reader))
            {
                if (json == null)
                    StatusCode(HttpStatusCode.InternalServerError);

                JsonSerializer serializer = new JsonSerializer();

                JObject obj = JObject.Load(json);
                // Father f = serializer.Deserialize<Father>(json);
            }

            return StatusCode(HttpStatusCode.OK);
        }
    }
}

When i call this WebAPI Controller Method from Postman i get the following error

"ExceptionMessage": "Unexpected character encountered while parsing value: <. Path '', line 0, position 0.",
  "ExceptionType": "Newtonsoft.Json.JsonReaderException",

What is wrong with this code?

A: You are trying to parse an html page.
Try with the raw version :
https://raw.githubusercontent.com/ysharplanguage/FastJsonParser/master/JsonTest/TestData/fathers.json.txt


text:
Q: Where should I put a function that is called many times? This is a follow-up to this question How to avoid repeated code?
I am using ASP.NET 4.0 with C# and I have a function called FillDropDownList(DropDownList ddl, DataTable dt, string dataValueField, string dataTextField, string defValue) which is called multiple times on one of my ASP.NET pages to populate some dropdown lists. I am now finding that I have several pages where I need to populate several dropdownlists in exactly the same way.
Rather than copying and pasting the same code in different pages, should I create a new class and put the method in that new class? How would I call it? What should I call the class? Should it have other functions in it? I was thinking maybe I should call it Util? What would you do?

A: You can create static class and place there your function
public static class DropDownFiller
{
   public static void  FillDropDownList(DropDownList ddl, DataTable dt, string dataValueField, string dataTextField, string defValue)
   {
        /// bla bla
   }
}

Or you can create an extension to DropDownList (it is also a static class)
public static class DropDownListExtension
{
   public static void  FillDropDownList(this DropDownList ddl, DataTable dt, string dataValueField, string dataTextField, string defValue)
   {
        /// bla bla
   }
}

Usage (like method of DropDownList)
yourDropDownList.FillDropDownList(dataTable,valueField,textField,defValue);


text:
Q: Frame morphisms. The following is a well known fact:

A frame morphism $\Phi : B \to A$, considered as a map of posets has a right adjoint $\Psi : A  \to B$.

My question is, under which hypotesis $\Phi \Psi \Phi = \Phi $ or $\Psi \Phi \Psi = \Psi$? I am asking because I do believe this might happen very often.

A: I believe the correct answer is: it's always true.
Observe that since you are dealing with adjunctions between posets you have the units
$$\eta_X \colon X {\longrightarrow} \Psi\Phi(X)$$
and counits
$$\epsilon_Y \colon \Phi\Psi(Y){\longrightarrow} Y$$
applying to them the monotone mappings (functors) $\Phi$ and $\Psi$ respectively you get
$$\Phi(\eta_X) \colon \Phi(X) \to \Phi\Psi\Phi(X)$$
and
$$\Psi(\epsilon_Y) \colon\Psi\Phi\Psi(Y) \to \Psi(Y)$$
which testify that $\Phi(X) \leq \Phi\Psi\Phi(X)$ and $\Psi\Phi\Psi(Y)\leq\Psi(Y)$ for each $X \in B$ and $Y \in A$.
On the other hand we have also the morphisms
$$\eta_{\Psi(Y)}\colon \Psi(Y) \to \Psi\Phi\Psi(Y)$$
and
$$\epsilon_{\Phi(X)} \Phi\Psi\Phi(X) \to \Phi(X)$$
which testify that $\Psi(Y) \leq \Psi\Phi\Psi(Y)$ and $\Phi\Psi\Phi(X)\leq \Phi(X)$.
By anti-symmetric property of the orders you get that $\Phi(X)=\Phi\Psi\Phi(X)$ and $\Psi(Y)=\Psi\Phi\Psi(Y)$ for every $X \in B$ and $Y \in A$.


text:
Q: Is the SSL now obsolete? I begin learn the information protection and start from OpenSSL. But I read on the Wikipedia that SSL have trouble with security that still not solved and anyone must use TLS instead. Is it true?  Is it mean that SSL now obsolete? (because there appears other way of information protection instead fixing SSL)

A: TLS is just the newer name for the protocol formerly named SSL. If you look at the protocol level you see that TLS 1.0 is practically SSL 3.1, TLS 1.1 is SSL 3.2 etc. Versions up to and including version SSL 3.0 are considered broken and should not be used any longer.
Because of this naming in practice "SSL" and "TLS" are often used to mean the same protocol group and often you find also "SSL/TLS" to refer to this protocol group. Usually only if a version number is added they refer to this version only. Libraries like OpenSSL, PolarSSL, MatrixSSL etc implement the protocol group, i.e. SSL and TLS.
To add to this naming confusion "SSL" is often used together with protocols like SMTP (send mail) or IMAP (access mail) to mean a secure connection from start while "TLS" is used in this context to mean secure connection after issuing a specific STARTTLS command. It is better to use "implicit" and "explicit" SSL/TLS instead.

A: SSL as a protocol is insecure, and TLS should be used instead.  However, people often use the name 'SSL' to refer to SSL as well as TLS.  Furthermore, it is often included in many systems as a fallback measure, so that connections can have some security, at least, if TLS isn't available.  The merits of doing this are questionable, as some people feel that this allows developers to be lazy, or not even realize they're using an insecure method.


text:
Q: How do I shuffle an ArrayList, but after shuffling specific indexes stay the same? In my ArrayList, every number has a color assigned to them based on their position within the ArrayList. Numbers in odd indexes are red, numbers in even indexes are blue, and numbers in indexes of multiples of 10 are black. I need to shuffle the list so that after the shuffle, the red numbers are still in odd indexes, the blue numbers are still in even indexes, and the black numbers are still in multiples of ten indexes. I know how to shuffle a whole list, but not specific things like this. How would I go about doing this?
Here is code for context:
/* Term 2 Assignment 5 - Game Wheel */
/* GameWheel class*/
import java.util.*;
import java.lang.*;

public class GameWheel
{
  // List of slices making up the wheel
  private List<Slice> slices;

  // Position of currently selected slice on wheel
  private int currentPos;

  /* Creates a wheel with 40 preset slices which are then randomized (keeping
   * the color pattern the same).
   */
  public GameWheel()
  {
    slices = new ArrayList<Slice>();
    currentPos = 0;
    initGameWheel();
    scramble();
  }

  /* Spins the wheel by so that a different slice is selected. Return that
   * slice (Note: the 20 slices following the current slice are more likely to
   * be returned than the other 20).
   */
  public Slice spinWheel()
  {
    //spin power between range of 1-100 (inclusive)
    int power = (int)(Math.random()*100 + 1);
    int newPos = (currentPos + power) % slices.size();
    currentPos = newPos;
    return slices.get(currentPos);
  }

  /* Helper method for the constructor. Randomizes the positions of the slices
   * that are in the wheel, but without changing the pattern of the colors
   * (i.e. the red slices will still be at odd indices, the black slices at
   * multiples of 10, and the blue slices at all other even indices).
   */
  private void scramble()
  {

  }

  // Helper method which initializes the slices in the wheel
  private void initGameWheel()
  {
    slices.add(new Slice("black", 8000));
    for (int i=1; i < 40; i++)
    {
      if (i%2 == 1)
        slices.add(new Slice("red", i*10));
      else if (i%10 == 0)
        slices.add(new Slice("black", i*200));
      else
        slices.add(new Slice("blue", i*100));
    }
  }

  // Returns the list of slices for this GameWheel
  public List<Slice> getSlices() {
    return slices;
  }
}

and here is how the slices are created:
/* Slice class*/
public class Slice
{
  private String color;
  private int prizeAmount;

  // Creates a slice with color c, and cash prize p
  public Slice(String c, int p) {
   color = c;
   prizeAmount = p;
  }

  // Returns the cash prize in dollars for this slice
  public int getPrizeAmount() {
    return prizeAmount;
  }

  // Returns the color of this slice as a string
  public String getColor() {
    return color;
  }

  /* Returns a string representation of the slice in the following format:
   * Color: red, prize amount: $50.
   */
  public String toString() {
    return "Color: " + color + ", Prize Amount: $" + prizeAmount;
  }
}

any help is appreciated

A: There is no 'easy' (as in, via an existing method like Collections.shuffle) way; you have to program this functionality yourself, but you can of course use some existing stuff to help you out.
One somewhat roundabout way is to 'deconstruct and reconstruct': Write a method that explodes a single list into 3 separate lists (1 for each colour), then shuffle those, then 'reconstruct' your three separate lists back into a single large list, using the obvious algorithm (if index divisible by 10, grab the next from the black list, otherwise if divisible by 2, grab from the blue list, otherwise, grab from the red list).
Another way is to just implement the shuffle algorithm yourself. For context, you're looking for the Fisher-Yates shuffle algorithm, which the implementation of Collections.shuffle also uses. The crucial things to know:

*

*To obtain a random number between 0 and N, call .nextInt(n) on an instance of Random (make a single instance, once, and keep reusing it). Do not use the common (int) (Math.random() * n), which is subtly wrong (pigeonhole principle), and non-idiomatic java.

*fisher yates primarily involves going through the list from the start (index 0) to the second to last element (the one with index list.size() -2). For each element, swap it around with a uniform random chosen element that is itself or any element above it.
In other words, to shuffle 1,2,3,4,5, we start at the 0th element (the 1), and pick any element, uniformly random, from itself and up to swap with. That's a choice of 5 elements, so we call rnd.nextInt(5) to figure it out. That random number could be 0, in which case 'you swap 1 with itself', meaning, it stays where it is (hey, shuffle means random; sometimes a card ends up in the same place in the pile after shuffling a deck of cards!). Then for the next element (the 2; at index 1), you pick any index from itself (so index 1) up to the end, so we call rnd.nextInt(4), and so on.
For this exercise, the tricky bit is to figure out how many valid places 'above you' that you can swap with exist (that'd be the argument you pass to rnd.nextInt(X)), and how to translate the number that your nextInt invocation gives you with the index you now need to swap with.
Note that this algorithm works entirely in place; there is no need for any additional lists or arrays. A single temporary variable in order to enable the swap is all you need.
This sounds like homework, so I'm not going to pre-chew the answer for you. Hopefully this is enough for you to write it yourself. Good luck!

A: Try this solution:
public void shuffle(List<Slice> slices) {
    Map<String, Iterator<Slice>> slicesByColor = slices.stream()
            .collect(groupingBy(Slice::getColor)).entrySet().stream()
            .peek(e -> Collections.shuffle(e.getValue()))
            .collect(toMap(Map.Entry::getKey, e -> e.getValue().iterator()));

    for (int i = 0; i < slices.size(); i++) {
        Iterator<Slice> sliceIterator = slicesByColor.get(colorByIndex(i));
        slices.set(i, sliceIterator.next());
    }
}

private String colorByIndex(int index) {
    if (index % 2 == 1)
        return "red";
    else if (index % 10 == 0)
        return "black";
    else
        return "blue";
}

Output before:
[Color: black, Prize Amount: $8000, Color: red, Prize Amount: $10, Color: blue, Prize Amount: $200, Color: red, Prize Amount: $30, Color: blue, Prize Amount: $400, Color: red, Prize Amount: $50, Color: blue, Prize Amount: $600, Color: red, Prize Amount: $70, Color: blue, Prize Amount: $800, Color: red, Prize Amount: $90, Color: black, Prize Amount: $2000]

Output after:
[Color: black, Prize Amount: $2000, Color: red, Prize Amount: $90, Color: blue, Prize Amount: $800, Color: red, Prize Amount: $70, Color: blue, Prize Amount: $200, Color: red, Prize Amount: $10, Color: blue, Prize Amount: $400, Color: red, Prize Amount: $50, Color: blue, Prize Amount: $600, Color: red, Prize Amount: $30, Color: black, Prize Amount: $8000]

A: I thik you could create 3 different list and shuffle them separately. After that recreate original list using shuffled lists:
public static List<Slice> shuffle(List<Slice> slices) {
    final int total = slices.size();
    List<Slice> red = new ArrayList<>();
    List<Slice> blue = new ArrayList<>();
    List<Slice> black = new ArrayList<>();

    int i = 0;

    for (Slice slice : slices) {
        if (i % 2 == 1)
            red.add(slice);
        else if (i % 10 == 0)
            black.add(slice);
        else
            blue.add(slice);
        i++;
    }

    Collections.shuffle(red);
    Collections.shuffle(blue);
    Collections.shuffle(black);

    Iterator<Slice> itRed = red.iterator();
    Iterator<Slice> itBlue = blue.iterator();
    Iterator<Slice> itBlack = black.iterator();
    slices.clear();

    for (int j = 0; j < total; j++) {
        if (j % 2 == 1)
            slices.add(itRed.next());
        else if (j % 10 == 0)
            slices.add(itBlack.next());
        else
            slices.add(itBlue.next());
    }

    return slices;
}


text:
Q: How to update the small content of a mongodb field using updateMany and replace method? Here's the example
{
  name:"John",
  emailId:"johncoderq@gmail.com"
}

And I wanted to change the emailId to johncoder@gmail.com .
Here I want to update this record by querying with regex and update using replace method.


text:
Q: Casting HTML Object elements? I am trying to tick a checkbox which is inside the first cell of a tablerow.
var checkbox = $(this).find("td").eq(0);

returns an [Object object] but when I use the html() function it is clear that it returns only the code for the input element.
Is it possible to cast the variable checkbox so that I can then check it?

A: You're getting [Object object] because .eq() returns a jQuery object.
You're getting HTML code with .html() because that is a method of the jQuery object, which returns the HTML inside an element (similar to raw Javascript .innerHTML()).
To get the raw HTML DOM element from a jQuery object, you can try something like:
var rawDomElement = $(this).find('td')[0];

EDIT
But if you want to check a checkbox, you can try calling .attr('checked', true) on a jQuery object representing the checkbox DOM element.

A: Try this :
var checkbox = $(this).find("td:first :input[type=checkbox]");
checkbox.prop('checked',!checkbox.prop('checked'));

And I recommend you use jquery's prop method instead of the attr one.

A: var checkbox = $(this).find("td:first").find(':checkbox');


text:
Q: Issue creating a script with dual logic in deeming a website online I am currently trying to create a script that allows me to check multiple web url's in order to see if they are online and active. My company has multiple servers with different environments active (Production, Staging, Development etc.) I need a script that can check all the environments URL's and tell me whether or not they are online each and every morning so I can be ahead of the game in addressing any servers or websites being down.
My issue however is I can't solely base the logic strictly on an HTTP code to deem the site online or not, some of our websites may be online from an HTTP standpoint but have components or webparts of the site that is down displaying an error message on the page.
I am having trouble coming up with a script that can not only check the HTTP status as well as scan the page and parse out any error messages and then write to host based on both pieces of logic whether or not the site is "Online" or "Down"
Here is what I have so far, you will notice it does not include anything regarding parse for key words as I don't know how to implement...
#Lower Environments Checklist Automated Script

Write-Host Report generated at (Get-date)

write-host("Lower Environments Status Check");

$msg = ""
$array = get-content C:\LowerEnvChecklist\appurls.txt
$log = "C:\LowerEnvChecklist\lowerenvironmentslog.txt"

write-host("Checking appurls.txt...One moment please.");

("`n---------------------------------------------------------------------------        ") | out-file $log -Append

Get-Date | Out-File $log -Append

("`n***Checking Links***") | out-file $log -Append
("`n") | out-file $log -Append

for ($i=0; $i -lt $array.length; $i++) {
    $HTTP_Status = -1
    $HTTP_Request = [System.Net.WebRequest]::Create($array[$i])
    $HTTP_Request.Timeout =60000
    $HTTP_Response = $HTTP_Request.GetResponse()
    $HTTP_Status = [int]$HTTP_Response.StatusCode

    If ($HTTP_Status -eq 200) {
    $msg =  $array[$i] + " is ONLINE!"
    }
    Else {
    $msg = $array[$i] + " may be DOWN, please check!"
    }
    $HTTP_Response.Close()
    $msg | Out-File $log -Append -width 120
    write-host $msg
}

("`n") | out-file $log -Append
("`n***Lower Environments Checklist Completed***") | out-file $log -Append

write-host("Lower Environments Checklist Completed");

appurls.txt just contains the internal URLs I need checked FYI.
Any help would be much appreciated! Thanks.

A: Here is something to at least give you an idea what to do. Need to capture the website data in order to parse it. Then we run a regex query against that which is built from an array of strings. Those strings are texts that might be seen on a page that is not working.
# build a regex query of error strings to match against.
$errorTexts = "error has occurred","Oops","Unable to display widget data","unexpected error occurred","temporarily unavailable"
$regex = ($errorTexts | ForEach-Object{[regex]::Escape($_)}) -join "|"

# Other preproccessing would go here

# Loop through each element of the array
ForEach($target in $array){
    # Erase results for the next pass in case of error.
    $result, $response, $stream, $page = $null

    # Navigate to the website.
    $result = [System.Net.WebRequest]::Create($target)
    $response = $result.GetResponse()
    $stream = [System.IO.StreamReader]$response.GetResponseStream()
    $page = $stream.ReadToEnd()

    # Determine if the page is truly up based on the information above.
    If($response.StatusCode -eq 200){
        # While the page might have rendered need to determine there are no errors present
        if($page -notmatch $regex){
            $msg = "$target is online!"
        } else {
            $msg = "$target may be DOWN, please check!"
        }
    } else {
        $msg = "$target may be DOWN, please check!"
    }

    # Log Result
    $msg | Out-File $log -Append -width 120

    # Close the connection
    $response.Close()
}

# Other postproccessing would go here

I wanted to show what a here-string looked like to replace some of your out-file repetition. Your log file header used to be several lines of this. I have reduced it to one.
@"

---------------------------------------------------------------------------
$(Get-Date)
***Checking Links***

"@ | Out-File $log -Append

Also consider CodeReview.SE for critiquing working code. There are other areas which could in theory be improved but are out of scope for this question.


text:
Q: How do you get pygame to give warning when player touches side of screen? I created a game using pygame, and I wanted to get pygame to give an error like "You can't touch the screen sides", when player touches screen side. I tried searching on the internet, but I didn't find any good results. I thought of adding a block off the screen and when the player touches the block, it gives warning but that took way to long and anyways didn't work. I also don't know how to give alert, and then after giving the alert, to get the game started again. Does anyone know how to do this?

A: Define a pygame.Rect object for the player:
player_rect = pygame.Rect(w, y, width, height)

or get a rectangle from the player image (player_image):
player_rect = player_image.get_Rect(topleft = (x, y))

Get the rectangle of the display Surface (screen)
screen_rect = screen.get_rect()

Evaluate if the player is out of the screen:
if player_rect.left < screen_rect.left or player_rect.right < screen_rect.right or \
   player_rect.top < screen_rect.top or player_rect.bottom < screen_rect.bottom:
    printe("You can't touch the screen sides")

See pygame.Rect.clamp() respectively pygame.Rect.clamp_ip():

Returns a new rectangle that is moved to be completely inside the argument Rect.

With this function, an object can be kept completely in the window:
player_rect.clamp_ip(screen_rect)

You can use the clamped rectangle to evaluate whether the player is touching the edge of the window:
screen_rect = screen.get_rect()
player_rect = player_image.get_Rect(topleft = (x, y))

clamped_rect = player_rect.clamp(screen_rect)
if clamped_rect.x != player_rect.x or clamped_rect.y != player_rect.y:
    printe("You can't touch the screen sides")

player_rect = clamped_rect
x, y = player_rect.topleft


text:
Q: HttpClient.PostAsync fails if the ASP.NET server returns RedirectResult On the server side I'm doing:
return Redirect(...); // <- doesn't matter which url

On client side I'm doing
await Http.PostAsync

It always gives an error..:
1- If I set it to "http://www.google.com" I get error:
System.Net.WebException: Error getting response stream (ReadDone2): ReceiveFailure ---> System.Exception:    at System.Net.WebConnection.HandleError(WebExceptionStatus st, System.Exception e, System.String where)

2- If I set it to a relative url like "/", the await times out:
System.Threading.Tasks.TaskCanceledException: A task was canceled

I've been stuck on this problem for a long time, I've finally found that it's all because for some reason HttpClient doesn't like being redirected apparently.
The exact some thing works perfectly fine when I test it in RESTClient in Firefox.
Any ideas?
Edit: Please ignore this question, it's a problem with Mono, complete simple code to reproduce here:
https://forums.xamarin.com/discussion/42410/bug-httpclient-times-out-when-redirected-on-a-post-request


text:
Q: Trusted Certificate fails after upgrade from 4.6.1 to 4.7.2 After upgrading a service written in F# from 4.6.1 to 4.7.2 i startet getting a classic SSL/TLS error "The request was aborted: Could not create SSL/TLS secure channel".

*

*TLS 1.2 is enabled on all servers.

*I verified with Fiddler that the old version and the new version of the application both uses TLS 1.2 as they should and have done for a long time.

*The requests appears to be identical.

*The service runs as a Network Service, however i get the same error if i run it as admin.

*The certificate is selfsigned and placed in Trusted Root Certification Auth.

*The certificate is only used to internal https between our services.

*If I add the certificate to Personal certificates in certmgr the error disappears and the service works!
From my view it is as if after upgrading to 4.7.2 the Trusted Ca certificates are "ignored".
Adding the certificate to Personal when its placed in Trusted Certificates is not a solution.
I havent been able to identify the change which somehow must have been introduced in 4.7.2.
What am i missing?


text:
Q: how to add tooltip for wordpress button? I have tried with plugin its woking fine.
i need without plugin add some tooltip with css.

Parent text
 Tooltip text here!

styles:
.tooltip-box {
 position: relative;
 display: inline-block;
}
.tooltip-box .tooltip-text {
visibility: hidden;
width: 100px;
background-color: black;
color: #fff;
text-align: center;
padding: 6px 0;
position: absolute;
z-index: 1;
}
.tooltip-box:hover .tooltip-text {
visibility: visible;
}

if using some text contents it works fine.
now i m using buttons here

 Tooltip Button

if i use span class also didnt work. usual button style also changed. better solution suggest me Thank you

A: check this for button and text

.tooltip-text {
color:#000;
text-align: center;
padding: 6px 0;
position: absolute;
z-index: 1;
}
.tooltip-text .tooltiptext,  .kt-btn-wrap  .tooltiptext{visibility:hidden;}
.tooltip-text:hover .tooltiptext,
.kt-btn-wrap:hover span.tooltiptext{
visibility: visible;background-color: black;color:#fff;width:100%;
}

Parent text
 Tooltip text here!

 Tooltip Button
Tooltip text here for button!

A: Your actual code should work (granted you're fixing class names – your example code has some "deviations" ...).
Example 1

.kt-button {
  position: relative;
  display: inline-block;
}

.kt-btn-inline {
  border: none;
  appearance: none;
  background-color: transparent;
  padding: 0;
  font-family: inherit;
  font-size: inherit;
}

.kt-btn-inner-text,
.kt-btn-inner {
  visibility: hidden;
  width: 100px;
  color: #fff;
  text-align: center;
  padding: 6px 0;
  position: absolute;
  z-index: 1;
}

.kt-btn-inner-text {
  background-color: black;
  color: #fff;
}

.kt-button:hover .kt-btn-inner {
  visibility: visible;
}

    Button Text (Link)
    Tooltip text

  <button class="kt-button kt-btn-inline button kt-btn-2-action kt-btn-size-custom kt-btn-style-basic kt-
 btn-svg-show-always kt-btn-has-text-true kt-btn-has-svg-false">
    Button Text (Button)
    Tooltip text
  </button>

  <button class="kt-button kt-btn-inline button kt-btn-2-action kt-btn-size-custom kt-btn-style-basic kt-
 btn-svg-show-always kt-btn-has-text-true kt-btn-has-svg-false">
    Button image tooltip

  </button>

So most likely there are some typos in your html or css.
The main concept is perfectly OK:

*

*tooltip parent element has position:relative

*tooltip text gets position: absolute and hidden visibility that's toggled on hover

Example 2: inlined tooltips

* {
  box-sizing: border-box;
}

body {
  font-family: "Segoe UI", sans-serif;
}

:root {
  --border-radius: 0.3em;
  --bg-color: rgba(0, 0, 0, 0.7);
  --padding: 0.3em;
}

button {
  appearance: none;
  border: 1px solid #ccc;
  padding: 0.3em;
  font-size: 2em;
}

.layout {
  width: 50%;
  margin: 0 auto;
}

.tooltip {
  position: relative;
}

span.tooltip {
  font-weight: bold;
}

.tooltip-content:before {
  content: "";
  display: inline-block;
  position: absolute;
  border: var(--padding) solid transparent;
  border-bottom-color: var(--bg-color);
  top: calc((var(--padding) * 2 * -1));
  left: 50%;
  margin-left: calc(var(--padding) / 2 * -1);
  border-radius: 0;
}

.tooltip-content {
  position: absolute;
  top: calc(100% - (var(--padding) * 2));
  left: 50%;
  z-index: 1;
  visibility: hidden;
  opacity: 0;
  margin-top: calc(var(--padding) * 3);
  transform: translateX(-50%);
  display: block;
  background-color: var(--bg-color);
  width: calc(100% + var(--padding));
  width: 100%;
  min-width: 8em;
  color: #fff;
  text-align: center;
  padding: var(--padding);
  padding-top: calc(var(--padding) / 2);
  border-radius: var(--border-radius);
  transition: 0.3s;
  font-size: 1rem;
  line-height: 1.2rem;
  vertical-align: baseline;
  font-weight: normal;
}
.tooltip:hover .tooltip-content {
  visibility: visible;
  opacity: 1;
}

.tooltip-content-img {
  padding: 0!important;
}

<button class="tooltip">Test button
 Tooltip text here!
</button>

Lorem ipsum dolor sit amet, consectetuer adipiscing Tooltip text here! elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, image  pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate

Should work for any parent element. But you might have more specific css rules inherited by your theme or plugins (... uhm, wordpress). So you will need to inspect your computed styles in dev tools if you encounter any issues.


text:
Q: Android - swipe gesture on Table row should give me Button to perform certain actions? Am new to Android and want to use swipe gesture on my table.
I am populating my table using an array list from a SQLite DB.
On swipe of ONE particular row, i want to

*

*show an option button (Update)

*identify the contents of that row (primary key of table?)

*On press of the Update button - move to the next screen with the values of that particular row from the DB

Can someone help me with this?
Current Code
DB table query
cursor = db.query(
                BANKTABLE_NAME,
                new String[]{BANKTABLE_ROW_ID, BANKTABLE_BANKNAME, BANKTABLE_BALAMT, BANKTABLE_CURRENCY},

Populating the Table from the above query
    private void updateTable()
{
    ArrayList<ArrayList<Object>> data = db.getAllRowsAsArrays();

    for (int position=0; position < data.size(); position++)
    {
        TableRow tableRow= new TableRow(this);

        ArrayList<Object> row = data.get(position);

        TextView bankNameN = new TextView(this);
        bankNameN.setText(row.get(1).toString());
        tableRow.addView(bankNameN);

        passCurrency = row.get(3).toString();

        currencyTable();

        TextView balINRA = new TextView(this);
        balINRA.setText(String.valueOf((Integer.parseInt(row.get(2).toString()))*rateForCalc));
        tableRow.addView(balINRA);

        dataTable.addView(tableRow);
    }
}

A: for achieving it you should create custom adapter for list.
Add gesture listener on row layout- Your should use this question for getting information about swap HERE
When user swipe on row while it onItemClickListner call in this listner you get row no of list
so you get information from DB using this row no.
Also implement onClicked listener in side getView method for Button(Update).
I hope its helpful to you.


text:
Q: Jquery form not submitting after validation Not sure why, but my form will not submit after I validate it. I am aware I shouldn't use any input fields with the name or ID of "submit" which I am not doing. I am assuming the prevent default method is stopping the submission? How can I validate before submission?
<form method="post" id="offersForm" enctype="multipart/form-data">
        <input type="text" name="offerTitle" id="offerTitle" maxlength="70" class="form-control yellow" placeholder="Offer title" value="" />

        <input type="submit" id="addOffer" name="addOffer" class="btn button-black" value="Add Offer" />
     </form>

<script type="text/javascript">
$(document).ready(function() {

  $('#offersForm').submit(function(e) {
        e.preventDefault();
        var offerTitle = $('#offerTitle').val();

        $(".error").removeClass('error');

        if (offerTitle.length < 1) {
            $('#offerTitle').addClass('error');
            return false;
        }

        return true

    });
  });
</script>

A: Please check man I have fixed your code.

$(document).ready(function() {

  $('#addOffer').click(function() {

        var offerTitle = $('#offerTitle').val();

        $(".error").removeClass('error');

        if (offerTitle.length < 1) {
            $('#offerTitle').addClass('error');
            return false;
        }
      $('#offersForm').submit();
        return true

    });
  });
.error{
    border-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="offersForm" enctype="multipart/form-data">
        <input type="text" name="offerTitle" id="offerTitle" maxlength="70" class="form-control yellow" placeholder="Offer title" value="" />

        <input type="button" id="addOffer" name="addOffer" class="btn button-black" value="Add Offer" />
     </form>

A:

$(document).ready(function() {

  $('#addOffer').click(function(e) {
        e.preventDefault();
        var offerTitle = $('#offerTitle').val();

        $(".error").removeClass('error');

        if (offerTitle.length < 1) {
            $('#offerTitle').addClass('error');
            return false;
        }
      $('#offersForm').submit();
        return true

    });
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="offersForm" enctype="multipart/form-data">
        <input type="text" name="offerTitle" id="offerTitle" maxlength="70" class="form-control yellow" placeholder="Offer title" value="" />

        <input type="button" id="addOffer" name="addOffer" class="btn button-black" value="Add Offer" />
     </form>


text:
Q: Use aws/aws-sdk-php with Google Cloud Storage Google Cloud Storage (not the same as Google Drive) appears to have compatibility with S3 APIs:
https://developers.google.com/storage/docs/migrating#migration-simple
Does anyone know if I can use the aws/aws-sdk-php (https://packagist.org/packages/aws/aws-sdk-php) package and configure it to connect to my Google Cloud Storage instead of AWS S3?
I have tried the following code:
<?php
use Aws\S3\S3Client;
use League\Flysystem\Filesystem;
use League\Flysystem\Adapter\AwsS3 as Adapter;
require_once 'vendor/autoload.php';
error_reporting(E_ALL & ~E_NOTICE);
ini_set('display_errors', 1);

$client = S3Client::factory(array(
    'key'    => 'MY_GCS_KEY',
    'secret' => 'MY_GCS_SECRET',
    'endpoint' => 'storage.googleapis.com'
));
$filesystem = new Filesystem(new Adapter($client, 'MY_GCS_BUCKET'));
$filesystem->write('filename.txt', 'contents');

But this give me an error:

Fatal error: Uncaught Aws\S3\Exception\InvalidAccessKeyIdException: AWS Error Code: InvalidAccessKeyId, Status Code: 403, AWS Request ID: BF7C1317719A4C67, AWS Error Type: client, AWS Error Message: The AWS Access Key Id you provided does not exist in our records., User-Agent: aws-sdk-php2/2.6.15 Guzzle/3.9.2 curl/7.32.0 PHP/5.5.4-1+debphp.org~raring+1 thrown in /var/www/prudhub/dev/vendor/aws/aws-sdk-php/src/Aws/Common/Exception/NamespaceExceptionFactory.php on line 91

Anyone know how or if I can properly setup the aws/aws-sdk-php package to connect to Google Cloud Storage instead?
EDIT
Here is the code that made it work:
<?php
use Aws\S3\S3Client;
use League\Flysystem\Filesystem;
use League\Flysystem\Adapter\AwsS3 as Adapter;
require_once 'vendor/autoload.php';

$client = S3Client::factory(array(
    'key'    => 'MY_GCS_KEY',
    'secret' => 'MY_GCS_SECRET',
    'base_url' => 'https://storage.googleapis.com'
));
$filesystem = new Filesystem(new Adapter($client, 'MY_GCS_BUCKET'));
$filesystem->write('filename.txt', 'contents');

A: endpoint is the wrong key. It should be base_url.
http://docs.aws.amazon.com/aws-sdk-php/guide/latest/configuration.html#setting-a-custom-endpoint


text:
Q: flex-slider first slide has wrong height on mobile I have enabled smooth height on flex-slider but the content on the first slide gets cropped as on this image screenshot. I checked with code inspector and noticed it gets the wrong height. When I navigate to the next slide and back to the first, it now gets the correct height. Where might be the problem?
Correct image Screenshot

A: This question is not related to Drupal, you have a css/js issue.
A quick search returns some issues similar to yours:
https://drupal.stackexchange.com/questions/125105/flexslider-cant-adjust-height
FlexSlider Auto Height still leaving a space below slider
Before asking for help, you should at least provide some code and the solutions you already tested and did not work.


text: Q: what are the memory impacts of increasing a NIC's ring buffer? What impact (if any) does NIC ring buffer tuning (e.g. via ethtool -G eth0 …) have on system memory utilization? For example, does increasing the ring buffer consume more RAM? And if so, how much? Or is the memory required for the "maximum" value already always preallocated — for example, in hardware?


text:
Q: Restructured text: Fall back if doctest module is missing It seems that Github does not support the sphinx.ext.doctest syntax in their reStructuredText renderer, which is causing some problems when trying to include a doctest-style code block (.. doctest) in a README.rst which is transcluded into the documentation index (which is rendered by sphinx). If I replace the .. doctest directive with something else, it doesn't render properly as a doctest on Sphinx, but if I don't remove the directive, the code block doesn't render at all (see this gist).
Ideally I'd like to find a solution which just does the right thing in both environments, but failing that, is there a way to fall back to a .. code block or some other supported format (e.g. the rST equivalent of a <NoScript> tag)?


text:
Q: XXClone as a tool for migrating Windows XP Home from PATA to SATA HD Has anybody had any experience using XXClone as a tool for cloning an existing installation of Windows in order to move it from an old PATA drive to a new, larger SATA without having to reinstall everything? Did you have any problems? Or can you recommend an alternative (free) software tool that you know - preferably from repeated experience - is reliable?
I'm looking to move Windows XP Home SP3 to a new disk: same file system, same partition size.
Thanks for looking.

A: I don't have specific experience for this procedure, I think it would work, but mind one thing, win xp don't support SATA drive natively, it needs an additional driver. This issue has been resolved with newer motherboard that can be configured to run SATA drives as IDE, before doing this procedure I would try to install winxp from disc to the SATA drive, if the procedure starts you are good to go, otherwise find the driver for your SATA drive model and install it in your old drive, THEN clone with XXClone.


text:
Q: PHP Variable in MySQL Query from list explode I have a section of code that I can't get to work. the $num variable needs to be passed to the mysql query so it update the latest record with the $num.
The code works when I set $num_d = '1234';
How can I pass the $num variable to the query statement
 $test_message ="$full, $t_phone_number, $f_phone_number";

//explode sms message into variables
list($name, $status, $timecode, $latitude, $longitude, $num, $city, $state, $t_phoneb, $t_phone, $f_phone) = explode("," , $test_message);

print_r(explode(',', "$test_message"));

$num_ext = explode(",", $test_message);
$num_d = (string)$num_ext[5];

// Update database table
 mysql_query("UPDATE msg SET timecode_off= '$timecode' WHERE (num= '$num_d') ORDER BY id DESC LIMIT 1");

A: If the $test_message is formatted right, you should be able to use $num directly like:
mysql_query("UPDATE msg SET timecode_off= '$timecode' WHERE (num= '$num') LIMIT 1");

A: $test_message ="$full, $t_phone_number, $f_phone_number";
$num_ext = explode(",", $test_message);

The result is:
$num_ext[0] = $full;
$num_ext[1] = $t_phone_number;
$num_ext[2] = $f_phone_number; and so on

$num_d = $num_ext[5];
$sql = "UPDATE msg SET timecode_off= '$timecode' WHERE num='$num_d' ORDER BY id DESC LIMIT 1"
$query = mysql_query($sql, $connection);

A: the index "5" in $num_ext is not exists.if you sure that the num_d always in the end of the the exploded array you can use
$num_d = (string) end($num_ext);

A: Your code looks to buggy, also three lines doing the same
/* Here, what is the $full format? I looks like a string with coma separated */
$test_message ="{$full}, {$t_phone_number}, {$f_phone_number}";

/* Mapping the array without spaces */
$array = array_filter(array_map('trim', explode(',', $test_message)));

/* Update database table */
 mysql_query("UPDATE msg SET timecode_off= '{$array[2]}' WHERE (num= '{$array[5]}');") or die (mysql_error());

I guess, this code must work, however I don't know the $full structure, another think to take care is the ORDER BY restriction, that is for SELECT clause, no for UPDATE clause, probably you need a WHERE

A: First drop the ORDER BY clause. that is for select statement. Next, echo all of your strings before you store them in the database to get an idea what should be stored and what is actually stored. If output does not give you a clue what went wrong then post the output here.


text:
Q: A rare integral involving $\operatorname{Li}_2$ A rare but interesting integral problem:
$$\int_{0}^{1}
\frac{\operatorname{Li}_2(-x)-
\operatorname{Li}_2(1-x)+\ln(x)\ln(1+x)+\pi x\ln(1+x)
-\pi x\ln(x)}{1+x^2}\frac{\text{d}x}{\sqrt{1-x^2} }
=\frac{\pi^3}{48\sqrt{2} }.$$
Where $\operatorname{Li}_2$ is dilogarithm.
The integral without the factor $\frac{1}{\sqrt{1-x^2} }$ is much easier(it can be expressed using $\operatorname{Li}_3$,$\ln(2)$,Catalan's constant and $\pi$).
However, the same idea dosen't work for this one. Any suggestion will be much appreciated.

A: We begin by separating the integral into three parts:
$$I = \pi \color{red}{\overbrace{\int_{0}^{1} \frac{x \ln (1+x)}{(1+x^2) \sqrt{1-x^2}} \, dx}^J} - \pi \color{blue}{\overbrace{\int_{0}^{1} \frac{ x \ln (x)}{(1+x^2) \sqrt{1-x^2}} \, dx}^K} + \color{purple}{\underbrace{\int_{0}^{1}\frac{\operatorname{Li}_2(-x)-\operatorname{Li}_2(1-x)+\ln(x)\ln(1+x)}{(x^2+1)\sqrt{1-x^2}} \, dx}_L}$$
We begin by evaluating $\color{red}{J}$:
$$J := \int_{0}^{1}\frac{x\ln(x+1)}{(x^2+1)\sqrt{1-x^2}} \, dx$$
Consider
\begin{align*}\int_{0}^{1}\frac{x(\ln(x+1)+\ln(1-x))}{(x^2+1)\sqrt{1-x^2}} \, dx&=-\frac{2}{\sqrt{2}}\int_{0}^{1}\frac{x}{1-x^2}\operatorname{artanh}\left(\frac{\sqrt{1-x^2}}{\sqrt2}\right) \, dx\\&=-\frac{2}{\sqrt{2}}\int_{0}^{1}\frac{1}{u}\operatorname{artanh}\left(\frac{u}{\sqrt2}\right)\,du \\&= -\frac{2}{\sqrt2}\left(-\frac{\pi^2}{48}+\frac{\ln^2(2)}{8}+\operatorname{Li}_2\left(\frac{1}{\sqrt2}\right)\right)\end{align*}
Consider now
\begin{align*}\int_{0}^{1}\frac{x(\ln(x+1)-\ln(1-x))}{(x^2+1)\sqrt{1-x^2}} \,dx&=\frac{2}{\sqrt{2}}\int_{0}^{1}\frac{1}{1-x^2}\operatorname{artanh}\left(\frac{\sqrt{1-x^2}}{\sqrt2}\right)\,dx\\&=\frac{2}{\sqrt{2}}\int_{0}^{1}\frac{1}{u\sqrt{1-u^2}}\operatorname{artanh}\left(\frac{u}{\sqrt2}\right) \,du\\&=\frac{\pi^2}{4\sqrt2}\end{align*}
Thus upon summing the two we have
$$\color{red}{\implies J =\frac{\pi^2}{8\sqrt2}-\frac{1}{\sqrt2}\left(-\frac{\pi^2}{48}+\frac{\ln^2(2)}{8}+\operatorname{Li}_2\left(\frac{1}{\sqrt2}\right)\right)}$$
Now we evaluate $\color{blue}{K}$:
$$K := \int_{0}^{1} \frac{x \ln (x)}{(1+x^2)\sqrt{1-x^2}} \, dx$$
\begin{align*}\int_{0}^{1}\frac{x \ln(x)}{\sqrt{1-x^2}(1+x^2)}\,dx &=\frac{1}{\sqrt{2}}\int_{0}^{1}\frac{1}{x}\left(\operatorname{artanh}\left(\frac{\sqrt{1-x^2}}{\sqrt2}\right)-\operatorname{artanh}\left(\frac{1}{\sqrt2}\right)\right)\,dx\\&=\frac{1}{\sqrt{2}}\int_{0}^{1}\frac{u}{1-u^2}\left(\operatorname{artanh}\left(\frac{u}{\sqrt2}\right)-\operatorname{artanh}\left(\frac{1}{\sqrt2}\right)\right)\,du\end{align*}
We shall now approach this with differentiation under the integral sign.
Define
$$f(b):=\frac{1}{\sqrt{2}}\int_{0}^{1}\frac{u}{1-u^2}\left(\operatorname{artanh}\left(\frac{u}{b}\right)-\text{arctanh}\left(\frac{1}{b}\right)\right)\,du$$
$$f'(b)=\frac{1}{2 \sqrt{2}}\left(\frac{b(\ln(b+1)-\ln(b-1))-2\ln(2)}{b^2-1}\right)$$
Notice that $\lim_{b \to \infty} f(b) = 0 \implies f(\sqrt{2})-f(\infty)=K$
$$\color{blue}{\implies K=-\frac{1}{4\sqrt{2}}\left(\frac{\pi^2}{3}+2\operatorname{Li}_2\left(\frac{1}{2}-\frac{1}{\sqrt{2}}\right)+\ln^2(2)-\operatorname{arsinh}(1)^2-2\ln(2)\operatorname{arsinh}(1)\right)}$$
Now we evaluate $\color{purple}{L}$:
$$L := \int_{0}^{1}\frac{\operatorname{Li}_2(-x)-\operatorname{Li}_2(1-x)+\ln(x)\ln(1+x)}{(x^2+1)\sqrt{1-x^2}} \,dx \\= -\frac{\pi^3}{24\sqrt2}+\frac{2}{\sqrt{2}}\int_{0}^{1}\frac{x\ln(x)}{1-x^2}\arctan \left(\frac{\sqrt{2}x}{\sqrt{1-x^2}}\right) \,dx$$
$$=-\frac{\pi^3}{24 \sqrt{2}}+\frac{2}{\sqrt{2}}\int_{0}^{\infty}\frac{u}{1+u^2}\ln\left(\frac{u}{\sqrt{u^2+1}}\right)\arctan\left(\sqrt{2}u\right)\,du$$
$$=-\frac{\pi^3}{12\sqrt{2}} + \frac{2}{\sqrt{2}}\int_{0}^{\infty}\frac{u}{1+u^2}\ln\left(\frac{u}{\sqrt{u^2+1}}\right)\left(\arctan (\sqrt{2}u)-\frac{\pi}{2}\right)\,du$$
Now separate the logarithm and consider the two integrals
$$\color{green}{A:=\int_{0}^{\infty}\frac{u}{1+u^2}\ln\left(u^2+1\right)\left(\arctan (\sqrt{2}u)-\frac{\pi}{2}\right) \, du}$$
$$\color{brown}{B:=\int_{0}^{\infty}\frac{u}{1+u^2}\ln\left(u\right)\left(\arctan (\sqrt{2}u)-\frac{\pi}{2}\right) \, du}$$
such that $\color{purple}{L} = -\frac{\pi^3}{12 \sqrt{2}} + \frac{2}{\sqrt{2}}\color{brown}{B}-\frac{1}{\sqrt{2}} \color{green}{A}$.
We begin by evaluating $\color{green}{A}$ via differentiation under the integral sign:
$$A=\int_{0}^{\infty}\frac{u}{1+u^2}\ln\left(u^2+1\right)\left(\arctan (\sqrt{2}u)-\frac{\pi}{2}\right) \, du$$
Recall
$$\ln(u^2+1)=2\int_{0}^{\infty}\frac{1-\cos(ux)}{x}e^{-x}\,dx$$
Define
$$g(b) := \int_{0}^{\infty}\frac{u}{1+u^2}\ln\left(u^2+1\right)\left(\arctan\left(\frac{u}{b}\right)-\frac{\pi}{2}\right)\,du$$
$$g'(b) = -2\int_{0}^{\infty}\frac{u^2}{(1+u^2)(b^2+u^2)}\int_{0}^{\infty}\frac{1-\cos(ux)}{x}e^{-x}\,dx\,du$$
$$=-\frac{\pi}{(1-b^2)}\int_{0}^{\infty}\frac{e^{-x}}{x}\left(1-e^{-x}-b+be^{-xb}\right)\,dx =\frac{\pi b\ln(1+b)-\pi\ln(2)}{1-b^2}$$
Notice $\lim_{b \to 0} g(b) = 0 \implies g \left(\frac{1}{\sqrt{2}}\right) - g(0) = A$
$$\color{green}{\implies A = -\frac{\pi^3}{24}-\pi \, \operatorname{arcoth}(\sqrt{2}) \,\ln(2)-\frac{\pi}{2}\operatorname{artanh}\left(\frac{1}{7}+\frac{2\sqrt2}{7}\right)\ln\left(\frac{2+\sqrt2}{16}\right)+\frac{\pi}{2}\operatorname{Li}_2\left(\frac{2-\sqrt2}{4}\right)}$$
Similarly, we evaluate $\color{brown}{B}$ via differentiation under the integral sign:
$$B=\int_{0}^{\infty}\frac{u}{1+u^2}\ln\left(u\right)\left(\arctan (\sqrt{2}u)-\frac{\pi}{2}\right) \, du$$
Define
$$h(b) := \int_{0}^{\infty}\frac{u}{1+u^2}\ln\left(u\right)\left(\arctan\left(\frac{u}{b}\right)-\frac{\pi}{2}\right) \, du$$
$$h'(b) = -\int_{0}^{\infty}\frac{u^2\ln(u)}{(u^2+1)(b^2+u^2)} \, du = \frac{\pi \, b \ln(b)}{2(1-b^2)}$$
Notice $\lim_{b \to 0} h(b) = 0 \implies h \left(\frac{1}{\sqrt{2}}\right) - h(0) = B$
$$\color{brown}{\implies B = -\frac{\pi^3}{96}-\frac{\pi \ln^2(2)}{16}}$$
Thus we have
$$\color{purple}{L} = -\frac{\pi^3}{12 \sqrt{2}} + \frac{2}{\sqrt{2}} \color{brown}{\left(-\frac{\pi^3}{96}-\frac{\pi \ln^2(2)}{16}\right)} - \frac{1}{\sqrt{2}} \color{green}{\left(
-\frac{\pi^3}{24}-\pi \, \operatorname{arcoth}(\sqrt{2}) \,\ln(2)-\frac{\pi}{2}\operatorname{artanh}\left(\frac{1}{7}+\frac{2\sqrt2}{7}\right)\ln\left(\frac{2+\sqrt2}{16}\right)+\frac{\pi}{2}\operatorname{Li}_2\left(\frac{2-\sqrt2}{4}\right) \right)}$$
$$\color{purple}{\implies L = -\frac{\pi\operatorname{Li}_2\left(\frac{1}{2}-\frac{1}{2\sqrt{2}}\right)}{2\sqrt{2}}-\frac{\pi^3}{16\sqrt{2}}-\frac{\pi\ln^2(2)}{8\sqrt{2}}-\frac{\pi\ln\left(16-8\sqrt{2}\right)\, \operatorname{artanh}\left(\frac{1}{7}+\frac{2\sqrt{2}}{7}\right)}{2\sqrt{2}}+\frac{\pi\ln(2)\,\operatorname{arcoth}\left(\sqrt{2}\right)}{\sqrt{2}}}$$
$$\color{purple}{\implies L = -\frac{\pi\operatorname{Li}_2\left(\frac{1}{2}-\frac{1}{2\sqrt{2}}\right)}{2\sqrt{2}}-\frac{\pi^3}{16\sqrt{2}}-\frac{7\pi\ln^2(2)}{8\sqrt{2}}+\frac{\pi\ln^2\left(2-\sqrt{2}\right)}{4\sqrt{2}}+\frac{\pi\ln(2)\ln\left(2+\sqrt{2}\right)}{2\sqrt{2}}}$$
Thus finally, we have
$$I = \pi \color{red}{\left(\frac{\pi^2}{8\sqrt2}-\frac{1}{\sqrt2}\left(-\frac{\pi^2}{48}+\frac{\ln^2(2)}{8}+\operatorname{Li}_2\left(\frac{1}{\sqrt2}\right)\right)\right)} - \pi \color{blue}{\left( -\frac{1}{4\sqrt{2}}\left(\frac{\pi^2}{3}+2\operatorname{Li}_2\left(\frac{1}{2}-\frac{1}{\sqrt{2}}\right)+\ln^2(2)-\operatorname{arsinh}(1)^2-2\ln(2)\operatorname{arsinh}(1)\right) \right)} + \color{purple}{\left( -\frac{\pi\operatorname{Li}_2\left(\frac{1}{2}-\frac{1}{2\sqrt{2}}\right)}{2\sqrt{2}}-\frac{\pi^3}{16\sqrt{2}}-\frac{7\pi\ln^2(2)}{8\sqrt{2}}+\frac{\pi\ln^2\left(2-\sqrt{2}\right)}{4\sqrt{2}}+\frac{\pi\ln(2)\ln\left(2+\sqrt{2}\right)}{2\sqrt{2}} \right) }$$
After some simplification
$$\implies I = -\frac{\pi\operatorname{Li}_2\left(\frac{1}{\sqrt{2}}\right)}{\sqrt{2}}+\frac{\pi\operatorname{Li}_2\left(\frac{1}{2}-\frac{1}{\sqrt{2}}\right)}{2\sqrt{2}}-\frac{\pi\operatorname{Li}_2\left(\frac{1}{2}-\frac{1}{2\sqrt{2}}\right)}{2\sqrt{2}}+\frac{\pi^3}{6\sqrt{2}}-\frac{\pi\ln^2(2)}{2\sqrt{2}}+\frac{\pi\ln^2\left(2-\sqrt{2}\right)}{4\sqrt{2}}-\frac{\pi\ln^2\left(1+\sqrt{2}\right)}{4\sqrt{2}}$$

We now finally prove the following equality:
$$2\operatorname{Li}_2 \left(\frac{\sqrt{2}}{2}\right)-\operatorname{Li}_2 \left(\frac{1-\sqrt{2}}{2}\right)+\operatorname{Li}_2 \left(-\frac{\sqrt{2}}{2} \left(\frac{1-\sqrt{2}}{2}\right)\right)\\=\frac{7\pi^2}{24} - \ln^2 (2) + \frac{1}{2} \ln^2 (2-\sqrt{2})-\frac{1}{2} \ln^2 (1+\sqrt{2})$$

By setting $z=-\frac{\sqrt{2}}{2}$ and $w = \frac{1-\sqrt{2}}{2}$ into this identity referenced to CJ.Hill, 1830 we determine that $$\operatorname{Li}_2 \left(-\frac{\sqrt{2}}{2} \left(\frac{1-\sqrt{2}}{2}\right)\right)=\operatorname{Li}_2 \left(-\frac{\sqrt{2}}{2}\right)+\operatorname{Li}_2 \left(\frac{1-\sqrt{2}}{2}\right)+\operatorname{Li}_2 \left(\frac{2-\sqrt{2}}{2}\right)+\operatorname{Li}_2 \left(\frac{1}{2}\right)+\frac{1}{8} \ln^2 (2)$$
Substituting this into the LHS of the equality we wish to prove, and using the well-known value $\operatorname{Li}_2 \left(\frac{1}{2}\right)=\frac{\pi^2}{12}-\frac{1}{2}\ln^2 (2)$, the LHS becomes
$$2\operatorname{Li}_2 \left(\frac{\sqrt{2}}{2}\right)+\operatorname{Li}_2 \left(-\frac{\sqrt{2}}{2}\right)+\operatorname{Li}_2 \left(\frac{2-\sqrt{2}}{2}\right)+\frac{\pi^2}{12}-\frac{3}{8}\ln^2 (2)$$
which further simplifies, by setting $z=\frac{\sqrt{2}}{2}$ into equation (3), to become
$$\operatorname{Li}_2 \left(\frac{\sqrt{2}}{2}\right)+\operatorname{Li}_2 \left(\frac{2-\sqrt{2}}{2}\right)+\frac{\pi^2}{8}-\frac{5}{8}\ln^2 (2)$$
which simplifies, by setting $z=\frac{\sqrt{2}}{2}$ into equation (5), to become $$\frac{7\pi^2}{24}-\frac{5}{8}\ln^2 (2) + \frac{1}{2} \ln (2) \ln\left(\frac{2-\sqrt{2}}{2}\right)=\frac{7\pi^2}{24}-\frac{9}{8}\ln^2 (2) + \frac{1}{2} \ln (2) \ln\left(2-\sqrt{2}\right)$$
Now if we consider the RHS of the equality we are trying to prove, we can factor
\begin{align*}\frac{1}{2}\ln^2 (2-\sqrt{2})-\frac{1}{2}\ln^2 (1+\sqrt{2}) &= \frac{1}{2}\left(\ln(2-\sqrt{2})+\ln(1+\sqrt{2})\right)\left(\ln(2-\sqrt{2})-\ln(1+\sqrt{2})\right)\\&=\frac{1}{4}\ln (2)\ln(3\sqrt{2}-4)\end{align*}
Since $3\sqrt{2}-4 = \frac{1}{\sqrt{2}} \left(2-\sqrt{2}\right)^2$, the given equality is true. $\square$
Thus upon multiplying the dilogarithm equality, we have proven by $\frac{\pi}{2\sqrt{2}}$ and rearranging, we have
$$I = \frac{\pi^3}{48 \sqrt{2}}$$
$\square$


text:
Q: function wont work after executing ajax load I have a list of users in my table. At first run it will load using the data from my controller. And I have a remove button function in every row. And then in my remove button I have an ajax load AFTER the successful removal of the user. Now I load the data using ajax. But the problem is the same functionality I have at first wont work anymore. I don't know why.
Here's my code:
Initial load of user from my controller

            Group Name
            Description

                <a href="<?php echo $add_group; ?>" class="btn ink-reaction btn-raised btn-primary btn-sm">
                <button class="btn ink-reaction btn-raised btn-danger btn-sm"></button>

        <?php if($user_groups) { ?>
            <?php foreach($user_groups as $g) { ?>

                        <input type="checkbox" name="group_id[]" value="<?php echo $g['id']; ?>" />

                        <?php echo $g['name']; ?>

                        <?php echo $g['definition']; ?>

                        <a class="btn btn-icon-toggle btn-primary edit_group" data-id="<?php echo $g['id']; ?>">
                        <?php if($g['id'] > 2) { ?>
                        <a class="btn btn-icon-toggle btn-danger remove_group" data-id="<?php echo $g['id']; ?>" data-name="<?php echo $g['name']; ?>">
                        <?php } ?>

            <?php } ?>
        <?php } else { ?>

There are no user group set

        <?php } ?>

Then in my JS
$('.remove_group').on('click', function(e) {
    e.preventDefault();
    var group_id = $(this).data('id');
    var name = $(this).data('name');

    alert(group_id); //wont work anymore after ajax load

    bootbox.dialog({
        message: "Are you sure you want to remove the group " + name.toUpperCase() + "",
        title: "Notification",
        buttons: {
            success: {
                label: "Yes, remove it",
                className: "btn-info",
                callback: function() {
                    $.ajax({
                        url: "<?php echo site_url('users/user/remove_user_group'); ?>",
                        data: {group_id: group_id},
                        dataType: 'json',
                        type: 'post',
                        beforeSend: function() {
                            console.log('Loading...');
                        },
                        success: function(d) {
                            loadUserGroup();
                            makeToast(d.status, d.toast_info);
                        },
                        error: function() {
                            alert('Error Found!');
                        }
                    });
                }
            },
            danger: {
                label: "Cancel",
                className: "btn-default",
                callback: function() {
                    $(this).modal('hide');
                }
            }
        }
    });
});

function loadUserGroup() {
    $.ajax({
        url: "<?php echo site_url('users/user/load_group_list'); ?>",
        dataType: 'json',
        beforeSend: function() {

            var loader =  "
";
                loader += " 	";
                loader += "
";

            $('#user-group-list tbody').empty();
            $('#user-group-list tbody').html(loader);
        },
        success: function(data) {
            $('#user-group-list tbody').empty();
            var group_list = '';
            $.each(data.user_groups, function(k, v){
                group_list += "
";
                group_list += " <input type='checkbox' />	";
                group_list += " " + v.name + "	";
                group_list += " " + v.definition + "	";
                group_list += " ";
                group_list += "     ";
                if(v.id > 2) {
                    group_list += "     ";
                }
                group_list += " 	";
                group_list += "
";
                //console.log(v.id);
            });

            $('#user-group-list tbody').html(group_list);

        },
        error: function() {
            alert('Error Occured!');
        }
    });
}

My ajax load
public function load_group_list() {

        $json['user_groups'] = array();
        $groups = $this->aauth->get_all_groups();

        if(count($groups) > 0) {
            foreach($groups as $group) {

                $json['user_groups'][] = array(
                    'id'    =>  $group['id'],
                    'name'  =>  $group['name'],
                    'definition'    =>  $group['definition'],
                    'href'  =>  site_url('users/user/user_group_info?group_id=' . $group['id'])
                );

            }
        }

         header('Access-Control-Allow-Origin: *');
        header("Content-Type: application/json");
        echo json_encode($json);

    }

A: Hope the below function fails
$('.remove_group').on('click', function(e) {//your code}

Change that to the below code
$(document).on('click','.remove_group', function(e) {//your code}

It occur because you load the class dynamically and DOM can't identify the element any more


text:
Q: Building OpenSSL 1.0.2 on iOS - make depend fails I am trying to build OpenSSL 1.0.2 for iOS, but I am getting an error with make depend. Here is the terminal output:
$ ./Configure iphoneos-cross no-shared no-dso no-hw no-engine --prefix=/usr/local/openssl-ios

...

Since you've disabled or enabled at least one algorithm, you need to do
the following before building:

    make depend

Configured for iphoneos-cross.
$ make depend
making depend in crypto...
makedepend: error:  failed to read /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk
mv: Makefile.new: No such file or directory
make[1]: *** [depend] Error 1

The directory it is complaining about exists and has read right for everyone, so I am at a loss on what to do. I tried to sudo it (against my better judgement) but that only resulted in a toooonnn more "No such this or that" errors.
Is there a step I am missing?

A: I was trying to configure here, and gave a very similar error. What solved for me:

*

*Download Xcode version 11.7 and 12.5;

*Keep in Xcode>preferences>locations>command line tools version 12.5;

*Rename the file from Xcode version 12.5 to only Xcode and 11.7 to Xcode_old

*Run again!

I hope it works for you too!


text:
Q: Django handle transaction on filter query I have a Model that has a "score" attribute and a route that returns the object with the biggest score from the database (MySQL).
I want to use multiple instances of the same application (two microservices) and I am afraid that I will face race conditions, both machines returning the same client. How could I make sure that this is not happening?
After returning a client, it will be marked as PROCESSED.
def getClient(request):
    client = Client.objects.order_by('-score').filter(state="UNPROCESSED").first()
    client.state = "PROCESSED"
    client.save()
    return HttpResponse(f"<h1>{client.name}</h1>")

A: In the official document, the transaction processing is well described.
https://docs.djangoproject.com/en/4.0/topics/db/transactions/


text:
Q: How can I get an element's innerHTML to update immediately? I have a web page with a text box. When entering in a .js file name into the box and clicking the Execute button, the file given will be loading via AJAX and eval()'d.
Also on this page is an empty <div> for used as output. If the file that is loaded needs to print something to the screen, it adds it to the div's innerHTML.
When adding text to the innerHTML, it usually doesn't render on the screen until the Javascript is completed, which is fine, except for the fact that, sometimes, the Javascript file performs heavy calculations which can take upwards to a minute to complete, and it would be useful to be able to see the output as it was executing.
Is there any way to "refresh" the document?

A: I would try solving this using setTimeout.
function performInitialHtmlRender() {
    /// This sets the innerHtml that you want the user to see
    /// While you are performing the calculations
}

function performExpensiveCalculationsAndRender() {
    // This is the really expensive function that
    // you want to run once the browser has rendered
    // the initial HTML
}

performInitialHtmlRender();
setTimeout(performExpensiveCalculationsAndRender(), 0);

A: You can use setTimeout:
div.innerHTML = html;
setTimeout( function(){
   doHeavyCalculations();
}, 35);

http://jsfiddle.net/YKEKK/


text:
Q: How to stop contentEditable="true" inserting  instead of  when pressing return? I have a div

 My headline

If i am editing the text inside the
 tag, and press return, it adds a new div under, instead of the normal paragraph tag it usually inserts when entering return
Making it:

 My headline edited

 i tapped return

What i really want is

 My headline edited

 i tapped return

 return again

Whats strange is that usually when you write somewhere and press return it adds a new
, but just not when editing
. Is it possible to fix this with Javascript/Jquery/Html5?
I am using Safari on an iOS-device

A: Adding a format blocker inside onkeyup with p will force the contenteditable (div) to add
 tag on return.
editable.onkeyup = (e)=> {
    e = e || window.event
    if (e.keyCode === 13)
        document.execCommand('formatBlock', false, 'p');
}


text:
Q: SciPy error: RuntimeWarning: overflow encountered in _beta_ppf My SciPy version is 1.7.3 and I'm running on an Apple M1 chip (not sure if it's relevant). My Python version is 3.9.11, installed via Annaconda.
I get the error message /opt/anaconda3/lib/python3.9/site-packages/scipy/stats/_continuous_distns.py:624: RuntimeWarning: overflow encountered in _beta_ppf return _boost._beta_ppf(q, a, b) when running the following PyMC3 code:
import pymc3 as pm
from scipy import stats

Y = stats.bernoulli(0.7).rvs(20)

with pm.Model() as model:
    theta = pm.Beta("theta", alpha=0.1, beta=0.1)
    y_obs = pm.Binomial("y_obs", n=2, p=theta, observed=Y)
    idata = pm.sample(1000, return_inferencedata=True)

I don't think the issue is with PyMC3, because the PyMC3 code someone else wrote runs without any errors:
np.random.seed(123)
n_experiments=4
theta_real =0.35
data =stats.bernoulli.rvs(p=theta_real,size=n_experiments)
with pm.Model()  as our_first_model:
    theta =pm.Beta('theta',alpha=1,beta=1)
    y =pm.Bernoulli('y',p=theta,observed=data)
    start =pm.find_MAP()
    step =pm.Metropolis()
    trace =pm.sample(1000,step=step,start=start)
    burnin=100
    chain =trace[burnin:]
    pm.traceplot(chain,lines={'theta':theta_real})

The SciPy code snippet below, however, gives the same error:
import numpy as np
from scipy import stats
q = 0.999995
a = np.array([ 2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
b = np.array([99999, 99998, 99997, 99996, 99995, 99994, 99993, 99992, 99991, 99990, 99989, 99988, 99987, 99986, 99985, 99984, 99983, 99982, 99981])
stats.beta.ppf(q, a, b)

I Googled "overflow encountered in _beta_ppf" and found a GitHub issue (https://github.com/scipy/scipy/issues/14901) that points to problems with SciPy <=1.7.2 on Intel chips. However, I'm using 1.7.3 on an M1 chip.
Anaconda doesn't allow me to update to the newest SciPy version (1.8.0). Using pip to update (pip install scipy==1.8.0 ) results in incompatibilities with ArviZ (arviz 0.11.2 requires typing-extensions<4,>=3.7.4.3, but you have typing-extensions 4.1.1 which is incompatible). I guess I could downgrade typing-extensions, but it may cause further issues with other packages, so I'd rather not.
I wonder what I can do to solve this problem. Thanks!

A: If you cannot upgrade scipy to 1.8.0, you can always downgrade it to 1.6.x (IIRC boost is not used in 1.6.x series)

A: Native Conda Environment
FWIW, I use native Mambaforge for osx-arm64, and have no problem with creating a native Python v3.10 with SciPy v1.8.0. If you already have an Anaconda/Miniconda base (i.e., osx-64), you should be able to create a native environment with:
Shell Session
conda create -n arm64
conda activate arm64
conda config --env --add channel conda-forge
conda config --env --set subdir osx-arm64
conda install -y scipy=1.8 pymc3
python

Python Session
Python 3.10.4 | packaged by conda-forge | (main, Mar 24 2022, 17:39:37) [Clang 12.0.1 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> from scipy import stats
>>> q = 0.999995
>>> a = np.array([ 2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
>>> b = np.array([99999, 99998, 99997, 99996, 99995, 99994, 99993, 99992, 99991, 99990, 99989, 99988, 99987, 99986, 99985, 99984, 99983, 99982, 99981])
>>> stats.beta.ppf(q, a, b)
array([0.00014976, 0.00017332, 0.00019478, 0.00021492, 0.0002341 ,
       0.00025256, 0.00027046, 0.00028788, 0.00030491, 0.00032161,
       0.00033802, 0.00035417, 0.00037009, 0.0003858 , 0.00040134,
       0.0004167 , 0.00043192, 0.00044699, 0.00046193])

Just make sure to activate the environment before installing additional packages.

Also, seems to not have any error with scipy=1.7.3 either.


text:
Q: Socket.io when client Internet going to off How can i callback from client to server internet going to off? I have users and i added their connections in the some room. But I can not know when they are Internet going to down. I want to callback their statues but I do not know how. My clients are android phone.
this function does not work.
socket.on("disconnect", function () {
    var SocketRoom= socket.room;
    socket.leave(SocketRoom);
});

A: The clients can't send a message through the socket connection, if they are not connected to the network/internet anymore. You might want to check for timeouts.
Once a client connects to the server, the server sends a message to the client in a fixed time interval (like every 5 seconds).
If the client responds to that message, you know, it's still conencted and continue with your program logic.
If the client does not respond to your message, then they are very likely not connected to the internet anymore (or are unreachable for other reasons). If this is the case, you can force them to leave the room (like in your socket.on("disconnect", ...) function).
Please note:

*

*The higher the timeout interval, the less precise is the actual disconnect time, but the load on the connection is kept low.

*If a client does not respond to a timeout-check, you might want to retry to send a message to that client a couple of times before force-closing the connection.


text:
Q: Inheritance from multiple inheritance Have a problem with multiple inheritance. I have solved diamond problem:
class A
{
    int m;
    int n;
public:
    A(int x, int y)
    {
        m = x; n = y
    }
    fA() {}
};

class B : virtual public A // B has fA(),fB()
{
public:
    B(int k) : A(1, k) {}
    fB() {}
};

class C : virtual public A // C has fA(),fC()
{
public:
    C(int k) : C(2, k) {}
    fC() {}
};

class D : public B, public C // D has fA(),fB(),fC()
{
public:
    D(int k) : B(k),C(k),A(3,k)
};

This is working well. Problem with this:
class S : public B // S has fA(),fB()
{
public:
    S() : B(6) {}
};

Compilator shows me: "error: no matching function for call to `A::A()'"
This code is working, but it doesn't satisfied me:
class S : public B // S has fA(),fB()
{
public:
    S() : B(6),A(1,6) {}
};

A: In virtual inheritance, the constructor of virtual base is called from the constructor of most derived class:
class S : public B // S has fA(),fB()
{
public:
    S() :   B(6) {}
};  //    ^  A base class is initialized at this point, before B

This also means that other explicit calls to A's constructor in initialization-lists further down the inheritance chain are ignored:
class B : virtual public A // B has fA(),fB()
{
public:
    B(int k) : A(1, k) {}
    fB() {} // ^^^^^^^    this call is ignored when B is a part of S object
};

If there's no explicit call to virtual base's constructor in initialization list of most derived class, the compiler will (of course) try to call the default constructor. But A doesn't have one and that's your problem.
One solution you already discovered yourself. The other is to write default constructor for A.


text:
Q: Adding and Removing User Controls at Runtime, On selection the previous control should get overwritten I have a placeholder control and a dropdown on an .aspx page which selects user controls and adds it to the placeholder :
 if (dropdown.SelectedValue == "1")
        {
            UserControl UC = (UserControl)LoadControl("usercontrolpath");
            placeholder.Controls.Add(UC);

        }

I perform all my operations on this user controls (by recreating it on every postback), now I want that when the user selects some other option from the dropdown say:
 if (dropdown.SelectedValue == "2")
        {
            UserControl UC = (UserControl)LoadControl("Newusercontrolpath");
            placeholder.Controls.Add(UC);

        }

then the first user control should be overwritten by this new user control (Older one should dissapear from the page). If I do
placeholder.Controls.remove(UC);

at the selected index change of the dropdown and then add the new user control then I am getting an index out of bound error when the new control is added to the placeholder.
How can I go about achieving this?
Please let me know if some more info is needed.

A: You can use Controls.Clear() first:
placeholder.Controls.Clear();
placeholder.Controls.Add(UC);

You cannot use Remove(UC) since that's trying to remove the new usercontrol that is yet not added.


text:
Q: No matching distribution found for torch==1.5.0 this error occurred
ERROR: Could not find a version that satisfies the requirement torch==1.5.0 (from versions: 1.7.0, 1.7.1, 1.8.0, 1.8.1, 1.9.0, 1.9.1, 1.10.0, 1.10.1, 1.10.2)
ERROR: No matching distribution found for torch==1.5.0

then I tried to solve it by the command
pip install torch==1.7.0 -f https://download.pytorch.org/whl/torch_stable.html

and then I tried to execute the command again ..
pip install -r C:\Bachelor\urban-sound-tagging-master\requirements.txt

the same error occurred
ERROR: Could not find a version that satisfies the requirement torch==1.5.0 (from versions: 1.7.0, 1.7.1, 1.8.0, 1.8.1, 1.9.0, 1.9.1, 1.10.0, 1.10.1, 1.10.2)
ERROR: No matching distribution found for torch==1.5.0

what can I do ?

A: You can install PyTorch previous versions from this link PyTorch previous versions
Example:
CUDA 9.2
conda install pytorch==1.5.0 torchvision==0.6.0 cudatoolkit=9.2 -c pytorch

CUDA 10.1
conda install pytorch==1.5.0 torchvision==0.6.0 cudatoolkit=10.1 -c pytorch

CUDA 10.2
conda install pytorch==1.5.0 torchvision==0.6.0 cudatoolkit=10.2 -c pytorch

CPU Only
conda install pytorch==1.5.0 torchvision==0.6.0 cpuonly -c pytorch


text:
Q: Libraries / tutorials for manipulating video in java I need to do some simple video editing within a Java application, but the frameworks I've found (JMF and FMJ) appear to be quite stale, and thus far I haven't found any evidence that either can actually edit video.  The type of operations I need are: cropping, redacting sections, and extracting clips.
I've never worked with video in any real capacity before, so I may just be misunderstanding what FMJ/JMF do, but I am still concerned by the age of the most recent releases of those tools.
What do people use to do this sort of thing? What keywords should I be using to get more relevant results?
(The specific format of video is not particularly important to me -- anything common is just fine.)

A: GStreamer has some Java bindings.

A: You may take a look on Xuggler. Also some alternatives to JMF were covered in Wikipedia.


text:
Q: Setting CollectionView cell height to dynamic based on content I have an application where I am using collectionview to display content which includes imageview, about 4 uilabels and a stackview which are all constrained to each other. This cell is scrollable vertically and not horizontally as I have to make provison for larger screen size like the iPad. The problem I have now is my CollectionViewFlowLayout height is static, How can I make it dynamic so that it resizes base on the height of the retuned content. the text of the label could vary so how do I handle this
below is how I have made my cell
func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize {

        return CGSize(width: collectionView.bounds.size.width, height: 400)
    }

further code would be added on request and any help is appritiated


text:
Q: How to remove newlines from beginning and end of a string? I have a string that contains some text followed by a blank line. What's the best way to keep the part with text, but remove the whitespace newline from the end?

A: If your string is potentially null, consider using StringUtils.trim() - the null-safe version of String.trim().

A: Use String.trim() method to get rid of whitespaces (spaces, new lines etc.) from the beginning and end of the string.
String trimmedString = myString.trim();

A: If you only want to remove line breaks (not spaces, tabs) at the beginning and end of a String (not inbetween), then you can use this approach:
Use a regular expressions to remove carriage returns (\\r) and line feeds (\\n) from the beginning (^) and ending ($) of a string:
 s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "")

Complete Example:
public class RemoveLineBreaks {
    public static void main(String[] args) {
        var s = "\nHello world\nHello everyone\n";
        System.out.println("before: >"+s+"<");
        s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "");
        System.out.println("after: >"+s+"<");
    }
}

It outputs:
before: >
Hello world
Hello everyone
<
after: >Hello world
Hello everyone<

A: String.replaceAll("[\n\r]", "");

A: This Java code does exactly what is asked in the title of the question, that is "remove newlines from beginning and end of a string-java":
String.replaceAll("^[\n\r]", "").replaceAll("[\n\r]$", "")

Remove newlines only from the end of the line:
String.replaceAll("[\n\r]$", "")

Remove newlines only from the beginning of the line:
String.replaceAll("^[\n\r]", "")

A: I'm going to add an answer to this as well because, while I had the same question, the provided answer did not suffice. Given some thought, I realized that this can be done very easily with a regular expression.
To remove newlines from the beginning:
// Trim left
String[] a = "\n\nfrom the beginning\n\n".split("^\\n+", 2);

System.out.println("-" + (a.length > 1 ? a[1] : a[0]) + "-");

and end of a string:
// Trim right
String z = "\n\nfrom the end\n\n";

System.out.println("-" + z.split("\\n+$", 2)[0] + "-");

I'm certain that this is not the most performance efficient way of trimming a string. But it does appear to be the cleanest and simplest way to inline such an operation.
Note that the same method can be done to trim any variation and combination of characters from either end as it's a simple regex.

A: Try this
function replaceNewLine(str) {
  return str.replace(/[\n\r]/g, "");
}

A: tl;dr
String cleanString = dirtyString.strip() ; // Call new `String::string` method.

String::strip…
The old String::trim method has a strange definition of whitespace.
As discussed here, Java 11 adds new strip… methods to the String class. These use a more Unicode-savvy definition of whitespace. See the rules of this definition in the class JavaDoc for Character::isWhitespace.
Example code.
String input = " some Thing ";
System.out.println("before->>"+input+"<<-");
input = input.strip();
System.out.println("after->>"+input+"<<-");

Or you can strip just the leading or just the trailing whitespace.
You do not mention exactly what code point(s) make up your newlines. I imagine your newline is likely included in this list of code points targeted by strip:

*

*It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space ('\u00A0', '\u2007', '\u202F').

*It is '\t', U+0009 HORIZONTAL TABULATION.

*It is '\n', U+000A LINE FEED.

*It is '\u000B', U+000B VERTICAL TABULATION.

*It is '\f', U+000C FORM FEED.

*It is '\r', U+000D CARRIAGE RETURN.

*It is '\u001C', U+001C FILE SEPARATOR.

*It is '\u001D', U+001D GROUP SEPARATOR.

*It is '\u001E', U+001E RECORD SEPARATOR.

*It is '\u001F', U+0

A: String trimStartEnd = "\n TestString1 linebreak1\nlinebreak2\nlinebreak3\n TestString2 \n";
System.out.println("Original String : [" + trimStartEnd + "]");
System.out.println("-----------------------------");
System.out.println("Result String : [" + trimStartEnd.replaceAll("^(\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029])|(\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029])$", "") + "]");

*

*Start of a string = ^ ,

*End of a string = $ ,

*regex combination = | ,

*Linebreak = \r\n|[\n\x0B\x0C\r\u0085\u2028\u2029]

A: Another elegant solution.
String myString = "\nLogbasex\n";
myString = org.apache.commons.lang3.StringUtils.strip(myString, "\n");

A: For anyone else looking for answer to the question when dealing with different linebreaks:
string.replaceAll("(\n|\r|\r\n)$", ""); // Java 7
string.replaceAll("\\R$", "");          // Java 8

This should remove exactly the last line break and preserve all other whitespace from string and work with Unix (\n), Windows (\r\n) and old Mac (\r) line breaks: https://stackoverflow.com/a/20056634, https://stackoverflow.com/a/49791415. "\\R" is matcher introduced in Java 8 in Pattern class: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html
This passes these tests:
// Windows:
value = "\r\n test \r\n value \r\n";
assertEquals("\r\n test \r\n value ", value.replaceAll("\\R$", ""));

// Unix:
value = "\n test \n value \n";
assertEquals("\n test \n value ", value.replaceAll("\\R$", ""));

// Old Mac:
value = "\r test \r value \r";
assertEquals("\r test \r value ", value.replaceAll("\\R$", ""));

A: String text = readFileAsString("textfile.txt");
text = text.replace("\n", "").replace("\r", "");


text:
Q: Android application behaves differently when download from Play Store I have built an application that returns data when entering a Dutch license plate. The data it returns is taken from the API from the RDW who stores all this data. Now my problem is: When I push the application from my Android Studio via ADB it works perfectly. But when I publish the SAME application to the Play Store and download/install it from there it only works the first time when entering a license plate. The second time it does just spin the progress bar and returns to the home screen after around 10 seconds.
How is this possible?

A: You should test your Signed APK before uploading to the store. Then You can debug that signed apk in android studio by printing some log messages on the corresponding activity. Then you can trace the issue as well

A: Just uncheck Instant Run in settings of Android Studio and then build and run that apk. For instant run option, go to File->Settings->Build,Execution,Deployment->Instant Run, then remove check of Enable Instant Run. After that run project again and make and use new apk. .I hope this solution work.


text:
Q: how to inject context to HttpModule I want inject context.heanders to Httpmodule when it register.how?
nestjs 6.0
i create a global Module like below, i want add context.header in this place
@Global()
@Module({
  imports: [
    HttpModule.register({
      timeout: 20000,
     // (how to get context.header in this place )
      // headers: {
      //   'x-sec-profile': '281567',
      //   'accessToken': 'f647e353790fd5c54dbd8c06be4575a58f369476a569c71a',
      // },
    }),
  ],
})
export class AxiosModule {}

this is cats.resolver.ts
@Resolver(Cat)
export class CatsResolver {
  constructor(private readonly catsService: CatsService) {}
  @Query(returns => Cat,  { name: 'cat' })
  async findDetail(@Args('id') id: number, @Context('headers') headers) {
    console.log(arguments.length)
    return await this.catsService.findDetail(id)
  }
}

use cats.service.ts
@Injectable()
export class CatsService {
  constructor(private readonly httpService: HttpService) { }

  async findDetail(id) {
    const a = await this.httpService.get('https://yuangong.com/api/contract-web/contract/contract-detail',
    {params: { contractId: 1000320 } }).toPromise()
    return {
      contractId: a.data.data.id,
    }
  }
}


text:
Q: Updates in libreoffice in main repository
Possible Duplicate:
Why do the Repositories not have the latest upstream versions?
Why don't the Ubuntu repositories have the latest versions of software?

Why does LO in the main repository don't keep up with the latest libreoffice version? 3.5.4 offers for example huge improvements in speed. Unless the packages gets updated in the main repository most users wont see the new build.
I know there is a PPA, but sometimes it breaks things (for example the 3.5.5 rc2 amd64 build is stuck (since yesterday!!) in building because of low storage space https://launchpad.net/~libreoffice/+archive/ppa/+build/3609969 )


text:
Q: Ignoring embeded spaces with AWK I'm looking for a simple way to print a specific field with awk while allowing for embedded spaces in the field.
Sample:   Field1 Field2 "Field Three" Field4
I want to be able to do the equivalent to awk '{print $3}' but getting "Field Three" as a single field not two.
Update: More specifically, I need to get later fields not $3 but the space in #3 is what's messing things up. The number of spaces between the quotes in $3 is variable. I'm just wanting to be able to treat what's between quotes as a single field even if not all fields are quoted. So, ignoring the spaces as field separators if between quotes.

A: You can do this if the double quotes are always there:
awk -F\" '{print $2}'

Specifically, I am telling awk that the fields are separated by double quotes, at which point the part you want is readily available as field 2.
If you need to get at subsequent fields, you can split the remainder of the line on spaces and get a new array, say F[] of fields, like this:
awk -F\" '{split($3,F," ");print $2,F[1],F[2]}' file

Field Three Field4 Field5

assuming your file looks like this:
Field1 Field2 "Field Three" Field4 Field5 Field6

A: Based on this, in gawk maybe you can use something like
awk 'BEGIN{FPAT = "([^ ]+)|(\"[^\"]+\")"}{print $3}' input.txt

Output:
"Field Three"

It may need more work to get suited to your needs completely.
I think it needs gawk 4+, https://lists.gnu.org/archive/html/info-gnu/2011-06/msg00013.html

A: Parsing CSV can be a tricky business. I like to use a language with a proper CSV parsing module. For example with ruby, parsing the given line, using space as the column separator, and default double quotes quoting character:
ruby -rcsv -ne 'row = CSV.parse_line($_, {:col_sep=>" "}); puts row[2]' <<END
Field1 Field2 "Field Three" Field4
END

Field Three

A: Mark Setchell's answer is good, although it will not work if you don't know in advance how many embedded quotes you have (and it doesn't split on spaces anymore).
I hacked this together (obviously it can be improved):
gawk -v FIELD=2 '{ a=$ FIELD; if (substr(a, 0, 1) == "\"") { gsub(/^\"/, "", a); s=a; for (i = FIELD + 1; i <= NF; i++) { a=$ i; nbSub=gsub(/\"$/, "", a); s = s " " a; if (nbSub > 0) { break } } print(s) } }' <<<'allo "hello world" bar'

I would recommend using something else than gawk for this (maybe look into parsing the fields with your shell's IFS variable?).
Addendum: As I said above, this is not really the right tool for the job. For example, you can specify the first field with the -v FIELD=, but it counts fields based on AWK's separator (the embedded spaces are still counted).