text:
Q: TypeError at /liveclass/ __init__() takes 1 positional argument but 2 were given My models.py:
from django.db import models

# Create your models here.

class LiveClass(models.Model):
    standard = models.IntegerField()
    no_of_students_registered = models.IntegerField(default=0)
    class Meta:
        verbose_name_plural = 'Class'

class User_details(models.Model):
    name = models.CharField(max_length=30)
    standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE)
    email = models.EmailField(max_length=30)
    mobile_number = models.IntegerField()
    class Meta:
        verbose_name_plural = 'User_details'

class Mentor(models.Model):
    name = models.CharField(max_length=30)
    standard = models.ManyToManyField(LiveClass)
    details = models.TextField()
    class Meta:
        verbose_name_plural = 'Mentors'

class LiveClass_details(models.Model):
    standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE)
    chapter_name = models.CharField(max_length=30)
    chapter_details = models.TextField()
    mentor_name = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE)
    class_time = models.DateTimeField()
    class Meta:
        verbose_name_plural = 'LiveClass_details'

class LiveClass_registration(models.Model):
    class_details = models.OneToOneField(LiveClass_details, on_delete=models.CASCADE)
    name = models.OneToOneField(User_details, on_delete=models.CASCADE)

    class Meta:
         verbose_name_plural = 'LiveClass_registration'

This is serializer for all my models, please tell a way to reduce the code in it as all of it is a repetition.
My Serializer.py:
from rest_framework import serializers
from . import models

class LiveClass_serializer(serializers.ModelSerializer):
    class Meta:
        model = models.LiveClass
        fields = '__all__'

class User_details_serializer(serializers.ModelSerializer):
    class Meta:
        model = models.User_details
        fields = '__all__'

class LiveClass_details_serializer(serializers.ModelSerializer):
    class Meta:
        model = models.LiveClass_details
        fields = '__all__'

class Mentor_serializer(serializers.ModelSerializer):
    class Meta:
        model = models.Mentor
        fields = '__all__'

class LiveClass_registration_serializer(serializers.ModelSerializer):
    class Meta:
        model = models.LiveClass_registration
        fields = '__all__'

My urls.py:
from django.urls import path, include
from . import views

urlpatterns = [
    path('liveclass/', views.List_live_class),
]

In views.py I am trying to list all the items in Liveclass_details column using class based Api view and using mixins.
My views.py:
from django.shortcuts import render
from rest_framework import mixins
from rest_framework import generics

from . import serializers
from . import models
# Create your views here.

class List_live_class(mixins.ListModelMixin, generics.GenericAPIView):
    queryset = models.LiveClass_details.objects.all()
    serializer_class = serializers.LiveClass_details_serializer
    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

I don't understand the location of error and why it is occurring. I am relying on the documentation of the REST framework.
Error:
TypeError at /liveclass/
__init__() takes 1 positional argument but 2 were given
Request Method: GET
Request URL:    http://localhost:8000/liveclass/
Django Version: 3.2.4
Exception Type: TypeError
Exception Value:
__init__() takes 1 positional argument but 2 were given
Exception Location: /home/dhruv/.local/lib/python3.8/site-packages/django/core/handlers/base.py, line 181, in _get_response
Python Executable:  /usr/bin/python3
Python Version: 3.8.5
Python Path:
['/home/dhruv/Desktop/liveClassApp',
 '/home/dhruv/tutorial_ws/devel/lib/python2.7/dist-packages',
 '/opt/ros/melodic/lib/python2.7/dist-packages',
 '/usr/lib/python38.zip',
 '/usr/lib/python3.8',
 '/usr/lib/python3.8/lib-dynload',
 '/home/dhruv/.local/lib/python3.8/site-packages',
 '/usr/local/lib/python3.8/dist-packages',
 '/usr/lib/python3/dist-packages']
Server time:    Thu, 17 Jun 2021 13:16:29 +0000

A: Your List_live_class is a class based view hence if you pass it like below to path you will get an error:
path('liveclass/', views.List_live_class),

Instead you need to use the as_view method of the class and pass that in place of the view function:
path('liveclass/', views.List_live_class.as_view()),

Note: Class names should ideally be in PascalCase hence you should use ListLiveClass instead of List_live_class. See PEP 8 --
Style Guide for Python
Code


text:
Q: Excel addin (C#) + SharePoint 2003 there is Excel add-in that generates an information sheet. The client has this Excel addin.
There is portal SharePoint 2003.
On the client in Excel addin there is a button to click which add excel document on SharePoint 2003 portal.
How can I do to add the document to the portal?

A: Following link provides you information regarding all Add-in in Excel. It also shows you step by step approach for dealing with this in terms of images.
http://www.add-in-express.com/docs/net-excel-automation-addins.php
Refer Following code:
void Application_WorkbookBeforeSave(Microsoft.Office.Interop.Excel.Workbook Wb, bool SaveAsUI, ref bool Cancel)
    {
        Excel.Worksheet activeWorksheet = ((Excel.Worksheet)Application.ActiveSheet);
        Excel.Range firstRow = activeWorksheet.get_Range("A1");
        firstRow.EntireRow.Insert(Excel.XlInsertShiftDirection.xlShiftDown);
        Excel.Range newFirstRow = activeWorksheet.get_Range("A1");
        newFirstRow.Value2 = "This text was added by using code";
    }

This Code belongs to following link which gives you all walk throughs for Creating Your First Application-Level Add-in for Excel.
http://msdn.microsoft.com/en-us/library/vstudio/cc668205.aspx
Hope its helpful.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to build a form builder object with FormBuilder.new in rails 3.1.4 We need to create a form builder object with FormBuilder.new in controller. Here is what we are doing now:
@f = ActionView::Helpers::FormBuilder.new(:invoice, @invoice, self, {}, proc {} )

There is an error saying:
ActionView::Template::Error (undefined method `fields_for' "invoiceController.."

We believe the @f is not a form builder object and that's why fields_for can not be recognized. The issue seems with the self parameter which is current view in definition. What is the right way to build a form builder object with FormBuilder? Thanks.

A: The reason you're not going to get it to work with those parameters in the controller is that you call 'self' for the 'template' parameter, which is only actually the template ... from within the template. In the controller, self is the controller, not the template.


text:
Q: Bukkit Java error: The method PlayerJoin(OnStartup) is undefined for the type OnStartup So, I recently started learning Java and BukkitAPI. I make a config file, and I make a class for player events, but then I can't register the events in my main class. I get an error "The method PlayerJoin(OnStartup) is undefined for the type OnStartup" and the only fix is to make a method. Here is my code:
OnStartup(main class):
package ml.zonia.plugin;

import java.io.File;
import java.util.logging.Logger;
import org.bukkit.event.Listener;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;

import ml.zonia.plugin.commands.Potion;
import ml.zonia.plugin.event.PlayerJoin;

public class OnStartup extends JavaPlugin implements Listener {

public void onEnable() {
    registerEvents();
    registerConfig();
        PluginDescriptionFile pdfFile = getDescription();
        Logger logger = getLogger();

        getServer().getPluginManager().registerEvents(this, this);

        getCommand("zonia").setExecutor(new Potion());

        logger.info(pdfFile.getName() + " version " + pdfFile.getVersion() + " has been enabled.");
    }

public void registerEvents() {
    PluginManager pm = getServer().getPluginManager();
//here is the error on PlayerJoin:The method PlayerJoin(OnStartup) is undefined for the type OnStartup
    pm.registerEvents(PlayerJoin(this), this);
}

private void registerConfig() {
    getConfig().options().copyDefaults(true);
    saveConfig();

}

public void onDisable() {
    PluginDescriptionFile pdfFile = getDescription();
    Logger logger = getLogger();
    logger.info(pdfFile.getName() + " version " + pdfFile.getVersion() + " has been disabled.");
    saveConfig();
}

}
Potion Class(Just in case):
package ml.zonia.plugin.commands;

import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;

public class Potion implements CommandExecutor, Listener {

public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {

    if (label.equalsIgnoreCase("zonia"))
        ;
    if (!(sender instanceof Player)) {
        sender.sendMessage("You must be in-game to execute this command.");
        return false;

    }

    Player player = (Player) sender;
    player.sendMessage(ChatColor.DARK_AQUA + "ZoniaCore, made by Patrick S.");
    return true;

}

}
PlayerJoin:
package ml.zonia.plugin.event;

import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;

import ml.zonia.plugin.OnStartup;

public class PlayerJoin implements Listener {

private OnStartup plugin;

public PlayerJoin(OnStartup pl) {
    plugin = pl;
}
@EventHandler
public void onJoin(PlayerJoinEvent pje) {
    int PlayerSpeed;
    PlayerSpeed = plugin.getConfig().getInt("PlayerSpeed");
    if (!pje.getPlayer().hasPermission("zonia.effects.remove"))
        ;
    pje.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, PlayerSpeed));
}

@EventHandler
public void onPlayerMove(PlayerMoveEvent pme) {
    double SpawnX, SpawnY, SpawnZ;
    SpawnX = plugin.getConfig().getDouble("SpawnX");
    SpawnY = plugin.getConfig().getDouble("SpawnY");
    SpawnZ = plugin.getConfig().getDouble("SpawnZ");
    if ((int) pme.getPlayer().getLocation().getY() == 20) {
        pme.getPlayer().teleport(new Location(Bukkit.getWorld("world"), SpawnX, SpawnY, SpawnZ));
    }
}

}
In eclipse, the config yml looks like this:
################################
#                              #
#     ZoniaCore-Hub Config     #
#         Version  1.0         #
#                              #
################################

#Sets the player's speed.
PlayerSpeed: 17

#sets X, Y, and Z of spawn.
SpawnX: -67.5
SpawnY: 156
SpawnZ: 4.5

#sets how much the player has to fall
#to be teleported back to spawn.
TeleportY: 50

But when it generates in the plugins folder under the plugin it generates the config like this, and I cant seem to make any changes to it.:
#
#                              #
#     ZoniaCore-Hub Config     #
#         Version  1.0         #
#                              #
PlayerSpeed: 6
SpawnX: -67.5
SpawnY: 156
SpawnZ: 4.5
TeleportY: 50

A: You probably mean:
pm.registerEvents(new PlayerJoin(this), this);

I don't see a PlayerJoin function, only the constructor. BTW it would be a bad practice to start a function name with capital letter, unless it's the constructor.


text:
Q: Inequality problem How might one show that $1\over 2m$$[\sigma_p^2+\mathbb E(p)^2]$ +$m\omega^2\over2$$[\sigma_x^2+\mathbb E(x)^2]$ $\geq \omega \sigma_x\sigma_p$?
The immediate thing I think would help is $(\sigma_p-\sigma_x)^2\geq0 \implies\sigma_p^2+\sigma_x^2\geq 2\sigma_p\sigma_x$. But then...?
Added: $m,\omega$ are positive constants. $\sigma_x,\sigma_p$ are standard deviations of $x,p$ respectively.
Thanks.

A: I assume this is taken from physics textbook or so. In particular, I assume $m$ (for mass),  $\omega$ (angular frequency?), as well as $\sigma_x$ and $\sigma_p$ (standard deviation terms) to be positive. The symbols are now defined.
Then the The given inequality follows by applying the AM-GM inequality to the nonnegative quantities $\frac{\sigma_p^2}{m}$ and $m \omega^2 \sigma_x^2$:
$$
\frac{1}{2} \left( \frac{\sigma_p^2}{m} + m \omega^2 \sigma_x^2 \right) \geq \sqrt{\frac{\sigma_p^2}{m} \times m \omega^2 \sigma_x^2} = \omega \sigma_p \sigma_x.
$$
Alternatively, you can also deduce this by expanding:
$$
\frac{1}{2} \left( \frac{\sigma_p}{\sqrt{m}} - \sqrt{m} \cdot \omega \sigma_x \right)^2 \geq 0.
$$
The two other terms involving $\mathrm{E}(x)^2$ and $\mathrm{E}(p)^2$ are nonnegative, so they do can be safely added to left hand side of the inequality.


text:
Q: Strange behavoir of RunWithElevatedPrivileges in Console Aplication with FBA
*

*I have a named site collection where FBA is on und i use ActiveDirectoryMembershipProvider.

*We have a farm administrator domain\administrator. He is not explicitly sitecollection administrator.

I created a sample console application that I run under the domain\administrator account.
In the code is something like that:
                    using (SPSite site = new SPSite(serverUrl))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            Console.WriteLine(web.CurrentUser.LoginName);
                            Console.WriteLine(WindowsIdentity.GetCurrent().Name);
                            string userName = "domain\\testuser";
                            SPUser spUser = web.EnsureUser(userName);
                            SPGroup group = web.SiteGroups["GroupName"];
                            group.AddUser(spUser);
                            group.Update();
                        }
                    }

The console output is domain\administrator however I become an AccessDenied exception when I try to add user to the group.
However when I run this with RunWithElevetadPrivileges (which according to all posts I read should have no influence in console app) and set AllowUnsafeUpdates = true (the same story) the code goes smoothly through, no exception thrown and the user is added to the group. The interesting thing is that the user that is written to the console output is still domain\administrator.
So my question is: WTF? Is there a better way? Why is this happenning? Has anyone already had this problem? Should I use another membershipprovider?
Small hint: When the FBA is off I become no exceptions.

A: RunWithElevatedPrivileges runs code with permissions of user that the application pool runs. It can be other than Administrator. Are you sure you get the same result with RunWithElevatedPrivileges?
Anyway, a better, more reliable way of elevating privileges is to pass system users User token in SPSite constructor. Try it.


text:
Q: Hidden symbol `__udivti3' in .../libgcc.a is referenced by DSO I am trying to compile a simple executable using CMake and Clang on Ubuntu 18. Some code coming from a third party source and compiled as a shared library  libtommath ends up calling the function __udivti3 after the compiler does some code optimisations.
At link time, I have an error coming from ld saying hidden symbol "__udivti3" in /usr/lib/gcc/x86_64-linux-gnu/7/libgcc.a(_udivdi3.o) is referenced by DSO
I did some research and thanks to this link this effectively means that __udivti3 is referenced by the shared library but It cannot be used from the libgcc.a as it is marked as hidden in this library.
My issue is whatever I try to fix it, the linkage always fails. I tried to link with libgcc_s which is located in the same directory but clang complains it cannot find it. On the other hand though, the compilation and linkage work perfectly on MacOS, with that problematic symbol still being present.


text:
Q: Biasing a common collector How do I bias a common collector to secure maximum output swing WITHOUT using a resistive divider? How can I use my transistor as a voltage source with output about half my Vcc?

A: Perhaps your instructor was remembering some of the early electronics books which showed the use of a bias battery in many circuits - perhaps even a hangover from the days of valves for biasing the grid negative.


text:
Q: How do I display a user's previous orders as a select box option on a product? I have an audio customization site (Wordpress/Woocommerce) that allows users to purchase licensed music in either an 'as-is' state or a customized version of it. The specifications of a customization are determined before the product is added to cart via monetized on-page options (eg. voiceovers, sound fx, etc).
Turns out a lot of customers don't know they want it customized until days/weeks/months after purchasing.
So I created individual products that mirror the product options so customers can still purchase them and basically 'apply them' to a previous order.
What I would like to do is to create a select box option on each of these products that calls the user's previous order numbers, so user's may specify which previous order they are applying this new purchase to.
If anyone can provide any direction on this I would greatly appreciate it.

A: You can try something like this:
add_action( 'woocommerce_before_add_to_cart_form', 'add_list_completed_orders' );
function add_list_completed_orders() {
    // get orders
    $orders = wc_get_orders (
        array (
            'status'        => array( 'wc-completed' ),
            'type'          => 'shop_order',
            'limit'         => -1,
            'return'        => 'ids',
            'customer_id'   => get_current_user_id(),
        )
    );

    if ( ! empty( $orders ) ) {
        // set value options
        $options = '';
        foreach ( $orders as $order_id ) {
            $options .= '<option value="' . $order_id . '">' . $order_id . '</option>';
        }
        // add list
        $form = '<label for="orders">Select completed orders:</label>';
        $form .= '<select id="orders" name="orders">' . $options . '</select>';
        echo $form;
    }

}

Tested and it works. The code goes into your theme's functions.php.


text:
Q: Classes/interfaces: A doesn't implement IA that has property of type IB, despite implementing B which implements IB Can someone explain why this doesn't compile? More specifically, you get an error stating that class A doesn't implement IA, even though B "is a" (implements) IB, which should satisfy IA? Or am I doing something completely wrong?
(I want to keep A/B as specific as possible, while still implementing IA/IB in order to pass it to a method that takes in IA)
public interface IA {
    public string Field { get; set; }
    public IB B { get; set; }
}

public interface IB {
    public string OtherField { get; set; }
}

public class A : IA {
    public string Field { get; set; }
    public B B { get; set; }
}

public class B : IB {
    public string OtherField { get; set; }
}

A: You're changing the signature that the interface enforced.
Even though B implements IB, there might be another class that implements IB, and for IA interface, it is a valid type to set as property B.
For instance:
    public class A1
    {
        public string Field { get; set; }
        public IB B { get; set; }

        public A1()
        {
            B = new B(); // completely valid
            B = new Bv2(); // completely valid as well, as Bv2 : IB
        }
    }

    public class A2
    {
        public string Field { get; set; }
        public B B { get; set; }

        public A2()
        {
            B = new B();   // completely valid
            B = new Bv2(); // CTE: Cannot implicitly convert type 'Bv2' to 'B'
        }
    }

So, in your example, you only need to adjust your class A slightly for it to work:
    public class A : IA
    {
        public string Field { get; set; }
        public IB B { get; set; }
    }

Or make IA specifically accept property B as an instance of a class B (1st option is generally better, allows more flexible design):
    public interface IA
    {
        string Field { get; set; }
        B B { get; set; }
    }

A: As pinkfloydx33 pointed out in their comment, the interface signature must be followed exactly, so A must have a property of type IB, and not of any type that implements IB. Plus, it's just better that A doesn't depend on a concrete implementation of IB. So your A class must (and should) look like this:
public class A
{
    public string Field {get; set;}

    public IB B {get; set;}
}

Note that
var b = new B();
var a = new A();

a.B = b;

Works and you don't need a cast, as b is implicitly converted to an IB

A: What should work is:
    public interface IA<out TIB> where TIB : IB // EDIT: Changed to "out" TIB
    {
        public string Field { get; set; }
        public TIB B { get; } // Edit: removed setter. Not possible with "out" Type
    }

    public interface IB
    {
        public string OtherField { get; set; }
    }

    public class A : IA<B>
    {
        public string Field { get; set; }
        public B B { get; set; }
    }

    public class B : IB
    {
        public string OtherField { get; set; }
    }


text:
Q: How can I separate a pandas dataframe based on time differences? I pulled my group's text messages and it looks something like the table below (excluding the third column).
How can I separate the first conversation from the second based on time and assign each message to a conversation_id?
If it helps, I'm comfortable assuming that if any message hasn't been responded to in an hour, the next message starts a new conversation.
If given the first the two columns, I'd ideally be able to figure out the third across nearly 45,000 messages with varying conversation lengths.
Once I have our text messages split into conversations, I think I could train a chatbot to participate in our chats! I don't know what I'm doing here so I'd appreciate any help :)
| created_at          | message                              | conversation_id |
| 2018-07-03 02:12:33 | knock knock                          | 1               |
| 2018-07-03 02:12:35 | who's there                          | 1               |
| 2018-07-03 02:12:40 | Europe                               | 1               |
| 2018-07-03 02:12:45 | Europe who?                          | 1               |
| 2018-07-03 02:12:48 | No - you're a poo                    | 1               |
| 2018-07-03 03:15:17 | knock knock                          | 2               |
| 2018-07-03 03:15:20 | who's there                          | 2               |
| 2018-07-03 03:15:23 | the KGB                              | 2               |
| 2018-07-03 03:15:28 | the KGB who?                         | 2               |
| 2018-07-03 03:15:33 | SLAP the KGB will ask the questions! | 2               |

A: This should do the trick. I don't think you can improve much upon iterating through the dataframe in order to assign the ID's, since they're based on a chained connection to previous values in the column:

d = {"created_at": pd.to_datetime(["2018-07-03 02:12:33", "2018-07-03 02:12:35","2018-07-03 02:12:40","2018-07-03 02:12:45","2018-07-03 02:12:48","2018-07-03 03:15:17","2018-07-03 03:15:20","2018-07-03 03:15:23","2018-07-03 03:15:28","2018-07-03 03:15:33","2018-08-03 09:00:00","2018-09-03 10:15:00"]),
     "message": ["knock knock","who's there","Europe","Europe who?","No - you're a poo","knock knock","who's there","the KGB","the KGB who?","SLAP the KGB will ask q's!","Hello?","Hello, again?"]}

import pandas as pd
import numpy as np

#60mins in secs
thresh = 60*60

df = pd.DataFrame(data=d)

#Creating time delta from previous message
df["delta"] = df["created_at"].diff().fillna(0).dt.total_seconds()

#Normalising delta based on threshold as a flag for new convos
df["id"] = np.where(df["delta"] < thresh, 0, 1)
df = df.drop(["delta"], axis=1)

#Assigning ID's to each convo
for i in range(1, len(df)):
    df.loc[i, 'id'] += df.loc[i-1, 'id']

print(df)

            created_at                     message  id
0  2018-07-03 02:12:33                 knock knock   0
1  2018-07-03 02:12:35                 who's there   0
2  2018-07-03 02:12:40                      Europe   0
3  2018-07-03 02:12:45                 Europe who?   0
4  2018-07-03 02:12:48           No - you're a poo   0
5  2018-07-03 03:15:17                 knock knock   1
6  2018-07-03 03:15:20                 who's there   1
7  2018-07-03 03:15:23                     the KGB   1
8  2018-07-03 03:15:28                the KGB who?   1
9  2018-07-03 03:15:33  SLAP the KGB will ask q's!   1
10 2018-08-03 09:00:00                      Hello?   2
11 2018-09-03 10:15:00               Hello, again?   3


text:
Q: ActiveRecord::ActsAs routing problems Upgrading an old Rails 3 app to Rails 4, multiple table inheritance gem has been changed due to deprecation. Now, using ActsAs.
Nested routes are not working producing following error:
undefined method `vehicle_path' for #<#<Class:0x007f0e2778da70>:0x007f0e26725778>

when called:
  - @vehicles.each do |vehicle|
    %tr
      %td= link_to vehicle.code, vehicle

Parent class:
class Vehicle < ActiveRecord::Base
  actable
end

Child class:
class Vehicles::Car < ActiveRecord::Base
  acts_as :vehicle
end

Routes.rb:
namespace :vehicles do
  resources :cars, except: [:index]
end

Any help would be appreciated.
Update: Rake routes
vehicles          GET    /:locale/vehicles(.:format)                  vehicles#index {:locale=>/en|es/}

vehicles_cars     POST   /:locale/vehicles/cars(.:format)             vehicles/cars#create {:locale=>/en|es/}

new_vehicles_car  GET    /:locale/vehicles/cars/new(.:format)         vehicles/cars#new {:locale=>/en|es/}

edit_vehicles_car GET    /:locale/vehicles/cars/:id/edit(.:format)    vehicles/cars#edit {:locale=>/en|es/}

vehicles_car      GET    /:locale/vehicles/cars/:id(.:format)         vehicles/cars#show {:locale=>/en|es/}

                  PATCH  /:locale/vehicles/cars/:id(.:format)         vehicles/cars#update {:locale=>/en|es/}

                  PUT    /:locale/vehicles/cars/:id(.:format)         vehicles/cars#update {:locale=>/en|es/}

                  DELETE /:locale/vehicles/cars/:id(.:format)


text:
Q: Animating div sliding from 100% of div width on x axis I have an invisible square2 div positioned to the left of square1. I'm using GSAP to animate square1 moving to the left, then after that I want to separately animate square2 slowly sliding out of square1.
I got the first part of the animation working, but I'm not unable to figure out how to get square2 to slide out of it.
I'm trying to position square2 100% of the div's width to the right, make it visible, then animate it moving to the left. This is my attempt.
I don't believe the visibility setting is necessary since GSAP should make it visible automatically, but I included it in case anyone thought the visibility settings were the issue.
Codepen: https://codepen.io/SquanchyHappy/pen/rNmKJdJ

body {
  background-color: black;
}

#container {
  position: absolute;
  right: 0%;
  width: 200px;
}

#square1 {
  visibility: hidden;
  background-color: grey;
height: 100px;
  width: 100px;
  float: left;
}

#square2 {
  background-color: blue;
  height: 100px;
  width: 100px;
  float: right;
}

gsap.registerPlugin("MotionPathPlugin");

slideAnimation();

function slideAnimation() {
  let tl = gsap.timeline({ delay: 1 });
  tl.set(square2, { xPercent: 50, transformOrigin: "0% 50%" });
  tl.from(
    square2,
    { x: screen.width, ease: "none", duration: 0.5 },
    0
  );
  tl.from(
    square2,
    {
      y: square2.getBoundingClientRect().top - 300,
      ease: "none",
      duration: 0.5
    },
    0
  );
  tl.to(square2, {
    xPercent: 0,
    duration: 0.5,
    ease: "power2",
    clearProps: "transform"
  });
  //Below is the part I can't figure out
  //square2.style.visibility = 'visible'
  //tl.set(square2, {xPercent: 100})
  //tl.from(square2, {duration: 3})
}


text:
Q: algorithm for solving a matrix There is a N * N matrix, for eg., we can take a 3 * 3 matrix,
3 6 5 9
4 5 0 8
8 7 9 0
3 4 0 1

The problem is to traverse all the '0's in the given matrix by passing through minimum numbers. For eg.,if we start from 3 (1,1), we can reach (2,3) by passign through (1,1)--> (1,2)--> (2,3) but we have to take the way (1,1)-->(2,2)--> (2,3).since we have to use minimum weight in the path.
(3+6 weight in the first case and 3+5 weight in the second case).
we have design an algorithm to traverse all the 0's  with minimum weight in the path.
My algorithm :
1. Mark all the 0's in the given matrix and count.
2. BFS loop: Induce a BFS from any node to reach the 0's. exit loop once the 0's are found.
but the weight of the path should be the minimum to find the 0's, could anyone help me in solving this?

A: This is a variation of the Traveling Salesman Problem, which is NP-Complete (This means there is no known efficient solution, and most believe such a solution does not exist).
Possible solution for small matrix:

*

*Represent your matrix as a weighted graph, where a vertex is a cell
and an edge is a possible move from two cells, with the weight being
the value of the target cell.

*You can find all-to-all shortest path using Floyd-Warshall algorithm, and create a graph containing only zeros, and the weight to move from each zero to the other, according to Floyd-Warshall weights.

*Use a TSP solver (a naive one is to generate all permutations and chose the best out of them)

The thread: Find the shortest path between a given source and a set of destinations deals with steps 2+3 in the above explanation with more details.

However, if you have extra restrictions that you did not mention (for example, can only move torwards down and right), your underlying graph is actually a Directed Acyclic Graph, and you can solve it more efficiently.


text:
Q: É possível inserir o caractere '#' (hash) nas rotas do MVC? É possível inserir o caractere # (hash) nas rotas do MVC? Estou desenvolvendo uma aplicação em MVC no qual uma das especificações é o uso de # nas rotas do MVC.
É possível realizar isso nativamente? Existe algum meio de contornar a situação?
Grato!

A:
É possível realizar isso nativamente? Existe algum meio de contornar a situação?

Não. # é um símbolo reservado para navegadores para indicar âncoras e não pode fazer parte de rotas.
Como só o cliente possui acesso ao que vem depois de #, não faz muito sentido definir rotas com ele. Só confundiria o navegador e o JavaScript não funcionaria direito.

A: Como já foi dito, com rotas não é possível fazer isso.
Uma forma de fazer isso, seria alterar o retorno do Controller para um Redirect() para o página desejada.
Algo como isso:
 return Redirect("/Home/Contact#contato");

Ou isso:
return Redirect(Url.Action("Contact", "Home") + "#contato");

Lembrando que isso colocará apenas "uma âncora" no final da URL. não sei ao certo o que deseja fazer com isso.
Caso queira mais detalhes, esta pergunta possui mais respostas sobre oq ue você perguntou.

Nota: Caso opte por usar o Redirect(), tome cuidado. Se a requisição para a mesma Action(), irá causar um Loop Infinito.

Caso queira fazer isso no cliente, você pode customizar o HtmlHelper e criar o seu próprio, com a rota desejada.


text:
Q: Query pages by child term I cannot seem to get this to work, I have tried everything I can think of and spent enough time googling, to get me to seek help elsewhere.
I need to query pages in a loop, using the same taxonomy as the current page, but the child term of the current pages term.
For example,
taxonomy = walls
current page term = art

queried pages taxonomy = art
queried pages term= modern-art ( where art is the parent term of modern-art)

I can do this using
$args = array(
  'post_type' => 'page'
  'orderby' => 'menu_order',
  'order'=>'ASC',
  'tax_query'   => array(
        array(
            'taxonomy' => 'walls',
            'field'    => 'slug',
            'terms'    =>  'modern-art'
       )
    )

However, I need this code to be dynamic and fetch the data. So I can use the same template of lots of different parent and child terms.

A: What do you mean by "dynamic" ? Do you want it to work with different posts?
If so, that's simple. Before your get_posts query function, get page terms, and pass them to your array. You can get taxonomies with
 <?php get_the_terms( $yourpostid, 'your_custom_taxonomy'); ?>


text:
Q: Netlogo , How to display number of ticks Hi I am writing simulation which uses ticks to represent time in simulation environment . Is it possible to display tick counter in monitor GUI? Also I have tried to input the code but it is not working.
My sample code:
if [agents count = 0]
show "count ticks"

This should show tick exactly value when agent unit value is zero. For example if agent = 0 at tick 200 it should display 200 on monitor even the whole simulation run on 500 ticks.
whole code is
  patches-own[
  nest?
  nest-scent
  food
  food-source-number
  chemical
   ]

breed [agents agent] ;agent is ant
breed [antiagents a-antiagent] ;antiagent spider
antiagents-own[energy]
agents-own[venom]

;;;;;;;;;;;;;;;;;;;;;;;;;; Setup ;;;;;;;;;;;;;;;;;;;
to setup
  clear-all

set-default-shape agents "ant"
  create-agents initial-ants  ;; create the ants, then initialize their variables
  [
    set color orange
    set size 2  ;; easier to see
    set venom  (ant-venom-strength)

  ]

  set-default-shape antiagents "spider"
  create-antiagents initial-spiders  ;; create the spider, then initialize their variables
  [
    set color yellow
    set size 3  ;; easier to see
    set energy (spider-health)
    setxy random-xcor random-ycor
  ]
  setup-patch
  display-labels

  reset-ticks
 end

;;;;; nest food patch;;;
to setup-patch
   ask patches
  [ setup-nest
    setup-food
    recolor-patch ]
end

;;;;; setup nest
to setup-nest  ;; patch procedure
  ;; set nest? variable to true inside the nest, false elsewhere
  set nest? (distancexy 0 0) < 5
  ;; spread a nest-scent over the whole world -- stronger near the nest
  set nest-scent 200 - distancexy 0 0
end

to setup-food  ;; patch procedure
  ;; setup food source one on the right
  if (distancexy (0.6 * max-pxcor) 0) < 5
  [ set food-source-number 1 ]
  ;; setup food source two on the lower-left
  if (distancexy (-0.6 * max-pxcor) (-0.6 * max-pycor)) < 5
  [ set food-source-number 2 ]
  ;; setup food source three on the upper-left
  if (distancexy (-0.8 * max-pxcor) (0.8 * max-pycor)) < 5
  [ set food-source-number 3 ]
  ;; set "food" at sources to either 1 or 2, randomly
  if food-source-number > 0
  [ set food one-of [1 2] ]
end

to recolor-patch  ;; patch procedure
  ;; give color to nest and food sources
  ifelse nest?
  [ set pcolor violet ]
  [ ifelse food > 0
    [ if food-source-number = 1 [ set pcolor cyan ]
      if food-source-number = 2 [ set pcolor sky  ]
      if food-source-number = 3 [ set pcolor blue ]
      if food-source-number = 4 [ set pcolor brown ]  ]
    ;; scale color to show chemical concentration
    [ set pcolor scale-color green chemical 0.1 5 ] ]
end

  ;;;;;;;;;;;;;;;;;;;;;;;;;;; GO ;;;;;;;;;;;;;;;;;;;;;;

 to go  ;; forever button
   ;;;;;;;;;;;;Spider ;;;;;;;;
   ask antiagents [
     setup-spider-movemonet ; option for user to select spider movement
     ;move-spider
     catch-ant
     spider-death
     ]

   ;;;;;;;;;; Ant ;;;;;;;;;;;;
  ask agents
  [ if who >= ticks [ stop ] ;; delay initial departure
    ifelse color = orange
    [ look-for-food  ]       ;; not carrying food? look for it
    [ return-to-nest ]       ;; carrying food? take it back to nest
    wiggle
    fd 1 ]
  diffuse chemical (diffusion-rate / 100)
  ask patches
  [ set chemical chemical * (100 - evaporation-rate) / 100  ;; slowly evaporate chemical
    recolor-patch ]

  tick
  display-labels
  ;;;;;;;;;;; Stop function ;;;;;;;;;;

  if count agents = 0 [stop]

  if count patches with [pcolor = blue] = 0 [stop]

end

 ;;;;;;;;;;;;;;;;;;;;;;;;;; function in go ;;;;;;;;;;;;;;;

to look-for-food  ;; turtle procedure
  if food > 0
  [ set color green + 1     ;; pick up food
    set food food - 1        ;; and reduce the food source
    rt 180                   ;; and turn around
    stop ]
  ;; go in the direction where the chemical smell is strongest
  if (chemical >= 0.05) and (chemical < 2)
  [ uphill-chemical ]
end

;;;;;;;;;;; ant function ;;;;;;;;;;

 ;; sniff left and right, and go where the strongest smell is
to uphill-chemical  ;; turtle procedure
  let scent-ahead chemical-scent-at-angle   0
  let scent-right chemical-scent-at-angle  45
  let scent-left  chemical-scent-at-angle -45
  if (scent-right > scent-ahead) or (scent-left > scent-ahead)
  [ ifelse scent-right > scent-left
    [ rt 45 ]
    [ lt 45 ] ]
end

to return-to-nest
  ifelse nest?
  [ ;; drop food and head out again
    set color orange
    rt 180 ]
  [ set chemical chemical + 60  ;; drop some chemical
    uphill-nest-scent ]         ;; head toward the greatest value of nest-scent
end

to wiggle  ;; turtle procedure
  rt random 40
  lt random 40
  if not can-move? 1 [ rt 180 ]
end
to uphill-nest-scent
  let scent-ahead nest-scent-at-angle   0
  let scent-right nest-scent-at-angle  45
  let scent-left  nest-scent-at-angle -45
  if (scent-right > scent-ahead) or (scent-left > scent-ahead)
  [ ifelse scent-right > scent-left
    [ rt 45 ]
    [ lt 45 ] ]
end

to-report chemical-scent-at-angle [angle]
  let p patch-right-and-ahead angle 1
  if p = nobody [ report 0 ]
  report [chemical] of p
end

to-report nest-scent-at-angle [angle]
  let p patch-right-and-ahead angle 1
  if p = nobody [ report 0 ]
  report [nest-scent] of p
end

;;;;;;;;;;;;;;;;;;;;;;;;;;;; Spider-Function ;;;;;;;;;;;;;;;;;;;;;;
to move-spider
  rt random 360
  lt random 360
  fd 3
end

to spider-death  ;; turtle procedure

  if energy  <= 0 [ask antiagents-here  [die]]

end

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
to catch-ant
  let prey one-of agents-here
  if prey != nobody
     [ ask prey [ die ]
      set energy (energy  - ant-venom-strength)]
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

 ;;;;; GUI Function ;;;;
 to display-labels
  ask antiagents [ set label "" ]
  if show-spider-health [
    ask antiagents [ set label round energy ]
    ]
end

 ;;;;;;; Spider movement GUI ;;;;;;
 to setup-spider-movemonet
         if setup-spider-movement
      [
        ask antiagents [ move-spider ]
      ]
 end

A: To make a monitor that displays the tick count, the complete code to put in the monitor is:
ticks

That's all.
If you want the monitor to show the tick count when there are no agents, but be blank otherwise, you would put this code in:
ifelse-value any? agents
  [ "" ]
  [ ticks ]

A: *

*Your syntax is incorrect.  You could however include in an observer procedure (e.g., your go procedure) the following: if (count agents = 0) [show ticks].     This would display in the area above the command line.

*However it sounds like you are looking for user-message, rather than show.  E.g., if (count agents = 0) [user-message (word ticks)]. http://ccl.northwestern.edu/netlogo/docs/dict/user-message.html

A: If you want to update the monitor each tick but only when there are agents, you need to create a separate global variable (called counter below) and update that instead. The ticks internal variable will always increase so monitoring it will always increment. This is because the ticks variable is the simulation clock, it reports the passage of time.
globals [counter]

to setup
  ...
  set counter 0    ; note, not required as initialise to 0 but helps readability
  reset-ticks
end

to go
  ...
  if any? turtles [ set counter counter + 1 ]
  ...
  tick
end

Then create a monitor with just counter (and 0 decimal places etc)


text:
Q: Transferring data from one table to another, some relational columns Table 1 - this table is completely populated from an XLSX file...

Tables 2 and 3 - contain 1-1 references for a couple of the columns in the final table.

Table 3 - the on I am trying to get populated with first three tables....

As you can see, the tables are sensible, there is no einsteinic equations or conversions going on. Here is the code that I have already tried, unsuccessfully:
INSERT INTO att_oem_orders SELECT NULL, ost.om_or_po, (SELECT j.job_id FROM jobs j WHERE j.project_number = project_no), NULL, (SELECT ao.id FROM att_oem WHERE ao.item_no = item_no), ost.po_number, (SELECT ol.id FROM order_lsc WHERE STATUS = ol.line_status_code), ost.ordered_date, ost.shipment_date, NULL, NULL, ost.item_qty, NULL, NULL, NULL, NULL, ost.shipping_to, ost.tracking_number, ost.carrier) FROM oem_temp_sync WHERE ost.item_qty > 0

A: Try limiting the number of possible values to put into a field using FIRST() like so:
INSERT INTO att_oem_orders SELECT
    NULL,
    ost.om_or_po,
    (SELECT FIRST(j.job_id) FROM jobs j WHERE j.project_number = project_no),
    NULL,
    (SELECT FIRST(ao.id) FROM att_oem WHERE ao.item_no = item_no),
    ost.po_number,
    (SELECT FIRST(ol.id) FROM order_lsc WHERE STATUS = ol.line_status_code),
    ost.ordered_date,
    ost.shipment_date,
    NULL,
    NULL,
    ost.item_qty,
    NULL,
    NULL,
    NULL,
    NULL,
    ost.shipping_to,
    ost.tracking_number,
    ost.carrier
FROM oem_temp_sync WHERE ost.item_qty > 0

You also appear to have an extra ) just before FROM

A: With a little bit of help from everyone, I've found a few errors and fixed a few sub-queries. Here is the final version:
INSERT INTO att_oem_orders
SELECT
    NULL,
    ost.om_or_po,
    (SELECT
        FIRST(j.id)
    FROM
        jobs j
    WHERE j.project_number = ost.project_no),
    NULL,
    (SELECT
        FIRST(ao.id)
    FROM
        att_oem ao
    WHERE ao.item_no = ost.item_no),
    ost.po_number,
    (SELECT
        FIRST(ol.id)
    FROM
        att_oem_lsc ol
    WHERE ol.status = ost.line_status_code),
    ost.ordered_date,
    ost.shipment_date,
    NULL,
    NULL,
    ost.item_qty,
    NULL,
    NULL,
    NULL,
    NULL,
    ost.ship_to,
    ost.tracking_no,
    ost.carrier
FROM
    oem_sync_temp  ost
WHERE ost.item_qty > 0


text:
Q: Implementing MERGE INTO using Table as target and dataframe as source(SPARK/SCALA) I am trying to implement merge in scala /spark . My target database is DB2.
Spark version : 3.x
if anyone has implemented solution like this please share your thought process
Thanks in advance
Update : As asked by one of the member What do I mean by merge
Table : emp (target) emp_id(primary key) emp_name salary
100 Bob 1000
200 Kelley 2000
300 Ron 1200
Table : emp_ext (source table from where we load data)
emp_id(primary key) emp_name salary
100 Bob 1100 (Row Changed)
200 Kelley 2000 (No Change)
300 Ron 1200 (No Change)
Final state of table emp
emp_id(primary key) emp_name salary
100 Bob 1100
200 Kelley 2000
300 Ron 1200


text:
Q: jQuery's .css isn't adding background attribute to body As I'm trying to create a grid of images for my background, I need to be able to add the background-image attribute to the css of the body via jQuery, but it isn't working. The following code returns the correct value, but all I see in the end is a blank page.
<body>
<script>

$('body').css('background-image', function() {

    var position = 0,
        image = '';

    for(var x=1; x<=4; x++) {
        // 4 rows

        for(var y=1; y<=8; y++) {
            // 8 columns

            position++;

            image += 'url(img/bg/' + position + '.jpg)';
            if(x<=4 && y<8) { image += ','; }

        }

    }

    console.log(image);
    return image;

});

</script>

As you can see, I'm doing the script work after the body tag is created, so my understanding is that I don't need $(function(){}) to make things happen.
Can anyone see what's keeping this from working?

A: Your if condition is wrong, so you're leaving out the , after every 8 URLs.

$(function() {
  $('body').css('background-image', function() {

    var position = 0,
      image = '';

    for (var x = 1; x <= 4; x++) {
      // 4 rows

      for (var y = 1; y <= 8; y++) {
        // 8 columns

        position++;

        image += 'url(img/bg/' + position + '.jpg)';
        if (x < 4 || y < 8) {
          image += ',';
        }

      }

    }

    console.log(image);
    return image;

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

The way I prefer to do things like this is to push the elements onto an array, then construct the string using array.join(',').


text:
Q: Is there a way to use Azure Diagnostics 1.0 for Azure SDK 2.5 projects Is there a way to keep Diagnostics 1.0 but upgrade to Azure SDK 2.5?
We use very simple diagnostics that just writes into Trace (and as a result into storage table). We also deploy our service as a package via Azure portal. Introducing of Diagnostics 1.3 is a quite a breaking change for our process, since it requires PowerShell to deploy Diagnostics extension.
I tried to revert back Cloud configuration files (import Diagnostics module) but it is not working. It seems that I have to stay on SDK 2.4 for now.

A:
Is there a way to keep Diagnostics 1.0 but upgrade to Azure SDK 2.5?

Unfortunately No. If you upgrade your Cloud Services to SDK 2.5, you can't use diagnostics 1.0. You have to use 1.3 version of the diagnostics.
We did the same with our projects and faced more or less the same issues as you faced and had to revert back. What we did was kept SDK 2.5 installed on the machines however our projects still use SDK 2.4 i.e. all referenced libraries in our project are from SDK 2.4.


text:
Q: How can I create a NLog Config Timeshift by hours in C#? How can I, if possible, create a log file with a timestamp that is shifted by x hours?
<variable name="logdt" value="${shortdate}"/>
<targets>
    <target
        name="file" xsi:type="File"
        layout="${shortdate}${semi}${time}${semi}${message}"
        fileName="${basedir}\logs\${logdt}**-6h**.csv"
        archiveFileName="${basedir}\archives\${logdt}**-6h**.{#}.zip"
        archiveEvery="Day"
        archiveNumbering="Rolling"
        maxArchiveFiles="7"
        enableArchiveFileCompression="true"
        keepFileOpen="true"
        openFileCacheTimeout="30"
    />
</targets>

A: You can configure the Time Source.
https://github.com/NLog/NLog/wiki/Time-Source


text:
Q: Unable to update to Ubuntu 22.04 from Ubuntu 20.04 So I've been trying to update to Ubuntu 22.04 development release but certain errors are coming. Whenever I try to update the following error comes ->
abc@ubuntu:~$ update-manager -d
Checking for a new Ubuntu release
authenticate 'jammy.tar.gz' against 'jammy.tar.gz.gpg'
extracting 'jammy.tar.gz'
No candidate ver:  chromium
No candidate ver:  microsoft-edge-stable
Traceback (most recent call last):
  File "/tmp/ubuntu-release-upgrader-6ylluso8/jammy", line 8, in <module>
    sys.exit(main())
  File "/tmp/ubuntu-release-upgrader-6ylluso8/DistUpgrade/DistUpgradeMain.py", line 241, in main
    if app.run():
  File "/tmp/ubuntu-release-upgrader-6ylluso8/DistUpgrade/DistUpgradeController.py", line 2038, in run
    return self.fullUpgrade()
  File "/tmp/ubuntu-release-upgrader-6ylluso8/DistUpgrade/DistUpgradeController.py", line 1881, in fullUpgrade
    if not self.updateSourcesList():
  File "/tmp/ubuntu-release-upgrader-6ylluso8/DistUpgrade/DistUpgradeController.py", line 784, in updateSourcesList
    self.sources = SourcesList(matcherPath=self.datadir)
  File "/usr/lib/python3/dist-packages/aptsources/sourceslist.py", line 273, in __init__
    self.matcher = SourceEntryMatcher(matcherPath)
  File "/usr/lib/python3/dist-packages/aptsources/sourceslist.py", line 470, in __init__
    dist = DistInfo(base_dir=matcherPath)
  File "/usr/lib/python3/dist-packages/aptsources/distinfo.py", line 184, in __init__
    with open(dist_fname) as dist_file:
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/ubuntu-release-upgrader-6ylluso8/Ubuntu.info'
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/problem_report.py", line 477, in add_to_existing
    self.write(f)
  File "/usr/lib/python3/dist-packages/problem_report.py", line 430, in write
    block = f.read(1048576)
  File "/usr/lib/python3.8/codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte

Original exception was:
Traceback (most recent call last):
  File "/tmp/ubuntu-release-upgrader-6ylluso8/jammy", line 8, in <module>
    sys.exit(main())
  File "/tmp/ubuntu-release-upgrader-6ylluso8/DistUpgrade/DistUpgradeMain.py", line 241, in main
    if app.run():
  File "/tmp/ubuntu-release-upgrader-6ylluso8/DistUpgrade/DistUpgradeController.py", line 2038, in run
    return self.fullUpgrade()
  File "/tmp/ubuntu-release-upgrader-6ylluso8/DistUpgrade/DistUpgradeController.py", line 1881, in fullUpgrade
    if not self.updateSourcesList():
  File "/tmp/ubuntu-release-upgrader-6ylluso8/DistUpgrade/DistUpgradeController.py", line 784, in updateSourcesList
    self.sources = SourcesList(matcherPath=self.datadir)
  File "/usr/lib/python3/dist-packages/aptsources/sourceslist.py", line 273, in __init__
    self.matcher = SourceEntryMatcher(matcherPath)
  File "/usr/lib/python3/dist-packages/aptsources/sourceslist.py", line 470, in __init__
    dist = DistInfo(base_dir=matcherPath)
  File "/usr/lib/python3/dist-packages/aptsources/distinfo.py", line 184, in __init__
    with open(dist_fname) as dist_file:
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/ubuntu-release-upgrader-6ylluso8/Ubuntu.info'

Is there any solution to this?
I guess a file named Ubuntu.info is missing.
EDIT:
I was asked to disable 3rd party repos by @vanadium, but the results remained unchanged.
abc@ubuntu:~$ sudo do-release-upgrade -d
Checking for a new Ubuntu release
Checking for a new Ubuntu release
authenticate 'jammy.tar.gz' against 'jammy.tar.gz.gpg'
extracting 'jammy.tar.gz'
No candidate ver:  chromium
No candidate ver:  microsoft-edge-stable
No candidate ver:  pipewire-audio-client-libraries
No candidate ver:  pipewire-bin
No candidate ver:  pipewire-media-session
No candidate ver:  pipewire-pulse
Traceback (most recent call last):
  File "/tmp/ubuntu-release-upgrader-son1yxme/jammy", line 8, in <module>
    sys.exit(main())
  File "/tmp/ubuntu-release-upgrader-son1yxme/DistUpgrade/DistUpgradeMain.py", line 241, in main
    if app.run():
  File "/tmp/ubuntu-release-upgrader-son1yxme/DistUpgrade/DistUpgradeController.py", line 2038, in run
    return self.fullUpgrade()
  File "/tmp/ubuntu-release-upgrader-son1yxme/DistUpgrade/DistUpgradeController.py", line 1881, in fullUpgrade
    if not self.updateSourcesList():
  File "/tmp/ubuntu-release-upgrader-son1yxme/DistUpgrade/DistUpgradeController.py", line 784, in updateSourcesList
    self.sources = SourcesList(matcherPath=self.datadir)
  File "/usr/lib/python3/dist-packages/aptsources/sourceslist.py", line 273, in __init__
    self.matcher = SourceEntryMatcher(matcherPath)
  File "/usr/lib/python3/dist-packages/aptsources/sourceslist.py", line 470, in __init__
    dist = DistInfo(base_dir=matcherPath)
  File "/usr/lib/python3/dist-packages/aptsources/distinfo.py", line 184, in __init__
    with open(dist_fname) as dist_file:
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/ubuntu-release-upgrader-son1yxme/Ubuntu.info'
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/problem_report.py", line 477, in add_to_existing
    self.write(f)
  File "/usr/lib/python3/dist-packages/problem_report.py", line 430, in write
    block = f.read(1048576)
  File "/usr/lib/python3.8/codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte

Original exception was:
Traceback (most recent call last):
  File "/tmp/ubuntu-release-upgrader-son1yxme/jammy", line 8, in <module>
    sys.exit(main())
  File "/tmp/ubuntu-release-upgrader-son1yxme/DistUpgrade/DistUpgradeMain.py", line 241, in main
    if app.run():
  File "/tmp/ubuntu-release-upgrader-son1yxme/DistUpgrade/DistUpgradeController.py", line 2038, in run
    return self.fullUpgrade()
  File "/tmp/ubuntu-release-upgrader-son1yxme/DistUpgrade/DistUpgradeController.py", line 1881, in fullUpgrade
    if not self.updateSourcesList():
  File "/tmp/ubuntu-release-upgrader-son1yxme/DistUpgrade/DistUpgradeController.py", line 784, in updateSourcesList
    self.sources = SourcesList(matcherPath=self.datadir)
  File "/usr/lib/python3/dist-packages/aptsources/sourceslist.py", line 273, in __init__
    self.matcher = SourceEntryMatcher(matcherPath)
  File "/usr/lib/python3/dist-packages/aptsources/sourceslist.py", line 470, in __init__
    dist = DistInfo(base_dir=matcherPath)
  File "/usr/lib/python3/dist-packages/aptsources/distinfo.py", line 184, in __init__
    with open(dist_fname) as dist_file:
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/ubuntu-release-upgrader-son1yxme/Ubuntu.info'

A: Just ran into this while doing a do-release-upgrade manually.  The gui was failing before this.  The workaround answer from here by MarianD is what solved it for me.  You need to create the Ubuntu.info file in the /tmp/ubuntu-release-upgrader-*/ folder using touch.
for example:
touch /tmp/ubuntu-release-upgrader-93aizvle/Ubuntu.info
This can be tricky since it makes a new folder every time you run do-distribution-upgrade and it can fail before you have a chance to type in the touch command for the newly created folder.  Exciting!  Took me 4 tries.  Remember to capitalize the 'U'.
I have a strong feeling adding a PopOS repo to my system is to blame.  I did it to get a non-snap version of Chromium but all hell broke loose as a result.  I tried to undo the damage but two years later I still run across some scars. I see a reference to Pop.info in many of the answers to this problem.

A: Just was surfing through internet and found the solution to this problem, and my Ubuntu 20.04 was successfully upgraded to 22.04.
The solution can be found here.
Instead of a file called "Pop.info"(as given in the answer) make a file called "Ubuntu.info"


text:
Q: Time complexity of a haskell function Consider the following code for a function isPrime.
f :: Integer -> Integer
f n = head (filter isPrime [0..n])

Assuming that isPrime k computes a boolean in O(k) time, what is the time complexity of f n?
My thought process was that filter is linear time, and we are given isPrime is also linear time, so the time complexity of f n should be O(n).
Is this correct and is there an easy way to eyeball the time complexity of code?

A: If we can assume that isPrime will return True for 2, then it takes constant time. Indeed, it will first call isPrime 0, then isPrime 1, and finally isPrime 2. All these function calls take constant time, since isPrime k runs in O(k).
If we make no assumptions what isPrime will return, then thefact that isPrime is a linear function, means that it will take O(n2) time. Indeed, we each time call isPrime k, which runs in O(k), and this thus means that it runs in O(Σn0k) and thus (n2).

Is this correct and is there an easy way to eyeball the time complexity of code?

Due to Haskell's laziness, analyzing the timecomplexity is more complicated. Especially since for example the time complexity of filter isPrime [0..n] depends on the function that uses that list (here head). head will stop at the first item of the list. Since filter is lazy, it will thus not determine the rest of the items. So the notion of time complexity of a function for lazy functions, is probably less straight forward.


text:
Q: Query Influx database I have this code to query a influx DB, but it is not working at all. Here is the python code.
import os

from influxdb import InfluxDBClient

username = u'{}'.format(os.environ['INFLUXDB_USERNAME'])
password = u'{}'.format(os.environ['INFLUXDB_PASSWORD'])

client = InfluxDBClient(host='127.0.0.1', port=8086, database='data',
                        username=username, password=password)

result = client.query("SELECT P_askbid_midprice1 FROM 'DCIX_OB' WHERE time > '2018-01-01';")

I got the following error, but it's still unclear how to fix the code above. If I query directly from influxdb with bash with SELECT P_askbid_midprice1 FROM 'DCIX_OB' WHERE time > '2018-01-01'; it worked perfectly fine.
    Press ENTER or type command to continue
    Traceback (most recent call last):
      File "graph_influxdb.py", line 11, in <module>
        result = client.query("SELECT P_askbid_midprice1 FROM 'DCIX_OB' WHERE time > '2018-01-01';")

  File "/home/ubuntu/.local/lib/python3.5/site-packages/influxdb/client.py", line 394, in query
    expected_response_code=expected_response_code
  File "/home/ubuntu/.local/lib/python3.5/site-packages/influxdb/client.py", line 271, in request
    raise InfluxDBClientError(response.content, response.status_code)
influxdb.exceptions.InfluxDBClientError: 400: {"error":"error parsing query: found DCIX_OB, expected identifier at line 1, char 31"}

How can I fix it?

A: result = client.query("SELECT P_askbid_midprice1 FROM DCIX_OB WHERE time > '2018-01-01'")
this should work

A: you might be able to use Pinform which is some kind of ORM/OSTM (Object time series mapping) for InfluxDB.
It can help with designing the schema and building normal or aggregation queries.
cli.get_fields_as_series(OHLC,
    field_aggregations={'close': [AggregationMode.MEAN]},
    tags={'symbol': 'AAPL'},
    time_range=(start_datetime, end_datetime),
    group_by_time_interval='10d')

Disclaimer: I am the author of this library


text:
Q: Teradata - Date format conversion from INT(yyyymmdd) type to date(mm/dd/yyyy) in Teradata SQL Assistant I have dates in integer format in a column. The length is 11.
Example values
current format integer (11) --> date format required

*

*yyyymmdd --> dd/mm/yyyy

*20121203 --> 03/12/2012

*20090403 --> 03/04/2009

Can someone suggest a solution keeping in mind that the change need to reflect across the entire column in the table?

A: Use STR_TO_DATE :
select STR_TO_DATE(col1, "%Y%m%d") as my_date
from test_tbl;

Result:
my_date
2012-12-03
2009-04-03

Demo
Or DATE_FORMAT as previous answer:
select DATE_FORMAT(col1, "%d/%m/%Y") as my_date
from test_tbl;

Result:
my_date
03/12/2012
03/04/2009

Demo
Maybe using both:
select DATE_FORMAT(STR_TO_DATE(col1, "%Y%m%d"),'%d/%m/%Y') as my_date
from test_tbl;

my_date
03/12/2012
03/04/2009

Demo

A: The easiest way is based on Teradata's storage of dates:
Cast(intdate - 19000000 AS DATE)

Of course this only works if there are no bad dates, as your source seems to be MySQL there might be 20220200, etc.

A: For Teradata SQL Assistant, you can use TO_CHAR and then CAST it to a DATE format like this:
SEL CAST(TO_CHAR(20211015) AS DATE FORMAT 'YYYYMMDD')

Result: 10/15/2021 (mm/dd/yyyy)

A: Docummentation: https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-format
DATE_FORMAT("20121203", "%d/%m/%Y")


text:
Q: Set PATH environment variable for my app but not to dependent Qt dlls and other dlls I create a Qt app. It uses Qt dlls and also libusb dll and openssl dlls. And I use Qt Installer Framework and with windeployqt I bundle all these dlls in the same folder as my app. So when it's extracted on the user's system it all works well as the dlls are right next to the app exe so the dlls are discovered correctly.
Now I want to add my app.exe to PATH environment variable. I can do it with the Qt Installer Framework. But the problem is that the dlls that come with my app will be now exposed to PATH too. And it does not look good. How do people normally solve the problem?
Maybe, it's bad to add/remove my app to/from PATH on installation/deinstallation? However, I've checked out that e.g. CMake's and Python's installers do modify the PATH, though it looks like they do it using Wix toolset or something like this, while I use Qt Installer Framework: JavaScript where I specify Powershell commands to get executed.


text:
Q: How to send object as POST parameters to ASP.Net web request? I'm trying to make web requests programmatically in ASP.NET, using the POST method.
I'd like to send POST parameters with the web request as well. Something like this:
LoginData obj = new LoginData();
obj.OSVersion = deviceInformation.OperatingSystem;
obj.DeviceModel = deviceInformation.FriendlyName;
string URI = "https://XXXXXXXXX.azure-mobile.net/user/logsuserin";
HttpWebRequest GETRequest = (HttpWebRequest)HttpWebRequest.Create(new Uri(URI, UriKind.RelativeOrAbsolute));
GETRequest.Method = "POST";
GETRequest.ContentType = "application/x-www-form-urlencoded";
GETRequest.Headers["applicationKey"] = "UFakeKkrayuAeVnoVAcjY54545455544";
//GETRequest.Parameters.add(obj);

Obviously, the commented line does not work. How do I achieve this?
How to get a response by sending my obj as params?
Thanks in advance,
Hemanth.

A: You need to use theGetRequestStream() method belonging to the HttpWebRequest
void Main()
{
    LoginData obj = new LoginData
    {
        Username = "foo",
        Password = "Bar"
    };

    byte[] objBytes = Encoding.UTF8.GetBytes(obj.ToString());

//    obj.OSVersion = deviceInformation.OperatingSystem;
//    obj.DeviceModel = deviceInformation.FriendlyName;
    string URI = "https://XXXXXXXXX.azure-mobile.net/user/logsuserin";
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(URI, UriKind.RelativeOrAbsolute));
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    request.Headers["applicationKey"] = "UFakeKkrayuAeVnoVAcjY54545455544";
    request.ContentLength = objBytes.Length;

    using (Stream stream = request.GetRequestStream())
    {
        stream.Write(objBytes, 0, objBytes.Length);
    }

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    using (Stream stream = response.GetResponseStream())
    using (StreamReader reader = new StreamReader(stream))
    {
        Console.WriteLine(reader.ReadToEnd());
    }

}

public class LoginData
{
    public string Username { get; set; }
    public string Password { get; set; }
    public string OSVersion { get; set; }
    public string DeviceModel { get; set; }
    public override string ToString()
    {
        var temp = this.GetType()
                       .GetProperties()
                       .Select(p => $"{p.Name}={HttpUtility.UrlEncode(p.GetValue(this).ToString())}");

        return string.Join("&", temp);
    }
}

A: If you want to use HttpClient:
using (var client = new HttpClient())
{
    var request = new HttpRequestMessage(HttpMethod.Post, "https://XXXXXXXXX.azure-mobile.net/user/logsuserin");

    request.Headers.Add("applikationKey", "UFakeKkrayuAeVnoVAcjY54545455544");
    request.Content = new FormUrlEncodedContent(new[]
    {
        new KeyValuePair<string, string>("OSVersion", deviceInformation.OperatingSystem),
        new KeyValuePair<string, string>("DeviceModel", deviceInformation.FriendlyName),
    });

    var response = client.SendAsync(request).GetAwaiter().GetResult();
}

A: You can dynamically generate a FORM with "NameValueCollection". Using "NameValueCollection" you can add number of objects to be posted as -
NameValueCollection FormFields = new NameValueCollection();
        FormFields.Add("abc", obj1);
        FormFields.Add("xyz", obj2);
     Response.Clear();
    Response.Write("");
    Response.Write(string.Format("", FormName));
    Response.Write(string.Format("<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >", FormName, Method, Url));
    for (int i = 0; i < FormFields.Keys.Count; i++)
    {
        Response.Write(string.Format("<input name=\"{0}\" type=\"hidden\" value=\"{1}\">", FormFields.Keys[i], FormFields[FormFields.Keys[i]]));
    }
    Response.Write("</form>");
    Response.Write("");
    Response.End();

OnLoad() of this form you can POST to desired URL.


text:
Q: Functions(procedure) I have many different queries (here is an example)
delete from dict.dct_task_type;
insert into dict.dct_task_type(id_task_type,nm_task_type)
SELECT * FROM dblink
        ('db',
         $$ select id_dict, nm_dict from dict.d_dict where kd_dict_entity = 30 $$)
          AS dct_task_type(id_task_type bigint,nm_task_type varchar);
delete from dict.dct_task_resolution;
insert into dict.dct_task_resolution (id_task_resolution,nm_task_resolution)
SELECT * FROM dblink
        ('db',
         $$ select id_dict, nm_dict from dict.d_dict where kd_dict_entity = 32 $$)
          AS dct_task_resolution(id_task_resolution bigint,nm_task_resolution varchar);

I want to do a job in time, for this I want to save the requests as procedures, how do I write them correctly?
DECLARE
  variable_name datatype;
BEGIN
  statements;
EXCEPTION
WHEN exception_name THEN
  statements;
END;

or
CREATE OR REPLACE FUNCTION

Write an example with my values.

A: CREATE OR REPLACE FUNCTION dict.only_dict (
)
RETURNS void AS
$body$
    BEGIN
delete from dict.dct_task_type;
insert into dict.dct_task_type(id_task_type,nm_task_type)
SELECT * FROM dblink
        ('ccrm_pp',
         $$ select id_dict, nm_dict from dict.d_dict where kd_dict_entity = 30 $$)
          AS dct_task_type(id_task_type bigint,nm_task_type varchar);
delete from dict.dct_task_resolution;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
SECURITY INVOKER
PARALLEL UNSAFE
COST 100;
ALTER FUNCTION dict.only_dict ()
  OWNER TO mb_owner;


text:
Q: NSString remove html tags, keep  How do I remove html tags from NSString, but keep any <Text in angle brackets>?
Like
123 <Hello> abc
 -> 123 <Hello> abc
I have tried all kinds of regexp, scanner and XML Parser solutions, but they remove <Text in angle brackets> as well as tags.
The only solution that fit me was to use an NSAttributedString with options
NSAttributedString *str = [[NSAttributedString alloc] initWithData:utf8Data
                                                               options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                                         NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
                                                    documentAttributes:nil
                                                                 error:nil];

NSString *result = [str string];

but this approach employs WebKit and consumes too much memory for my task.
So, how do I strip tags from NSString, keeping <Text in angle brackets> without using any kind of WebKit/UIWebView and so on?

A: I asked a similar questionma while ago, may be some of the answers can help you out.
If you do need the full HTML parser and just want to strip HTML tags out, a NSString category might be useful (this one is a modified category by mwaterfal):
- (NSString *)stringByStrippingTags {

    // Find first & and short-cut if we can
    NSUInteger ampIndex = [self rangeOfString:@"<" options:NSLiteralSearch].location;
    if (ampIndex == NSNotFound) {
        return [NSString stringWithString:self]; // return copy of string as no tags found
    }

    // Scan and find all tags
    NSScanner *scanner = [NSScanner scannerWithString:self];
    [scanner setCharactersToBeSkipped:nil];
    NSMutableSet *tags = [[NSMutableSet alloc] init];
    NSString *tag;
    do {
        // Scan up to <
        tag = nil;
        [scanner scanUpToString:@"<" intoString:NULL];
        [scanner scanUpToString:@">" intoString:&tag];

        if (tag) {
            NSString *t = [[NSString alloc] initWithFormat:@"%@>", tag];
            [tags addObject:t];
        }

    } while (![scanner isAtEnd]);
    NSMutableString *result = [[NSMutableString alloc] initWithString:self];
    NSString *finalString;

    NSString *replacement;
    for (NSString *t in tags) {
        replacement = @" ";
        if ([t isEqualToString:@""] ||
            [t isEqualToString:@""] ||
            [t isEqualToString:@""] ||
            [t isEqualToString:@""] ||
            [t isEqualToString:@""] ||
            [t isEqualToString:@""] ||
            [t isEqualToString:@""] ||
            [t isEqualToString:@""]) {
            replacement = @"";
        }
        [result replaceOccurrencesOfString:t
                            withString:replacement
                               options:NSLiteralSearch
                                 range:NSMakeRange(0, result.length)];
    }

    // Remove multi-spaces and line breaks
    return = [result stringByRemovingNewLinesAndWhitespace];
}


text:
Q: How can I display a rectangle that overlaps everything in a panel control? I want to display a rectangle drawing over EVERYTHING inside of a panel control. I only have a WebBrowser in the panel control as of now. If I start run the program WITHOUT adding the WebBrowser to the panel control, then I will be able to see the rectangle. But, if I add the WebBrowser to the panel control, then it will overlap my rectangle drawing.
How can I create a rectangle drawing INSIDE of a panel control, that will overlap everything? (always on top)
The code below will draw a blue rectangle inside of the panel control. But it will not be shown, because the panel contains a WebBrowser.
using System;
using System.Drawing;
using System.Windows.Forms;

namespace Graphics_Overlay
{
    public partial class GraphicsOverlayForm : Form
    {
        public GraphicsOverlayForm()
        {
            InitializeComponent();

            Panel panel = new Panel();
            panel.Dock = DockStyle.Fill;
            panel.Paint += panel_Paint;

            WebBrowser webBrowser = new WebBrowser();
            webBrowser.Dock = DockStyle.Fill;
            webBrowser.Url = new Uri("http://stackoverflow.com/");

            Controls.Add(panel);

            // If I comment out the line below then I will
            // be able to see my blue rectangle.
            panel.Controls.Add(webBrowser);
        }

        private void panel_Paint(object sender, PaintEventArgs e)
        {
            ShowLineJoin(e);
        }

        private void ShowLineJoin(PaintEventArgs e)
        {
            // Create a new pen.
            Pen skyBluePen = new Pen(Brushes.Blue);

            // Set the pen's width.
            skyBluePen.Width = 1;

            // Set the LineJoin property.
            skyBluePen.LineJoin = System.Drawing.Drawing2D.LineJoin.Bevel;

            // Draw a rectangle.
            e.Graphics.DrawRectangle(skyBluePen,
                new Rectangle(0, 0, 200, 200));

            //Dispose of the pen.
            skyBluePen.Dispose();
        }
    }
}

A: This is not possible. If you add the WebBrowser as a child control of the panel, it will be displayed on top of the Panel's background area. The Panel's background area is, of course, where you are drawing the blue rectangle. Your drawing is still there, the WebBrowser control is just being displayed on top of it.
There are three possible solutions that come to mind, listed here in no particular order:

*

*Set the Visible property of the WebBrowser control to false whenever you want the blue rectangle (or whatever is drawn on the background of the Panel control to be visible). Set WebBrowser.Visible to true again so that the WebBrowser control can be used.

*Rather than adding the WebBrowser control as a child control of the Panel, which is in turn a child control of the container form, add both the Panel and WebBrowser control as children of your container form. In other words, flatten the hierarchy. Because this removes the parent-child relationship, you can now alter the Z order of the controls, changing which one is visible. This is trivial in WinForms using the SendToBack and BringToFront member functions.

*Create a new control, named something like BlueRectangle or DrawingSurface or whatever, that inherits from System.Windows.Forms.Control. Override its OnPaint event and put your drawing code there. Add an instance of this control class to your Panel control, as a child. Effectively, then, your Panel control will have two children: a BlueRectangle control and a WebBrowser control. Shuffle back and forth between the two by changing the Z order, as described above, with SendToBack and BringToFront.
On an unrelated note, you should prefer the using statement as a way of ensuring that an object implementing IDisposable is automatically disposed, rather than explicitly calling the Dispose method. For example, write your ShowLineJoin method like this:
private void ShowLineJoin(PaintEventArgs e)
{
    // Create a new pen with the specified color and width.
    using (Pen skyBluePen = new Pen(Brushes.Blue, 1))
    {
        // Set the LineJoin property.
        skyBluePen.LineJoin = System.Drawing.Drawing2D.LineJoin.Bevel;

        // Draw a rectangle.
        e.Graphics.DrawRectangle(skyBluePen,
        new Rectangle(0, 0, 200, 200));
    }
}

Simpler, easier to read, and safer.


text:
Q: Java. How do I override initial arguments? I am in a pickle with a java application. When It launches it uses -Xmx 256m and Xss 2m. I need to make it use more ram because it keeps crashing when running out of ram. So I use java -jar application.jar -Xmx 4G.
Nothing happens, it still uses the built in -Xmx 256m
How do I override the initial settings to give this application more ram?

A: First, use uppercase X as -Xmx and -Xss; -x is an error.
Second, put all JVM options, including -X and -D and so on, BEFORE -jar jarname if you use that, or otherwise before the main-class name. Any arguments after the run-jar or main-class are passed to the Java program, not interpreted by the JVM.
PS: I assume/hope you have 64-bit java (and hardware) if you want 4G.


text:
Q: How to match character inside inline style? I want to match one letter or number or symbol inside inline style.
Example:

hi there

perfect

I want to match any c or o or # or 4 or ; or -
If we take o for example, it's supposed to match 5 occurrences.
I want to replace every occurrence within a style declaration using preg_replace().
How can I get this?  I tried so many different expressions, but none of them did what I want.
Some of what I tried:

*

*/(?:\G(?!^)|\bstyle=")(?:.{0,}?)(o)(?=[^>]*>)/

*/(style=")(?:\w+)(o)(([^"]*)")/
I just need the regex to match all o in my HTML. I expect this:

how blabla

perfect normal o moral bla bal

I just want all o occurrences inside inline-style above to be replaced with 'o'

A: A quick/dirty/simple solution is to use preg_replace_callback() with str_replace().
Pattern: (Demo with Pattern Explanation) /<[^<]+ style="\K.*?(?=">)/
Code: (Demo)
$html='

hi there

perfect

';

$needle="o";
echo preg_replace_callback('/<[^<]+ style="\K.*?(?=">)/',function($m)use($needle){return str_replace($needle,"$needle",$m[0]);},$html);
//   add the i flag for case-insensitive matching------^                                     ^-- and add i here for case-insensitive replacing

Output:

        <p style="color: #48ad64;font-weight:10px;">hi there

        <div style="background-color: #48ad64;">

perfect

This is a pure regex replacement method/pattern:
$needle="o";
//                                               vv-----------vv--make the needle value literal
echo preg_replace('/(?:\G(?!^)|\bstyle=")[^"]*?\K\Q'.$needle.'\E/',"'$needle'",$html);
//        assumes no escaped " in style--^^^^  ^^-restart fullstring match

The [^"]*? component eliminates the need for a lookahead.  However, if a font family name (or similar) were to use \" (escaped double quotes) then replacement accuracy would be negatively impacted.
I wouldn't call either of these methods "robust" because certain substrings of text may trick the pattern into "over-matching" illegitimate style substrings.
To do this properly, I suggest that you use DomDocument or some other html parser to ensure you are only modifying real/true style attributes.
DomDocument Code: (Demo)
$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); // 2nd params to remove DOCTYPE
$xp = new DOMXpath($dom);
foreach ($xp->query('//*[@style]') as $node) {
    $node->setAttribute('style',str_replace($needle,"'$needle'",$node->getAttribute('style'))); // no regex
}
echo $dom->saveHTML();


text:
Q: AWS ECS Task is stuck at PROVISIONING I have an ECS Cluster with a capacity provider and a service. The capacity provider runs an autoscale group, and when one instance of this group starts, at the end I can see that there are ECS instances avalaible. Actually, I can connect to them through SSH.
The service also runs well, since it creates a new task which is based on a docker image at ERS repository. However, the task never pass from "PROVISIONING", and if I open the task I can see that the container of the task is void and loading. If I enter into my instance, I see the same docker instance if I do docker ps or docker ps -a. If I execute the agent docker exec id_docker /agent I see:
level=info time=2022-05-02T21:16:05Z msg="Successfully got ECS instance credentials from provider: EC2RoleProvider" module=instancecreds.go
level=info time=2022-05-02T21:16:05Z msg="Starting Amazon ECS Agent" version="1.61.0" commit="05730614"
level=info time=2022-05-02T21:16:05Z msg="Loading configuration"
level=info time=2022-05-02T21:16:05Z msg="Successfully got ECS instance credentials from provider: EC2RoleProvider" module=instancecreds.go

If I try with docker exec id_docker bash I get an error:
OCI runtime exec failed: exec failed: container_linux.go:380: starting container process caused: exec: "bash": executable file not found in $PATH: unknown

What's happening here? Any clue?

A: What I had after doing docker ps wsa in fact ecs-agent, which is something Amazon creates to control the container. That was the stucked part. My docker wasn't even running in fact.
To solve it, when you create the task, in the container options, when you select the ports of the container to redirect to the host, put in your host values a 0. E.g, redirect port 22 to 22 -> 0 to 22. This is a dynamic port mapping in ecs.


text:
Q: "hidden parent" for a git commit? I'd like to attach a branch to a git commit in a way that it does not show up the usual tools (e.g. in git log), but it is contained in the git repository and will be as long as the commit itself is, and moves to other repositories together with that commit.
Something like a parent of a commit, but ignored by most tools.
My use case is: I work on a feature branch that I regularly rebase to produce nice clean self-contained test-suit-passing patches; eventually I am going to push this cleaned branch to master. But I'd also like to attach something like the branch's reflog to it, so I can still obtain the history of the branch, if I later remember that some intermediate state has something worth looking at.
Is that possible somehow?


text:
Q: Python: "inner join" array of dictionaries I'm currently using this code to compare and make a new array when the value of the key 'time' is the same for both list1 and list2:
def innerJoin(self, list1, list2):

    mergedList = []
    for i in range(len(list1)):
        for j in range(len(list2)):
            if (list1[i]['time']==list2[j]['time']):
                mergedList.append(list2[j])

    return mergedList

But when both list has, for exemple, more than 6000 items each, it's taking too long to process. There is a way to make it faster?
Can I use Numpy to improve the speed in this case?
EDIT
An exemple:
list1 =[{
      'time': '2017-07-03T01:12:13Z',
      'tag': 'TEMP',
      'value': 34.5
    },{
      'time': '2017-07-03T01:12:17Z',
      'tag': 'TEMP',
      'value': 34
    }]

list2 =[{
      'time': '2017-07-03T01:12:13Z',
      'tag': 'VOLUME',
      'value': 3
    }]

It should return:
mergedList =[{
          'time': '2017-07-03T01:12:13Z',
          'tag': 'VOLUME',
          'value': 3
        }]

I don't need the 'tag' and 'code', so if returns like this will be fine:
mergedList =[{
          'time': '2017-07-03T01:12:13Z'
        }]

A: You could try something along these lines:
def innerJoin(list1, list2):
    set1 = set(l['time'] for l in list1)
    return [l for l in list2 if l['time'] in set1]

Or you could use filter:
    ...
    return filter(lambda i: i['time'] in set1, list2)

A: You can use this. It is MUCH faster:
def innerJoin(list1, list2):
    mergedList = []
    # Of course you can skip the sorting if you know that they are sorted
    # but it is much faster even if you sort first
    l1 = sorted(list1, key=lambda s:s['time'])
    l2 = sorted(list2, key=lambda s:s['time'])

    i1=0
    i2=0

    while(i1 < len(l1) and i2 < len(l2)):

        if (l1[i1]['time']==l2[i2]['time']):
                mergedList.append(l2[i2])
                i1=i1+1
                i2=i2+1

        else:
            if (l1[i1]['time']<l2[i2]['time']):
                i1=i1+1
            else:
                i2=i2+1
    return mergedList

Your algorithm is O(n²), while my algorithm is O(n). The sorting is probably O(n*log n). The solution from knipknap is in general better to use, but I'll think this answer gives a good insight in how wise chosen algorithms can affect performance.
I tried this with n=3,000,000. When I had to sort the list, it took 10 seconds, and if I presorted it it took 3.2s.
I want to point out that your code may have a bug, depending if you want to consider it a bug or not. If there is a doublet in one of the lists, you will get doublets in the list you return. I don't know if you have a thought behind this, but that's how it is. It took me about en hour to realize that it was nothing wrong with my code. :)
If you want to use my code and DO want that feature, you'll have to modify it.


text:
Q: Why tikzmark doesn't work with beamer class? Consider the following MCE that makes use of:

*

*tikzmark library and its listings library that let us add marks to lstlisting environments,

*the high level \balloon macro (provided by the tikzmark's author in https://tex.stackexchange.com/a/86457/18401) that puts a fancy node behind certain lines of the code (it is here a bit modified in order to avoid overlapping of the line preceding the first one wanted, see Jellby's comment on Mar 9 '14 at 18:26 in https://tex.stackexchange.com/a/79787/18401).

The point is, this code works nicely with e.g. the article class but not with the beamer one: with the latter, the node isn't displayed.
% \documentclass{beamer}
\documentclass{article}\usepackage{beamerarticle}
%
\usepackage{listings}
\usepackage{tikz}
\usetikzlibrary{tikzmark,fit,calc}
\usetikzmarklibrary{listings}
\lstset{basicstyle=\ttfamily}
\tikzset{
  balloon/.style={
    draw,
    fill=blue!20,
    opacity=0.4,
    inner sep=4pt,
    rounded corners=2pt
  },
}
%
\newcommand{\balloon}[4]{%
  \pgfmathtruncatemacro\firstline{%
    #3-1%
  }%
  \iftikzmark{line-#2-\firstline-start}{%
    \iftikzmark{line-#2-#3-first}{%
      \xdef\blines{($ ({pic cs:line-#2-\firstline-start} -| {pic
          cs:line-#2-#3-first})!.5!({pic cs:line-#2-#3-first}) $)}%
    }{%
      \iftikzmark{line-#2-#3-start}{%
        \xdef\blines{({pic cs:line-#2-\firstline-start} -| {pic
            cs:line-#2-#3-start})}%
      }{%
        \xdef\blines{(pic cs:line-#2-\firstline-start)}%
      }%
    }%
  }{%
    \xdef\blines{}%
  }%
  \foreach \k in {#3,...,#4} {%
    \iftikzmark{line-#2-\k-first}{%
      \xdef\blines{\blines (pic cs:line-#2-\k-first) }%
    }{} \iftikzmark{line-#2-\k-end}{%
      \xdef\blines{\blines (pic cs:line-#2-\k-end) }%
    }{}%
  }%
  \ifx\blines\empty
  \else
  \edef\temp{\noexpand\tikz[remember picture,overlay]
    \noexpand\node[fit={\blines},balloon] (#1) {};}%
  \temp
  \fi
}
%
\begin{document}
\begin{frame}[fragile]
  \balloon{comment}{code}{3}{4}
\begin{lstlisting}[name=code]
Foo Bar Baz
Foo Baz Bar
Bar Foo Baz
Bar Baz Foo
Baz Foo Bar
Baz Bar Foo
\end{lstlisting}
\end{frame}
\end{document}

Results
With article (and beamerarticle)

With beamer

A: beamer redefines \pgfmark and adds a number for the slide to the internal name to make if overlay aware. If you look at the aux you can see that you get names like line-code-6-start-1 instead of line-code-6-start. This means that all your \iftikzmark fails.
\documentclass{beamer}
%\documentclass{article}\usepackage{beamerarticle}
%
\usepackage{listings}
\usepackage{tikz}
\usetikzlibrary{tikzmark,fit,calc}
\usetikzmarklibrary{listings}
\lstset{basicstyle=\ttfamily}
\tikzset{
  balloon/.style={
    draw,
    fill=blue!20,
    opacity=0.4,
    inner sep=4pt,
    rounded corners=2pt
  },
}

\makeatletter

%
\newcommand{\balloon}[4]{%
  \pgfmathtruncatemacro\firstline{%
    #3-1%
  }%
  \iftikzmark{line-#2-\firstline-start-\the \beamer@slideinframe}{%
    \iftikzmark{line-#2-#3-first-\the \beamer@slideinframe}{%
      \xdef\blines{($ ({pic cs:line-#2-\firstline-start} -| {pic
          cs:line-#2-#3-first})!.5!({pic cs:line-#2-#3-first}) $)}%
    }{%
      \iftikzmark{line-#2-#3-start-\the \beamer@slideinframe}{%
        \xdef\blines{({pic cs:line-#2-\firstline-start} -| {pic
            cs:line-#2-#3-start})}%
      }{%
        \xdef\blines{(pic cs:line-#2-\firstline-start)}%
      }%
    }%
  }{%
    \xdef\blines{}%
  }%
  \foreach \k in {#3,...,#4} {%
    \iftikzmark{line-#2-\k-first-\the \beamer@slideinframe}{%
      \xdef\blines{\blines (pic cs:line-#2-\k-first) }%
    }{} \iftikzmark{line-#2-\k-end-\the \beamer@slideinframe}{%
      \xdef\blines{\blines (pic cs:line-#2-\k-end) }%
    }{}%
  }%
  \ifx\blines\empty
  \else
  \edef\temp{\noexpand\tikz[remember picture,overlay]
    \noexpand\node[fit={\blines},balloon] (#1) {};}%
  \temp
  \fi
}
%
\begin{document}

\begin{frame}[fragile]
\balloon{comment}{code}{3}{4}

\begin{lstlisting}[name=code]
Foo Bar Baz
Foo Baz Bar
Bar Foo Baz
Bar Baz Foo
Baz Foo Bar
Baz Bar Foo
\end{lstlisting}
\end{frame}
\end{document}

Addition
An alternative to the redefinition of \ballon is a redefinition of \iftikzmark:
\makeatletter
\renewcommand\iftikzmark[3]{%
    \@ifundefined{save@pt@#1-\the\beamer@slideinframe}{%
      #3%
    }{%
      #2%
    }%
  }%

A: It looks like this problem has been fixed upstream by https://github.com/loopspace/tikzmark/commit/1427ccaa0be7932d964d3f51b26b5a4d3444e1af or https://github.com/loopspace/tikzmark/commit/00141c09c0b53c14459c206dc23ea6ea90f96b0b
So if you use the work-around presented above on a recent TeXlive distribution (I have tried on Ubuntu 19.04 & 19.10 and Debian/unstable) it does not work...
You need now to go back to the first example of this page.


text:
Q: Read multiple CSV files into separate data frames Suppose we have files file1.csv, file2.csv, ... , and file100.csv in directory C:\R\Data and we want to read them all into separate data frames (e.g. file1, file2, ... , and file100).
The reason for this is that, despite having similar names they have different file structures, so it is not that useful to have them in a list.
I could use lapply but that returns a single list containing 100 data frames.  Instead I want these data frames in the Global Environment.
How do I read multiple files directly into the global environment? Or, alternatively, How do I unpack the contents of a list of data frames into it?

A: Here is a way to unpack a list of data.frames using just lapply
filenames <- list.files(path="../Data/original_data",
                        pattern="xyz+.*csv")

filelist <- lappy(filenames, read.csv)

#if necessary, assign names to data.frames
names(filelist) <- c("one","two","three")

#note the invisible function keeps lapply from spitting out the data.frames to the console

invisible(lapply(names(filelist), function(x) assign(x,filelist[[x]],envir=.GlobalEnv)))

A: Reading all the CSV files from a folder and creating vactors same as the file names:
setwd("your path to folder where CSVs are")

filenames <- gsub("\\.csv$","", list.files(pattern="\\.csv$"))

for(i in filenames){
  assign(i, read.csv(paste(i, ".csv", sep="")))
}

A: Thank you all for replying.
For completeness here is my final answer for loading any number of (tab) delimited files, in this case with 6 columns of data each where column 1 is characters, 2 is factor, and remainder numeric:
##Read files named xyz1111.csv, xyz2222.csv, etc.
filenames <- list.files(path="../Data/original_data",
    pattern="xyz+.*csv")

##Create list of data frame names without the ".csv" part
names <-substr(filenames,1,7)

###Load all files
for(i in names){
    filepath <- file.path("../Data/original_data/",paste(i,".csv",sep=""))
    assign(i, read.delim(filepath,
    colClasses=c("character","factor",rep("numeric",4)),
    sep = "\t"))
}

A: Quick draft, untested:

*

*Use list.files() aka dir() to dynamically generate your list of files.

*This returns a vector, just run along the vector in a for loop.

*Read the i-th file, then use assign() to place the content into a new variable file_i
That should do the trick for you.

A: A simple way to access the elements of a list from the global environment is to attach the list.  Note that this actually creates a new environment on the search path and copies the elements of your list into it, so you may want to remove the original list after attaching to prevent having two potentially different copies floating around.

A: Use assign with a character variable containing the desired name of your data frame.
for(i in 1:100)
{
   oname = paste("file", i, sep="")
   assign(oname, read.csv(paste(oname, ".txt", sep="")))
}

A: This answer is intended as a more useful complement to Hadley's answer.
While the OP specifically wanted each file read into their R workspace as a separate object, many other people naively landing on this question may think that that's what they want to do, when in fact they'd be better off reading the files into a single list of data frames.
So for the record, here's how you might do that.
#If the path is different than your working directory
# you'll need to set full.names = TRUE to get the full
# paths.
my_files <- list.files("path/to/files")

#Further arguments to read.csv can be passed in ...
all_csv <- lapply(my_files,read.csv,...)

#Set the name of each list element to its
# respective file name. Note full.names = FALSE to
# get only the file names, not the full path.
names(all_csv) <- gsub(".csv","",
                       list.files("path/to/files",full.names = FALSE),
                       fixed = TRUE)

Now any of the files can be referred to by my_files[["filename"]], which really isn't much worse that just having separate filename variables in your workspace, and often it is much more convenient.

A: I want to update the answer given by Joran:
#If the path is different than your working directory
# you'll need to set full.names = TRUE to get the full
# paths.
my_files <- list.files(path="set your directory here", full.names=TRUE)
#full.names=TRUE is important to be added here

#Further arguments to read.csv can be passed in ...
all_csv <- lapply(my_files, read.csv)

#Set the name of each list element to its
# respective file name. Note full.names = FALSE to
# get only the file names, not the full path.
names(all_csv) <- gsub(".csv","",list.files("copy and paste your directory here",full.names = FALSE),fixed = TRUE)

#Now you can create a dataset based on each filename
df <- as.data.frame(all_csv$nameofyourfilename)

A: a simplified version, assuming your csv files are in the working directory:
listcsv <- list.files(pattern= "*.csv") #creates list from csv files
names <- substr(listcsv,1,nchar(listcsv)-4) #creates list of file names, no .csv
for (k in 1:length(listcsv)){
  assign(names[[k]] , read.csv(listcsv[k]))
}
#cycles through the names and assigns each relevant dataframe using read.csv

A: #copy all the files you want to read in R in your working directory
a <- dir()
#using lapply to remove the".csv" from the filename
for(i in a){
list1 <- lapply(a, function(x) gsub(".csv","",x))
}
#Final step
for(i in list1){
filepath <- file.path("../Data/original_data/..",paste(i,".csv",sep=""))
assign(i, read.csv(filepath))
}

A: Use list.files and  map_dfr to read many csv files
df <- list.files(data_folder, full.names = TRUE) %>%
    map_dfr(read_csv)

Reproducible example
First write sample csv files to a temporary directory.
It's more complicated than I thought it would be.
library(dplyr)
library(purrr)
library(purrrlyr)
library(readr)
data_folder <- file.path(tempdir(), "iris")
dir.create(data_folder)
iris %>%
    # Keep the Species column in the output
    # Create a new column that will be used as the grouping variable
    mutate(species_group = Species) %>%
    group_by(species_group) %>%
    nest() %>%
    by_row(~write.csv(.$data,
                      file = file.path(data_folder, paste0(.$species_group, ".csv")),
                      row.names = FALSE))

Read these csv files into one data frame.
Note the Species column has to be present in the csv files, otherwise we would loose that information.
iris_csv <- list.files(data_folder, full.names = TRUE) %>%
    map_dfr(read_csv)


text:
Q: Standard error of linear regression fit I have a naive question about regression. How does R function predict.lm compute the 95% confidence interval of the fitted line? In particular why is this not a straight line?
 x <- rnorm(10,0,10)
 y <- 20*x + rnorm(10,0,2)
 fit <- lm(y ~ x)
 newx <- sort(x)
 prd <- predict(fit,newdata=data.frame(x=newx),interval = c("confidence"),level = 0.95,type="response")

 # plot
 plot(x,y)
 abline(fit)
 lines(newx,prd[,2],col="red",lty=2)
 lines(newx,prd[,3],col="red",lty=2)

Can somebody help me understand how the upper and lower bounds of 95% CI of the fitted line are computed by predict?


text:
Q: Moving UIImages Back and Forth I don't know if I am doing this correctly. Please help me. I am trying to move the two images back and forth on the screen to make it look like it's closing and opening.
while (x>=1) {

    var customFrame1 = Laser1.frame
    if isImageLeftSide {
        customFrame1.origin.x = customFrame1.origin.x + 25
    }
    else {
        customFrame1.origin.x = customFrame1.origin.x - 25
    }

    var customFrame2 = Laser2.frame
    if isImageLeftSide {
        customFrame2.origin.x = customFrame2.origin.x + 25
    }
    else {
        customFrame2.origin.x = customFrame2.origin.x - 25
    }
        x += 1
    }

A: Use this:
while (x >= 1) {

    UIView.animateWithDuration(YOUR_ANIMATION_DURATION) {

        if isImageLeftSide {
            Laser1.frame.origin.x += 25
        } else {
            Laser1.frame.origin.x -= 25
        }
    }

    UIView.animateWithDuration(YOUR_ANIMATION_DURATION) {

        if isImageLeftSide {
            Laser2.frame.origin.x += 25
        } else {
            Laser2.frame.origin.x -= 25
        }
    }

    x += 1
}

Note: if Laser1 and Laser2 are properties of the class you'll have to use self.Laser1 and self.Laser2 in the animation blocks.


text:
Q: Filter your questions and answers
Possible Duplicate:
Ability to search my stuff?

Sometimes I want to go back to an answer I got from a question or check an answer I answered, say, last year but I wouldn't be able to find it...because you have to go through 9 pages or so of your questions and answers.
I think that it would very useful if some sort of Filter was implemented (like in the Users Page) that would be used to help you traverse your questions and answers easily and find what you are looking for.

A: If you want to search your own answers on Stack Overflow, you can use AskJonSkeet - it doesn't just index my answers. The URL format is
http://www.askjonskeet.com/user/[userid]/[username]/search/

e.g.
http://www.askjonskeet.com/user/1288/bill-the-lizard/search/

Of course it would be nice to have something like this built into the SE engine - apart from anything else, I believe AskJonSkeet only indexes SO, not the other sites - but you may find it a helpful workaround for the moment.