text:
Q: Allowed memory size error in Tbs library Hello i am facing the problem of Allowed memory size error. I have created the project in codeigniter, php and I have used Tbs library. Its worked fine but today it display the error:

Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 258010 bytes) in
  /home/abc/public_html/application/libraries/Tbs.php on line
  4222

Please give me any suggestions.

A: "Allowed memory size of XXXXXX bytes exhausted" is a typical error when you don't have, as it's own name says, enough memory available for the php query to run.
Try upgrading memory_limit variable on your php.ini file, or by setting up ini_set('memory_limit', 'XXXM'); on your PHP file that you are running, being XXX the amount of Mb memory that you want to define.
If this isn't the case, you might have a bug in your software that is causing, i.e. a loop that is consuming memory without any control; but as you have said that it did work before...
Anyway, please check all the other answers from StackOverflow on this aspect:
Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)
CodeIgniter Fatal error: Allowed memory size of bytes exhausted
Codeigniter - Allowed memory size exhausted while uploading

A: If you are using TBS + OpenTBS in order to merge an XLSX file , then there is a known problem fixed with OpenTBS version 1.9.2 : if the number of row to merge is quite numerous, then you can have a very long process or a memory size error when calling $TBS->Show().
Use OpenTBS 1.9.2 or higher which is optimized for this point, and if the process is still long you can optimize more using the OPENTBS_RELATIVE_CELLS command.

A: Generally this type of occurs when your script is using too much memory. This can often happen in PHP if you have a loop that has run out of control and you are creating objects or adding to arrays on each pass of the loop. Check for infinite loops.
If that isn't the problem, try and help out PHP by destroying objects that you are finished with by setting them to null eg. $OldVar = null;.
Check the code where the error actually happens as well. Would you expect that line to be allocating a massive amount of memory? If not, try and figure out what has gone wrong.
Never upgrad memory_limit variable on your php.ini file, or by setting up ini_set('memory_limit', 'XXXM'); on your PHP file that you are running, being XXX the amount of Mb memory that you want to define.Letting application to eat memory he wants to is insane step.Try to find out bug does your application wants that much memory?? Find out


text:
Q: Using a custom query to get data I've been thinking of creating my own custom query to get data using $wpdb. But there are just some things I don't quite understand:

*

*When the results come in, how will it know which template file to use to display those results?

*What do I type in the link's href attribute which will activate the query?

*Should there be many results, will pagination be enabled like a normal loop?

*Do I put my query in a file (in #1) or in functions.php?

A: If you want to create new custom loop, you can create new template for it. In this case pagination, loop work normally. You just place custom wp_query above loop. And in href you must write url of page which built on new custom template. For understanding all this process step by step i suggest you to read my article in wptuts. It is called "Creating a Custom 'The Posts I Commented On' Loop" and it is the guide what you need.

redpajama_set_name: RedPajamaStackExchange


text:
Q: parameter in my Rule in fluentvalidation I want to have range validation in my class that value of my range defined in my class
public class FieldViewModel
    {
        public string FieldName { get; set; }
        public string FieldValue { get; set; }
        public string MinRange { get; set; }
        public string MaxRange { get; set; }
        public List<int> Validations { get; set; }

    }

how to get value of MinRange and MaxRange of my class to pass to
InclusiveBetween(MinRange ,MaxRange )
public class FieldModelValidator : AbstractValidator<FieldViewModel> {

//!!!--MinRange and MaxRange  not recognized in InclusiveBetween
 RuleFor(x => x.FieldValue ) .InclusiveBetween(MinRange ,MaxRange ) .When(w => w.Validations.Any(x => x.Validations.Contain(2) ))

}

A: See this article:
public class Validator
   {
       public AndClass IsNumber(int val)
       {
           int n;
           bool isNumeric = int.TryParse(val.ToString(), out n);
           if (isNumeric)
               return new AndClass( Convert.ToInt32(val));
           throw new Exception(";The value should be number";);
       }
   }

A: I found a way for my issue.
In fact i need other property of current object.
We can have it in one of the overloads of Must method:
public class FieldModelValidator : AbstractValidator<FieldViewModel> {
{
    public FieldModelValidator()
    {
        RuleFor(x => x.FieldValue).Must(RangeValidation).When(w => w.Validations.Any(x => x.Validations.Contain(2)))
    }

    private bool RangeValidation(FieldViewModel field, String value)
    {
        int val = int.Parse(value);

        if (val >= field.MinRange && val <= field.MaxRange)
        {
            return true;
        }

        return false;
    }
}

More Info


text:
Q: How can make a div vertically center to parent div This is MY demo Work in JSFIDDLE
NB without using table property
http://jsfiddle.net/SxxWV/12/
I want to make the class .box should be vertically centered
CSS
.main{ height:300px; border:1px red solid;position:relative}
.box{width:40px; height:40px; background:red; }

/* for centering */
.box{ display: inline-block;position:relative; top:50% }
.main{ text-align: center; }

HTML

A: You need to subtract half of the height of the element you want to center, so in this case add the following to .box:
margin-top: -20px;

A: I will Prefer to use CSS after
This line of CSS will work fine
.main:after{ content: ""; display: inline-block;
height: 100%; vertical-align: middle; }

Here id the Demo Work

A: You can set the box to position: absolute and then set the top and bottom to 0, and then set the margin to auto:
.box {
   position: absolute;
   top: 0;
   bottom: 0;
   margin: auto;
}

Here's an example:
http://jsfiddle.net/SxxWV/23/

A: You can try this :
Fiddle here
.main{ height:300px; border:1px red solid;position:relative}
.box{width:40px; height:40px; background:red; }

/* for centering */
.box{ display: inline-block;position:relative; top:50%; margin-top:-20px; }
.main{ text-align: center; }

Good Luck


text:
Q: How to correctly switch between two UIViews by using segment control ios? I am trying to switch between two UIViews using segmentControl.Now both of these UIViews have embedded scrollView of their own.These UIViews are supposed to appear as one , so I have placed them on top of each other (in XIB) .And when segmentControl is clicked I am trying to hide / show them accordingly.  But so far I am unable to switch between the two.Also tried solution suggested below .However it only works in random cells and fails to switch in all cells.What is missing ?
This is how I set the upper view hidden in didSelectRow where I am expanding the tableViewCell .
 -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

if ([self.expandedCells containsObject:indexPath]) {

    expCell.upperContainer.hidden = NO;
    expCell.upperScroll.hidden = NO;
    [self.expandedCells removeObject:indexPath];

     }else{
    isExpanded=YES;
    [self.expandedCells addObject:indexPath];

    //hide upper container

    if (!expCell.upperContainer.hidden) {

        expCell.upperContainer.hidden = YES;

    }
    if (!expCell.upperScroll.hidden) {

        expCell.upperScroll.hidden =YES;
    }

   }

  [self.bTableView beginUpdates];
  [self.bTableView reloadData];
  [self.bTableView endUpdates];
 }

And in expandedCell on segmentControl click I am doing the following.
-(void)selectDeckView:(UISegmentedControl*)sender{

if (sender.selectedSegmentIndex==0) {
     NSLog(@"segment 0");             //executes
     expCell.lowerDeckView.hidden=NO;
     expCell.lowerScrollView.hidden=NO;
     expCell.upperScroll.hidden=YES;
     expCell.upperContainer.hidden=YES;

}else if (sender.selectedSegmentIndex==1){
    NSLog(@"segment 1");                //executes
    expCell.lowerDeckView.hidden=YES;
    expCell.lowerScrollView.hidden=YES;
    expCell.upperContainer.hidden=NO;
    expCell.upperScroll.hidden=NO;

}

}

A: I would recommend having each view in its own view controller, then add the appropriate child view controller whenever a segment is pressed.
Your view controller that contains the segmented control would be the container view controller, and it would have a method like this that adds one of your two content view controllers (with each containing one of the views you mentioned), which gets invoked when a segment is pressed:
- (void) displayContentController: (UIViewController*) content;
{
   [self addChildViewController:content];                 // 1
   content.view.frame = [self frameForContentController]; // 2
   [self.view addSubview:self.currentClientView];
   [content didMoveToParentViewController:self];          // 3
}

You could cache your child view controller instances so that they only get created once, if that is appropriate, meaning it will be fast.  Apple's documentation on content/child view controllers:
https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/CreatingCustomContainerViewControllers/CreatingCustomContainerViewControllers.html

A: you might have a view that covers the other,have you tried:
if (sender.selectedSegmentIndex==0) {
     NSLog(@"segment 0");             //executes
     expCell.lowerDeckView.hidden=NO;
     expCell.lowerScrollView.hidden=NO;
     expCell.upperScroll.hidden=YES;
     expCell.upperContainer.hidden=YES;
     [self.view bringSubviewToFront:expCell.upperScroll]
     [self.view bringSubviewToFront:expCell.upperContainer]

}else if (sender.selectedSegmentIndex==1){
    NSLog(@"segment 1");                //executes
    expCell.lowerDeckView.hidden=YES;
    expCell.lowerScrollView.hidden=YES;
    expCell.upperContainer.hidden=NO;
    expCell.upperScroll.hidden=NO;
    [self.view bringSubviewToFront:expCell.lowerScrollView]
    [self.view bringSubviewToFront:expCell.lowerDeckView]

}

}

make sure that you bring them to the front in the correct order.


text:
Q: SQLPlus : default define settings My workstation is Ubuntu 14.04. I have Oracle Express 11g installed. Whenever i run the define command in SQLPlus, is see the define _editor = "ed". Is there a way to change that permanently to gedit instead of defining my preferred editor with every new session.

A: You should be able to do this using the either glogin.sql or login.sql. The former is run whenever anyone logs into SQL*Plus and the latter is specific to a user. Im not currently in a position to install it myself to try out but this link to the Oracle docs should help.
Configuring SQL*Plus

A: There are 2 ways of doing this.
Edit your shell dot file (.profile, .bash_profile etc) to add:
export EDITOR=gedit

Or, you can create the sqlplus equivalent of a Unix dot file. Create a file called glogin.sql and place it in $ORACLE_HOME/sqlplus/admin, then add this to it:
DEFINE _EDITOR=gedit


text:
Q: Watir-Webdriver - how to differentiate the buttons if there are more than one with same properties This query is based on the my previous question here Watir-Webdriver - Unable to locate a button with id, name, text, value and i got some details on how to fetch the fields through elements. But now in one of my screen i have two buttons with same class and div. So i am not able to take the one which i need. I need to get the button which has "Checking and Savings" product. Could someone help on how to get the exact button click? And my web application is developed on AnjularJS.
Here's a full div portion of the HTML from the page where the button is identified.

Checking and Savings

            <button type="button" tabindex="0" ng-click="ctrl.submitProductSelection(entry)" class="extra-button-padding secondary jl-button">
                <ng-transclude>
                    Select
                </ng-transclude>
            </button>

Savings

            <button type="button" tabindex="0" ng-click="ctrl.submitProductSelection(entry)" class="extra-button-padding secondary jl-button">
                <ng-transclude>
                    Select
                </ng-transclude>
            </button>

A: When there are no unique properties on the element you want to interact with, you will have to look at the elements around it. In this case, it is the h3 element text that differentiates the buttons.
Solution - Navigating DOM From Unique Element
The simplest solution conceptually is to:

*

*Get the related h3 element.

*Navigate to the parent div element, which is also the parent of the button.

*Get the button element in that parent div.

This would be done using:
product = 'Checking and Savings'
browser.h3(text: product).parent.button.click

Solution - Iterating Through Groups of Related Elements
Another approach is to iterate through each div that represents an item. For each div (item), you would check if it is the right product and then click the button.
This would be:
browser.divs(class: 'item').find { |div| div.h3(text: product).exists? }.button.click

Note that given your specific HTML snippet, this will always return the first button. The lack of closing div tag for
  is making everything appear in the same item div.
Solution - Using XPath
This is the same approach as the first solution. However, it is done using a single XPath locator. The benefit is that it is faster due to fewer method calls. However, it can be harder to read.
browser.button(xpath: "//h3[text()='#{product}']/../button").click


text:
Q: twilio phoneNUmber pricing api throw exception https://pricing.twilio.com/v1/PhoneNumbers/Countries/{countryCode}
API is fetching country and give a response like
expected response =>
{
    "url": "https://pricing.twilio.com/v1/PhoneNumbers/Countries/US",
    "country": "United States",
    "price_unit": "USD",
    "phone_number_prices": [
        {
            "number_type": "local",
            "base_price": "1.00",
            "current_price": "1.00"
        },
        {
            "number_type": "toll free",
            "base_price": "2.00",
            "current_price": "2.00"
        }
    ],
    "iso_country": "US"
}

but I am facing a problem while fetching country, it will give exception
Country country= Country.fetcher(countryCode).fetch();

exception =>
Unrecognized field "number_type" (class com.twilio.type.PhoneNumberPrice), not marked as ignorable (5 known properties: "basePrice", "type", "base_price", "currentPrice", "current_price"])
 at [Source: (org.apache.http.conn.EofSensorInputStream); line: 1, column: 212] (through reference chain: com.twilio.rest.pricing.v1.phonenumber.Country["phone_number_prices"]-
>java.util.ArrayList[0]->com.twilio.type.PhoneNumberPrice["number_type"])

how to resolve this problem

A: Twilio developer evangelist here.
What version of the Twilio Java library are you using? This looks like an issue that was fixed back in March 2017.
I recommend you upgrade the version of the Twilio Java library you are using and if that doesn't solve the issue, raise an issue on the library repo.


text:
Q: C - Sending cyclic message on socketCAN's broadcast manager I'm writing some messages on a CAN bus using socketcan's broadcast manager:
struct bcm_message{
    struct bcm_msg_head msg_head;
    struct can_frame frame[5];
};

int main(){
    int s;
    struct sockaddr_can addr;
    struct ifreq ifr;
    struct bcm_message msg;
    s = socket(PF_CAN, SOCK_DGRAM, CAN_BCM);
    strcpy(ifr.ifr_name, "can1");
    ioctl(s, SIOCGIFINDEX, &ifr);
    addr.can_family = AF_CAN;
    addr.can_ifindex = ifr.ifr_ifindex;
    connect(s, (struct sockaddr *)&addr, sizeof(addr));

    msg.msg_head.opcode  = TX_SETUP;
    msg.msg_head.can_id  = 0x180;
    msg.msg_head.flags   = SETTIMER|STARTTIMER|TX_CP_CAN_ID;
    msg.msg_head.nframes = 5;
    msg.msg_head.count = 5;
    msg.msg_head.ival1.tv_sec = 0;
    msg.msg_head.ival1.tv_usec = 100000;
    msg.msg_head.ival2.tv_sec = 0;
    msg.msg_head.ival2.tv_usec = 0;
    msg.frame[0].can_dlc=8;
    memcpy(msg.frame[0].data,(__u8[]){0x00,0x28,0xFF,0x00,0x00,0x01,0xFF,0x00},8);
    msg.frame[1].can_dlc=8;
    memcpy(msg.frame[1].data,(__u8[]){0x00,0x32,0xFF,0x00,0x00,0x01,0xFF,0x00},8);
    msg.frame[2].can_dlc=8;
    memcpy(msg.frame[2].data,(__u8[]){0x00,0x3C,0xFF,0x00,0x00,0x01,0xFF,0x00},8);
    msg.frame[3].can_dlc=8;
    memcpy(msg.frame[3].data,(__u8[]){0x00,0x46,0xFF,0x00,0x00,0x01,0xFF,0x00},8);
    msg.frame[4].can_dlc=8;
    memcpy(msg.frame[4].data,(__u8[]){0x00,0x50,0xFF,0x00,0x00,0x01,0xFF,0x00},8);

    write(s, &msg, sizeof(msg));
    while(1){}
return 0;
}

This code works properly and simply sends the five messages once with an interval of 100ms, but it's not what I want. I want send the five messages (from frame[0] to frame[4]) once, then continue sending only the last frame (frame[4]) always with an interval of 100ms. So bcm should send:
frame[0]
frame[1]
frame[2]
frame[3]
frame[4]
frame[4]
frame[4]
frame[4]
....
....

If i set iva2.tv_usec to 100000 it will continue sending all the frames, while i want to send only the last. How could I do this? I've read that adding the TX_COUNTEVT flag, the bcm will generate a TX_EXPIRED message when count reaches the zero. Maybe i can handle this TX_EXPIRED message and manually modify the bcm transmission as i need? And just if in case, how and where can I handle this TX_EXPIRED message? Is there another simplier way to reach my aim?

A: You have to split your msg into two instances to bcm_message.
In the first one, you configure your frames 0 to 3. SETTIMER and STARTTIMER are not really necessary if you want these messages to be sent only once.
In the second instance, you just configure what is frame[4] in your code.
Then you can set iva2.tv_usec which will only apply to that frame.

A: You first need to send one BCM message with the content for frames 0 to 3. In this message you need to configure SETTIMER, STARTTIMER and TX_COUNTEVT. When you receive TX_EXPIRED message, just send another BCM message with only frame 4, and with only SETTIMER flag set (and the same timing configuration). This will not restart the timer and will continue sending with just the new data.


text:
Q: ContextMenu, get Parent TextBlock Id ItemSource for the ListBox is a ObservableCollection of Animals.
Each animal have a Name and a Id. Inside the TextBlock showing the name of the animal, I have a ContextMenu. When long tap, it shows a menu UnFollow. When clicking on that Menu it raises the UnFollow_OnClick event.
Now to my question, how can I in my code behind get the Id of the animal?
Have tried some different scenarios but cannot find any working solutions.
 <ListBox x:Name="AllAnimals" Margin="0,0,-12,0" ItemsSource="{Binding AllAnimals}">
               <ListBox.ItemTemplate>
                  <DataTemplate>
                     <StackPanel Margin="0,0,0,17">
                        <TextBlock Text="{Binding Name}" TextWrapping="NoWrap" Style="{StaticResource PhoneTextExtraLargeStyle}">
                           <toolkit:ContextMenuService.ContextMenu>
                              <toolkit:ContextMenu IsZoomEnabled="False">
                                    <toolkit:MenuItem Header="Unfollow" Click="UnFollow_OnClick" />
                              </toolkit:ContextMenu>
                           </toolkit:ContextMenuService.ContextMenu>
                        </TextBlock>
                     </StackPanel>
                  </DataTemplate>
               </ListBox.ItemTemplate>
            </ListBox>

private void UnFollow_OnClick(object sender, RoutedEventArgs e)
{

}

A: this should work:
    private void UnFollow_OnClick(object sender, RoutedEventArgs e)
    {
        Animal animal = ((Animal)((sender as FrameworkElement).DataContext));

        MenuItem item = (sender as MenuItem);
        string itemValue = item.Header.ToString();

        if (itemValue == "Unfollow")
        {
            try
            {
                if (animal != null)
                {
                    // animal.Id
                }
            }
            catch (Exception)
            {
            }
        }
    }

A: Try this:
 private void UnFollow_OnClick(object sender, RoutedEventArgs e)
    {
        var animal = AllAnimals.SelectedItem as Animal;
        if(animal==null) return;
        var id = animal.Id;
    }

Hope its help.


text:
Q: Is it safe to assume memory won't get destroyed before Application's onCreate is triggered again? I want to fetch some important data in onCreate of my Application, and store them in the memory.
Can I assume the data I store in memory will be there? If the app get destroyed, can I assume onCreate will always get triggered again?

A: From the documentation for onCreate

Called when the application is starting, before any activity, service, or receiver objects (excluding content providers) have been created.

If your application is killed in the background by the system, then it would have to call onCreate again next time it is launched. As long as you re-initialize your static value in onCreate each time it should be safe - assuming your application class would hold a reference to it to prevent it from being garbage collected.
You may also find this question useful regarding garbage collecting of static variables.

A: I don't think that you can depend on that.
If you really need to recover the information, you'll need to store it somewhere that survives the destruction of the application, like local storage, or a database.


text:
Q: How to start portable pdflatex I know that this is a very easy question. I have never used Linux before and I could not figure out how this has to be done.
I am installing a protable texlive on my Kubuntu machine. Now I want to run pdflatex. In the texlive/bin/linux-i386/ directory there is the pdflatex file. If I use the dir command I can see that the file exists.
I tried to call /path/to/texlive/bin/linux-i386/pdflatex test.tex in the terminal but I get the error .../pdflatex: File or directory not found.
Calling pdflatex test.tex I get This application is not installed. You can install it...
Also using sudo pdflatex does not work.
How do I start it? Thanks for your help.
Note: The installation has to be portable. There is no way to use a not portable version.

A: Ok, I found the solution. It was only about me and my missing knowledge about Linux, LaTex and searching for the wrong terms on google. Sorry for the question.
I changed the path path/to/texlive/bin/linux-i386/pdflatex to path/to/texlive/bin/x86_64-linux/pdflatex. Now everything works fine.
Thank you for helping.


text:
Q: How to run minikube start as a linux service on startup? This question is related to How to arrange a non admin command as a systemd service?
I have the following minikube.service file:
[Unit]
Description=Runs minikube on startup
After=vboxautostart-service.service vboxballoonctrl-service.service vboxdrv.service vboxweb-service.service

[Service]
Type=forking
ExecStart=/usr/local/bin/minikube start
User=mark
Group=mark

[Install]
WantedBy=multi-user.target

And it works fine when I start it manually from the shell:
mark@minikube-vm:~$ sudo systemctl start minikube.service
mark@minikube-vm:~$ minikube ip
192.168.99.100
mark@minikube-vm:~$ systemctl status minikube.service
● minikube.service - Runs minikube on startup
   Loaded: loaded (/etc/systemd/system/minikube.service; enabled; vendor preset: enabled)
   Active: active (running) since Fri 2020-09-25 17:32:48 UTC; 34min ago
  Process: 8388 ExecStart=/usr/local/bin/minikube start (code=exited, status=0/SUCCESS)
    Tasks: 46 (limit: 19141)
   CGroup: /system.slice/minikube.service
           ├─8434 /usr/lib/virtualbox/VBoxXPCOMIPCD
           ├─8439 /usr/lib/virtualbox/VBoxSVC --auto-shutdown
           ├─8618 /usr/lib/virtualbox/VBoxHeadless --comment minikube --startvm 6ec91432-0f09-4fdc-9976-6f736b15c37f --vrde config
           ├─8632 /usr/lib/virtualbox/VBoxNetDHCP --comment HostInterfaceNetworking-vboxnet0 --config /tmp/dhcp-config-kiyf3.xml
           └─8658 /usr/bin/pulseaudio --start --log-target=syslog

Sep 25 17:31:22 minikube-vm minikube[8388]: * Using the virtualbox driver based on existing profile
Sep 25 17:31:22 minikube-vm minikube[8388]: * Starting control plane node minikube in cluster minikube
Sep 25 17:31:22 minikube-vm minikube[8388]: * Restarting existing virtualbox VM for "minikube" ...
Sep 25 17:31:23 minikube-vm pulseaudio[8658]: [pulseaudio] server-lookup.c: Unable to contact D-Bus: org.freedesktop.DBus.Error.NotSu
Sep 25 17:31:23 minikube-vm pulseaudio[8658]: [pulseaudio] main.c: Unable to contact D-Bus: org.freedesktop.DBus.Error.NotSupported:
Sep 25 17:32:16 minikube-vm minikube[8388]: * Preparing Kubernetes v1.19.0 on Docker 19.03.12 ...
Sep 25 17:32:43 minikube-vm minikube[8388]: * Verifying Kubernetes components...
Sep 25 17:32:48 minikube-vm minikube[8388]: * Enabled addons: dashboard, default-storageclass, storage-provisioner
Sep 25 17:32:48 minikube-vm minikube[8388]: * Done! kubectl is now configured to use "minikube" by default
Sep 25 17:32:48 minikube-vm systemd[1]: Started Runs minikube on startup.
mark@minikube-vm:~$

But on machine boot it fails:
mark@minikube-vm:~$ systemctl status minikube.service
● minikube.service - Runs minikube on startup
   Loaded: loaded (/etc/systemd/system/minikube.service; enabled; vendor preset: enabled)
   Active: failed (Result: timeout) since Fri 2020-09-25 17:18:09 UTC; 12min ago
  Process: 7140 ExecStart=/usr/local/bin/minikube start (code=killed, signal=TERM)

Sep 25 17:16:39 minikube-vm minikube[7140]: * Using the virtualbox driver based on existing profile
Sep 25 17:16:39 minikube-vm minikube[7140]: * Starting control plane node minikube in cluster minikube
Sep 25 17:16:39 minikube-vm minikube[7140]: * Restarting existing virtualbox VM for "minikube" ...
Sep 25 17:16:40 minikube-vm pulseaudio[7438]: [pulseaudio] server-lookup.c: Unable to contact D-Bus: org.freedesktop.DBus.Error.NotSu
Sep 25 17:16:40 minikube-vm pulseaudio[7438]: [pulseaudio] main.c: Unable to contact D-Bus: org.freedesktop.DBus.Error.NotSupported:
Sep 25 17:17:34 minikube-vm minikube[7140]: * Preparing Kubernetes v1.19.0 on Docker 19.03.12 ...
Sep 25 17:18:06 minikube-vm minikube[7140]: * Verifying Kubernetes components...
Sep 25 17:18:08 minikube-vm systemd[1]: minikube.service: Start operation timed out. Terminating.
Sep 25 17:18:09 minikube-vm systemd[1]: minikube.service: Failed with result 'timeout'.
Sep 25 17:18:09 minikube-vm systemd[1]: Failed to start Runs minikube on startup.
mark@minikube-vm:~$

What am I missing?

A: You've started a "service" which is basically just a script that runs some commands and then exits. This sort of thing should use Type=oneshot and RemainAfterExit=yes in a systemd unit, so that systemd knows the process will go away but still consider the "service" active.
You should also add a matching ExecStop= line that stops minikube, for completeness.
The systemd documentation has another example of such a unit.

A: work for me on centos 8 and 7
create the file location
/usr/lib/systemd/system/minikube.service
[Unit]
Description=minikube
After=network-online.target firewalld.service containerd.service docker.service
Wants=network-online.target docker.service
Requires=docker.socket containerd.service docker.service

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=/root
ExecStart=/usr/local/bin/minikube start --driver=none
ExecStop=/usr/local/bin/minikube stop
User=root
Group=root

[Install]
WantedBy=multi-user.target

run the next commands to enable and start the service
systemctl daemon-reload
systemctl enable minikube
systemctl start minikube

A: Ubuntu 21.04, minikube installed via deb: also need to set the systemd unit working directory to match minikube run off the cmdline:
[Unit]
Description=minikube

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=/root
ExecStart=/usr/bin/minikube start --embed-certs --driver=none
ExecStop=/usr/bin/minikube stop

[Install]
WantedBy=multi-user.target

Unit can be created with systemctl edit --force --full minikube.service
# systemctl status minikube
● minikube.service - minikube
     Loaded: loaded (/etc/systemd/system/minikube.service; enabled; vendor preset: enabled)
     Active: active (exited) since Fri 2021-06-25 03:01:57 UTC; 4s ago
    Process: 418 ExecStart=/usr/bin/minikube start --embed-certs --driver=none (code=exited, status=0/SUCCESS)
   Main PID: 418 (code=exited, status=0/SUCCESS)

...
Jun 25 03:01:57 minikube systemd[1]: Finished minikube.

# minikube status
minikube
type: Control Plane
host: Running
kubelet: Running
apiserver: Running
kubeconfig: Configured

~root/.kube/config includes embedded certs and can be used off host/vm.


text:
Q: why not db_query? (drupal db layer) The drupal database layer api says about db_query

Do not use this function for INSERT, UPDATE, or DELETE queries. Those should be handled via db_insert(), db_update() and db_delete() respectively.
  (source)

I think this is said for other database layers as well. Does anybody know why? Is it unsafe, inefficient, etc.?

A: It's just convention as far as I know. Certainly there's no technical problem with running an INSERT/UPDATE through db_query(); all it does is run a vanilla SQL query against the database so it will definitely work.
I'd imagine the documentation is simply pointing out that there are dedicated functions for those operations, and that those should be preferred to running an SQL INSERT etc. directly.
'Structured' queries (i.e. those using db_select(), db_insert(), db_update() and db_merge()) will also get the added benefit of being run through hook_query_alter() before they're executed, meaning other parts of the system can alter them as required. You don't get that same functionality when using db_query().


text:
Q: css-loader broken with modules and keyframes animation I am attempting to use keyframe animations in a react app which is using css-modules and a webpack build system.
Simplest example that reproduces the problem:
.confirmRemove {
  animation: 150ms appear ease-in;
}
@keyframes appear { ... }

Compiled to:
.comparators__confirmRemove__32JB0 {
  -webkit-animation: 150ms :local(appear) ease-in;
  animation: 150ms :local(appear) ease-in;
}

@keyframes comparators__appear__KTI43 { ... }

What it should be:
.comparators__confirmRemove__32JB0 {
  -webkit-animation: 150ms comparators__appear__KTI43 ease-in;
  animation: 150ms comparators__appear__KTI43 ease-in;
}

@keyframes comparators__appear__KTI43 { ... }

Things I have done

*

*Attempted various usages of sprinkling :local around the place

*Found an open issue request 539 but no action or responses in past
week

*Attempted versions 28.1 (latest), 27.3, and saw 26 doesn't work either

*Contemplated giving up web development

*Commented on pull request

*Attempted all steps with issue 264
What I need
A known version of css-loader that works for keyframe animations and css modules or a work around until this is fixed by the authors.
Other Relevant Information
Node Version 7.9
Current relevant package.json:
"autoprefixer": "7.1.1",
    "css-loader": "0.28.1",
    "extract-text-webpack-plugin": "2.1.0",
    "file-loader": "0.11.1",
    "node-sass": "4.5.3",
    "sass-loader": "6.0.5",
    "style-loader": "0.18.1",
    "url-loader": "0.5.8",
    "webpack": "2.5.1",
    "webpack-bundle-analyzer": "2.8.2",
    "webpack-dev-middleware": "1.10.2",
    "webpack-hot-middleware": "2.18.0",
    "webpack-md5-hash": "0.0.5"

Current relevant webpack section:
{
        test: /(\.css|\.scss|\.sass)$/,
        use: [
          {loader: 'style-loader'},
          {
            loader:'css-loader',
            options:{
              sourceMap:true,
              modules: true,
              localIdentName: '[local]---[hash:base64:5]'
            }
          },
          {
            loader: 'postcss-loader',
            options:{
              sourceMap: true,
              plugins:()=>[
                autoprefixer()
              ]
            }
          },
          {
            loader: 'sass-loader',
            options:{
              sourceMap:true,
              includePaths: [path.resolve(__dirname, 'src', 'scss')]
            }
          }
        ]
      }

A: You have to put the name of the animation first
# this
  animation: appear 150ms ease-in;

# not this
  animation: 150ms appear ease-in;

Your naming looks fine.  I've seen a lot of errors around global naming and animation naming conflicts, but that doesn't seem to be your issue.


text:
Q: Moq - Create mocked instance for constructor injected object Question
I want to create a unit test for Credentials class that verifies the password for a given credentials after executing Calculate() method it its equal to the password calculated by an object that implements IPasswordCalculator interface.
Actually, the mock object that I created returns string.Empty value when calls Calculate(ICredentials) method, instead of Pa$$w0rd, that would be the desired return.
Then...

*

*How I can implement this test without having to manually create a stub class?

*How I can define the callback method on mock object to always return Pa$$w0rd?

Thanks in advance.
Code
IPasswordCalculator interface
/// <summary>
///     The password calculator interface.
/// </summary>
public interface IPasswordCalculator
{
    /// <summary>
    /// Calculates the user password using
    /// <paramref name="credentials"/> instance.
    /// </summary>
    /// <param name="credentials">
    /// <see cref="ICredentials"/> to perform the calculation.
    /// </param>
    void Calculate(ICredentials credentials);
}

ICredentials interface
/// <summary>
///     The Credentials interface.
/// </summary>
public interface ICredentials
{
    /// <summary>
    ///     Gets or sets the user password.
    /// </summary>
    string Password { get; set; }

    /// <summary>
    ///     Gets the user name.
    /// </summary>
    string Username { get; }

    /// <summary>
    ///     Calculates the password.
    /// </summary>
    void Calculate();
}

Credentials implementation
/// <summary>
///     User credentials.
/// </summary>
public sealed class Credentials : ICredentials
{
    /// <summary>
    ///     Initializes a new instance of the <see cref="Credentials" /> class.
    /// </summary>
    /// <param name="passwordCalculator">
    ///     The credentials calculator.
    /// </param>
    /// <param name="username">
    ///     The user name.
    /// </param>
    public Credentials(IPasswordCalculator passwordCalculator, string username)
    {
        this.Calculator = passwordCalculator;
        this.Username = username;
        this.Password = string.Empty;
    }

    /// <summary>
    ///     Calculates the password.
    /// </summary>
    public void Calculate()
    {
        if (null != this.Calculator)
        {
            this.Calculator.Calculate(this);
        }
    }
}

Test
    /// <summary>
    /// Calculate should set password value expected using calculator.
    /// </summary>
    [TestMethod]
    public void CalculateShouldSetPasswordValueExpectedUsingCalculator()
    {
        ICredentials credentials = null;
        var repo = new MockRepository(MockBehavior.Default);
        var mock = repo.Create<IPasswordCalculator>();
        mock.Setup(x => x.Calculate(credentials))
            .Callback(() => { credentials.Password = "Pa$$w0rd"; });

        IPasswordCalculator calculator = mock.Object;

        credentials = new Credentials(calculator, "Me");
        credentials.Calculate();

        Assert.AreEqual("Pa$$w0rd", credentials.Password);  // Fail
    }

A: You need to setup your mock in the following way
mock.Setup(x => x.Calculate(It.IsAny<ICredentials>()))
    .Callback((ICredentials c) => { c.Password = "Pa$$w0rd"; });

Thus you tell it "whatever ICredentials you get as the parameter of the Calculate method, set its Password to 'Pa$$word'"

A: I think you need to initialize the credentials variable before the call to mock.Setup(). With your code, Moq expects a call credentials.Calculate(null).


text:
Q: XCode debug error Thread 1 Ok so I'm trying to work with swift on XCode but every time I start to run my code I get this
Thread 1 Queue: com.apple.main-thread(serial)
What does this mean?, and how do I fix it? Also i've started a new project with the same code to make sure theres no unnecessary code mistakes. However I still get the same error.

A: What you describe as an error, it's not. That is the main queue where the program runs. You will see that queue every time you run a program.


text:
Q: Maximum number of elements (excluding the identity)that one need to compute the order, to determine the isomorphism class of Abelian group $G$ I just finished below to exercises.

If $G$ is Abelian group of order $9$ then, maximum number of elements
(excluding the identity)that one need to compute the order, to
determine the isomorphism class of $G$ is $3$

If $G$ is Abelian group of order $18$ then, maximum number of elements
(excluding the identity)that one need to compute the order, to
determine the isomorphism class of $G$ is $6$

My Question: Is there is general statement regarding this?
I mean,

If $G$ is Abelian group of order $n$ then, what is the maximum number of elements (excluding the identity)that one need to compute the order, to determine the isomorphism class of $G$?

Please help


text:
Q: Byte array getString only converts the first index I am attempting to send data across localhost via TCP, the data is being sent and put into a byte array, then converted to a string and finally printed out. Everything except the converting to a string works:
Data is appearing in Wireshark
The byte array holds all the correct bytes
However, when printing I only see the first index.
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes, 0, handler.Available, SocketFlags.None);

data = Encoding.UTF8.GetString(bytes, 0, bytesRec);
Debug.Log(data);

Message being shown in Wireshark:


text:
Q: Store canvas image to mysql using path location I'm trying to save my canvas image (generated by the user in the template) in my database. I've been through a lot of sources here, majority I've combined everything on it and got pretty much confused.
Steps that I'm trying to make:

*

*Html form where provides different choices asked from the user (done)

*Each time the user selects his/her choice, beside of it is the canvas that displays the image. (done)

*A button that displays the summary of his choices and the canvas image generated through modal (done)

*A button to Submit his order with the image in database using php and mysql No error! But it doesn't store my image
I don't need to download it, i just want it to directly store in my database once submitted
So where I'm stuck is in the STEP 4
I'll give a summary choice on my codes: (it works fine in my file, just giving you the outcome idea)

    /*This retrieves my data my JS w/c is same file with my HTML:  */
    $('#review').click(function () {
    $('#shape').html($('input[name="shape_design"]:checked').val());
    $('#color').html($('input[name="color_design"]:checked').val());

//in this part, i am getting the image displayed in the canvas based on the user's choice
    var canvasSource = document.getElementById('myCanvas');
    var contextSource = canvasSource.getContext('2d');
    var canvasShow = document.getElementById('show_canvas');
    var contextShow = canvasShow.getContext('2d');
    var image = contextSource.getImageData(0, 0, canvasSource.width, canvasSource.height);
    contextShow.putImageData(image, 0, 0); });
     });

     $(function () { //this function converts the canvas to image, so it is now called as "Show Canvas" , it display well in my modal... not sure if its the right code
       $("#submitBtn").bind("click", function () {
       var base64 = $('#myCanvas')[0].toDataURL();
       $("#show_canvas").attr("src", base64);
       $("#show_canvas").show();
       });
      });

   //After reviewing it, this part will perform to store it in the database.. which is quite I'm confused
    $('#submitOrder').click(function(confirm){
      swal({ //sweetalert style
        title: "ORDER SENT", },
      function(submit){
        setTimeout(function(){
        $('#showchoices').submit();   }, 500); //"showchoices" is the name of the Html form, it will proceed to ordersent.php
        });
       });

For my php which I'm not sure what I'm doing.
Ordersent.php
   <? php
            $shape_design = $_POST['shape_design'];
            $color_design = $_POST['color_design'];
            $upload_dir = "upload/";  //what does this do?
            $myCanvas = $_POST['myCanvas']; //myCanvas is the name and id in my form
            $myCanvas = str_replace('data:image/png;base64,', '', $myCanvas);
            $myCanvas = str_replace(' ', '+', $myCanvas);
            $data = base64_decode($myCanvas);
            $file = $upload_dir."image_name.png";
            $success = file_put_contents($file, $data);

          $dbc = @mysql_connect('localhost' , 'root', '');
          @mysql_select_db('order_tbl', $dbc);
          $query1 = "INSERT INTO choices_tbl VALUES (NULL,'$shape_design','$color_design', '$myCanvas')";

            if(@mysql_query($query1,$dbc))
              {    Header("Location: /home.php");  }
            else {  print 'error!! '.mysql_error().'';  }
?>

I tried following the instructions most of the tutorial, but it doesn't work on me.
I wanted to save it in my database using PATH , my my data type in my tables are
order_tbl
designID INT(6) NOT NULL ,
shape_design VARCHAR(20) ,
color_design VARCHAR(20) ,
myCanvas VARCHAR(150) ,
am I missing an attribute?
thanks for the help in advance! Thanks for bearing with me.


text:
Q: Updating dependent property once instead of twice In my ViewModel I have two properties type of Datetime. They are bound in XAML with TwoWay mode. When I update each of them - OnPropertyChanged raises in set part of this Datetime property for the third property. So I want to update the third property only once when I update two Datetime properties at the same time, instead of updating third property twice. How it can be archieved?
Code applied:
//1
public DateTime StartDate
{
    ...
    set
    {
        this.selectedEndDate = value;
        this.OnPropertyChanged("StartDate");
        this.OnPropertyChanged("MyList");
    }
}
//2
public DateTime EndDate
{
    ...
    set
    {
        this.selectedEndDate = value;
        this.OnPropertyChanged("EndDate");
        this.OnPropertyChanged("MyList");
    }
}
//third property
public IEnumerable<MyObject> MyList
{
    get
    {
        return _data.Where(kvp=> kvp.Key.Date >= Start && kvp.Value.Date <= End).Select(kvp => kvp.Value);
    }
}

A: You may delay the MyList property change notification by means of a timer that is started whenever one of the date properties changes. This would not only avoid double notifications when both properties change "at the same time", but would also protect against frequent notifications when one of the properties changes too frequently.
The timer would be reset on every property change by stopping and restarting it, hence you can have many subsequent property changes before actually notifying the MyList property change.
The code example below uses a DispatcherTimer to perform this task. Of course you have to find a sensible value for the Interval value.
private DispatcherTimer notifyTimer;

public ViewModel()
{
    notifyTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(200) };
    notifyTimer.Tick += OnNotifyTimerTick;
}

private void OnNotifyTimerTick(object sender, EventArgs e)
{
    OnPropertyChanged("MyList");
    notifyTimer.Stop();
}

public DateTime StartDate
{
    ...
    set
    {
        selectedEndDate = value;
        OnPropertyChanged("StartDate");
        notifyTimer.Stop();
        notifyTimer.Start();
    }
}

public DateTime EndDate
{
    ...
    set
    {
        selectedEndDate = value;
        OnPropertyChanged("EndDate");
        notifyTimer.Stop();
        notifyTimer.Start();
    }
}

A: As I see it user change startDate fist endDate second. ? or vice versa.
The below code has a chance ,
        bool fistChanged,endChanged;

         on Ctor (Constructor)
         this.PropertyChanged+=(s,p)=>
         {
                if(p.PropertyName=="firstDate")
                {
                 firstChanged=true;
                }
                if(p.PropertyName=="endDate")
                {
                 endChanged=true;
                }
                if(firstChanged && endChanged)
                {
                    this.OnPropertyChanged("MyList");
                    fistChaned=false;endChanged=false;
                }
         }


text:
Q: Div Randomly Translates Vertically I recently created a VS Code Extension on code completion. Now I started creating a website as a landing page for people to sign up for and customize their extension settings.
I almost finished creating the editor which pops up first on that page but then this issue occured - In this clip, everything seems to work normally:
Here is the video link
But this is not working as intended:
Link of the other video
My CSS file(main_light.css):

function load() {
  var python1 = $("#python-1");
  var python2 = $("#python-2");
  var java1 = $("#java-1");
  var java2 = $("#java-2");
  var typescript1 = $("#typescript-1");

  var fileContents = $(".file-contents");
  var mode = sessionStorage.getItem("mode") || "light";

  let createLineNumbers = (n) => {
    let lineNumbers = "";
    for (let i = 1; i <= n; i++) {
      lineNumbers += "" + i + "";
    }
    let lineNumbersDiv = $(".line-numbers");
    lineNumbersDiv.empty();
    lineNumbersDiv.html(lineNumbers);
  }

  $(python1).click(() => {
    fileContents.empty();
    console.log("python1");
    python1.addClass("selected");
    python2.removeClass("selected");
    java1.removeClass("selected");
    java2.removeClass("selected");
    typescript1.removeClass("selected");
    var vara = ('a');
    var comma = (', ');
    var varb = ('b ');
    var equals = ('= ');
    var zero = ('0');
    var comma2 = (', ');
    var one = ('1
');
    var comment = ('#Print the first 10 numbers of the fibonacci series');
    var loopfor = ('for ');
    var var1 = ('i ');
    var loopin = ('in ');
    var range = ('range');
    var parenopen = ('(');
    var ten = ('10');
    var parenclose = (')');
    var colon = (':
');
    var print = ('	print');
    var parenopen2 = ('(');
    var varb2 = ('b');
    var parenclose2 = (')
');
    var vara2 = ('	a');
    var comma3 = (', ');
    var varb3 = ('b ');
    var equals2 = ('= ');
    var varb4 = ('b');
    var comma4 = (', ');
    var parenopen3 = ('(');
    var vara3 = ('a ');
    var plus = ('+ ');
    var varb5 = ('b');
    var parenclose3 = (')');

    var pretyped = $("
" + vara + comma + varb + equals + zero + comma2 + one + "
");
    var completion = $("
" + loopfor + var1 + loopin + range + parenopen + ten + parenclose + colon + "

" + print + parenopen2 + varb2 + parenclose2 + "

" + vara2 + comma3 + varb3 + equals2 + varb4 + comma4 + parenopen3 + vara3 + plus + varb5 + parenclose3 + "
");

    createLineNumbers(2);

    fileContents.append(pretyped);

    var totypeLine = $("

");
    fileContents.append(totypeLine);

    var typewriter = new Typewriter('#to-type-line', {
      loop: false,
      cursor: '|',
      delay: 50
    });
    typewriter.typeString(comment).pauseFor(1000).start();

    fileContents.append(completion);
    var decoration = $("
Codosaurus Copilot
");
    fileContents.append(decoration);
    completion.css("opacity", "0");
    decoration.css("opacity", "0");
    setTimeout(() => {
      createLineNumbers(5);
      fileContents.css("transform", "translate(50px, -115px)");
      completion.css("opacity", "1");
      decoration.animate({
        "opacity": "1"
      }, 1000);
    }, 4000);
  });
  $(python2).click(() => {
    fileContents.empty();
    console.log("python1");
    python2.addClass("selected");
    python1.removeClass("selected");
    java1.removeClass("selected");
    java2.removeClass("selected");
    typescript1.removeClass("selected");
    var comment = ('# Take two numbers from the user as an input and display them after adding');
    var number1 = ('number1 ');
    var equals = ('= ');
    var int = ('int');
    var parenopen = ('(');
    var input = ('input');
    var parenopen2 = ('(');
    var prompt = ('"Enter a number"');
    var parenclose2 = (')');
    var parenclose = (')
');
    var number2 = ('number2 ');
    var equals2 = ('= ');
    var int2 = ('int');
    var parenopen3 = ('(');
    var input2 = ('input');
    var parenopen4 = ('(');
    var prompt2 = ('"Enter another number"');
    var parenclose4 = (')');
    var parenclose3 = (')');
    var sum = ('sum ');
    var equals3 = ('= ');
    var number1plusnumber2 = ('number1 + number2');
    var print = ('print');
    var parenopen5 = ('(');
    var sum2 = ('sum');
    var parenclose5 = (')');

    var pretyped = $("
" + comment + "
" + number1 + equals + int + parenopen + input + parenopen2 + prompt + parenclose2 + parenclose + "
" + "
");
    var completion = $("
" + "

" + sum + equals3 + number1plusnumber2 + "

" + print + parenopen5 + sum2 + parenclose5 + "
");

    createLineNumbers(3);

    fileContents.append(pretyped);

    var totype = number2 + equals2 + int2 + parenopen3 + input2 + parenopen4 + prompt2 + parenclose4 + parenclose3;

    var totypeLine = $("

");
    fileContents.append(totypeLine);

    var typewriter = new Typewriter('#to-type-line', {
      loop: false,
      cursor: '|',
      delay: 50
    });
    typewriter.typeString(totype).pauseFor(1000).start();

    fileContents.append(completion);
    var decoration = $("
Codosaurus Copilot
");
    fileContents.append(decoration);
    completion.css("opacity", "0");
    decoration.css("opacity", "0");
    setTimeout(() => {
      createLineNumbers(6);
      //fileContents.css("transform", "translate(50px, -115px)");
      completion.css("opacity", "1");
      decoration.animate({
        "opacity": "1"
      }, 1000);
    }, 4000);
  });

  python1.click();
}
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@900&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@400;900&family=Poppins&display=swap');
* {
  outline: none;
}

body {
  background-color: #f5f5f5;
}

.title {
  font-size: 6em;
  font-weight: bold;
  color: #000;
  font-family: 'Montserrat', sans-serif;
  text-align: center;
  margin-top: 1em;
  margin-bottom: 0em;
}

.sub {
  font-size: 1.2em;
  font-weight: bold;
  color: #626262;
  font-family: 'Poppins', sans-serif;
  text-align: center;
  margin-top: 0em;
  margin-bottom: 2em
}

.btn-primary {
  background-color: #8000ff;
  color: #fff;
  border: none;
  font-size: 1.2em;
  font-weight: bold;
  font-family: 'Poppins', sans-serif;
  margin: auto;
  margin-bottom: 2em;
  border-radius: 10px;
  padding: 16px 20px;
  display: block;
  cursor: pointer;
  transition: 0.5s;
}

.btn-primary:hover {
  box-shadow: inset 0px 0px 40px 5px #ffb300a4;
}

.material-icons {
  transform: translate(10px, 5px);
}

.editor {
  margin: auto;
  max-width: 950px;
  min-height: 450px;
  height: auto;
  background-color: #fff;
  border-radius: 1em;
  box-shadow: 0px 0px 50px 10px rgba(0, 0, 0, 0.2);
}

.editor-tabs {
  width: 100%;
  height: 50px;
  background-color: #effffd;
  border-radius: 1em 1em 0 0;
  overflow-x: scroll;
  overflow-y: hidden;
}

.editor-tabs::-webkit-scrollbar {
  display: none;
}

.file-tab {
  position: relative;
  top: 0;
  left: 0;
  height: 50px;
  width: auto;
  background-color: #effffd;
  border-radius: 1em 1em 0 0;
  color: #6d6d6d;
  overflow: hidden;
  border: none;
  padding: 10px;
  cursor: pointer;
}

.file-tab:hover {
  background-color: #fff;
}

.file-tab.selected {
  background-color: #fff;
  color: #000;
  border-top: #8000ff solid 2px;
}

.file-tab-content {
  position: relative;
  top: 0;
  left: 0;
  height: auto;
  width: auto;
  border-radius: 0.5em;
  display: table-cell;
  vertical-align: top;
}

.lang-logo {
  position: relative;
  top: 0;
  left: 0;
  height: 20px;
  width: auto;
}

.filename {
  position: relative;
  font-size: 1em;
  font-family: 'Poppins', sans-serif;
  font-weight: bold;
  text-align: center;
  margin-top: 0em;
  transform: translateY(-5px);
  display: inline-block;
}

.line-numbers {
  position: relative;
  font-weight: bold;
  color: #2a2a2a;
  text-orientation: upright;
  writing-mode: vertical-lr;
  background-color: #effffd;
  font-size: 1.2em;
  font-family: 'consolas', monospace;
  text-align: right;
  padding-left: 1em;
}

.line {
  position: relative;
  color: #2a2a2a;
  margin-top: 0em;
  background-color: #ffffff;
  font-size: 1.2em;
  font-family: 'consolas', monospace;
}

.file-contents {
  position: relative;
  top: 0;
  left: 0;
  vertical-align: middle;
  transform: translate(50px, -46px);
  width: 90%;
}

.completion {
  background: #d4ebff;
  width: fit-content;
}

.decoration {
  position: relative;
  top: 0;
  left: 0;
  vertical-align: middle;
  width: 160px;
  font-size: 1em;
  font-family: 'Poppins';
  background-color: #8000ff;
  color: #fff;
  padding: 5px 10px;
  font-weight: bold;
  border-radius: 7px;
  margin-top: 10px;
  transform: translateX(180px);
}

.var {
  color: #000;
}

.comment {
  color: #a0a1a7;
}

.separator {
  color: #000;
}

.keyword {
  color: #a626a4;
}

.method-2 {
  color: #4078f2;
}

.bracket {
  color: #000;
}

.method-1 {
  color: #4078f2;
}

.operator {
  color: #000;
}

.number {
  color: #986801;
}
<!DOCTYPE html>

  <meta charset='utf-8'>
  <meta http-equiv='X-UA-Compatible' content='IE=edge'>
  <title>Codosaurus Copilot - By Melting Obsidian</title>
  <meta name='viewport' content='width=device-width, initial-scale=1'>
  <link rel='stylesheet' href='CSS/main-light.css'>
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

Codosaurus Copilot

A better AI for a better programming experience

      <button class="btn-primary">Sign Upeast</button>

          <button class="file-tab selected" id="python-1">

                            Fibonacci.py

                    </button>

          <button class="file-tab" id="python-2">

                            Add.py

                    </button>

          <button class="file-tab" id="java-1">

                            SwingExample.java

                    </button>

          <button class="file-tab" id="java-2">

                            PersonExample.java

                    </button>

          <button class="file-tab" id="typescript-1">

                            HelloWorld.ts

                    </button>

Any suggestions would be appreciated. Thank you in advance

A: You are adding fileContents.css("transform", "translate(50px, -115px)");
due to which file-content is being getting its position changed and when you are switching tab as per .file-content is positioned top:0; left:0;
so your div is getting translated to -115px above
For the solution you need to reset its position to 50px, -46px. So, on click of tabs you need to add
fileContents.css("transform", "translate(50px, -46px)");


text:
Q: Why are high end audio connections gold? Silver has a lower resistivity than gold and is cheaper, so why are high end audio components gold plated?

A: Tarnished contacts cause distortion. You can really hear the audio quality degradation; it is not some audio-fool nonsense, like directional speaker cables or two hundred dollar amplifier power cords.
Even a dyed-in-the-wool objective measurement man like like Doug Self acknowledges this problem, in no uncertain terms, right in the middle of his treatise on "Subjectivism":

Corrosion is often blamed for subtle signal degradation at switch and connector contacts. By far the most common form of contact degradation is the formation of an insulating sulphide layer on silver contacts, derived from hydrogen sulphide air pollution; the problem seems to have become worse in recent years. This typically cuts the signal altogether, except when signal peaks temporarily punch through the sulphide layer. The effect is gross and completely inapplicable to theories of subtle degradation. Gold-plating is the only certain cure. It costs money. A switch with gold-flashed contacts can cost five times as much as the silver version.  [Source] [Bold emphasis mine].

Other metals like silver will do, but the contacts will require regular polishing to perform their best. Gold is more maintenance-free.
I own a bunch of old audio and guitar gear, and I can tell you that if you put a little bit of toothpaste on a cotton swab and vigorously polish the inside of a 1/4" phone jack on some old amplifier or signal processor, it comes out black. The sound quality improves drastically.

A: Mainly for marketing purposes: Gold is always better than silver, right?
But also, silver oxidizes (tarnishes) readily while gold does not.

A: Gold is highly resistant to corrosion or oxidation, so prevents poor connections from those sources.It is also fairly soft, so the mating surfaces deform slightly, increasing contact area to reduce resistance. The gold plating is very thin, so the added resistance from the gold is easily overcome by its other properties.
Note that gold is only needed on the actual contact areas - gold plating (or colour) on the body of the connector is only there to attract the gullible.
Many commercial (not audiophile) connectors have selective gold plating on the contacts - the gold is only placed where it really matters.

A: An important thing to remember is that when dissimilar metals are joined, and there is a thermal flux, a voltage is generated due to the thermoelectric effect. This voltage is called a thermal EMF.
A good discussion of this effect can be found in the classic Linear Technology application note AN-86 by the late Jim Williams. See in particular page 48 for a table of thermoelectric EMFs.
From that table, note that copper-copper junctions have the lowest thermal EMF of less than 0.2 uV/°C BUT notice that copper-copper oxide junctions have the highest thermal EMF of over 1000 uV/°C. Copper-gold junctions have a reasonable thermal EMF of 0.3uV/°C.
So, in precision voltage / current / resistance measurements we often use cleaned copper-copper junctions or copper-gold junctions to minimize thermal EMFs.
That said, in audio applications, if the contributed thermal EMF was 100uV, if the full scale signal is 15 volts, that's only 6.6ppm (parts per million). That's nearly -120dB. It's pretty hard to make the case that a human can hear 6ppm / -120dB.

A: Some professional audio gear does use silver or silver alloy contacts (or did : the items I am thinking about are well and truly obsolete!) - such equipment served the broadcast audio for decades - BUT it was regularly and thoroughly maintained, with metal polish being an essential item of the toolkit.
The rotary "stud faders" in BBC mixer desks up until the 1970s were of this type : not variable resistors but switched attenuators with something like 1dB steps, a huge array of precision resistors, and solid silver contacts. These lasted until the stereo era.
Prototype stereo "stud faders" were tried - but however accurately they were made, the two channels switched gain at slightly different times, and the "blurring" in the stereo image during fades was judged to be quite unpleasant.
Here is a description of a mono one - as you can see, rapid maintenance was an important design consideration. (I cannot embed the picture, it appears to be protected) The contacts look pinkish; they need cleaning to show their true colour.
So silver has a long history in audio, and not all of it can be dismissed as woolly headed nonsense (though there is plenty of that too!).
But gold is easier to deal with and, while lower conductivity, quite good enough for most purposes and overall better for domestic equipment. Unless you are so dedicated to perfect sound that you are willing to overhaul every connector and switch contact on something like a regular six-monthly schedule.


text:
Q: Blackberry soap response I am trying to consume .net webservices, and I can establish the connection. However this is the response I am getting:
[0.0] anyType{NewDataSet=anyType{Table=anyType{Card_ID_PK=2243; PAN=63369610009001016; Expiry_Date[0.0] =15/06/2015; Embossed_Name=IDL IG scheme;

I want them to split and display it as a table. I searched in google and I found some methods like split() but that can only delimit single character and also I need the way to remove the characters and use them as key value pair which is used for .
Here is my code for soap:
       // TODO Auto-generated method stub
    if (DeviceInfo.isSimulator()) {
        URL = URL + ";deviceSide=true";
    }

        SoapObject rpc = new SoapObject(NAMESPACE, METHOD_NAME);    //soap object to open the namespace and method name
        rpc.addProperty("CH_ID","15");
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

    envelope.bodyOut = rpc;
    System.out.println("envelope response"+envelope.bodyOut.toString());
    envelope.dotNet = true;
    envelope.encodingStyle = SoapSerializationEnvelope.XSD;
    System.out.println("in soap");

    envelope.setOutputSoapObject(rpc);

        HttpTransport ht = new HttpTransport(URL);
        ht.debug = true;
       try {
    System.out.println("int try");
    ht.call(SOAP_ACTION, envelope);
              System.out.println("int try");

               SoapObject resultProperties = (SoapObject) envelope.getResponse();
            System.out.println("IN TRY");
                                            String res=resultProperties.getProperty(1).toString();
            System.out.println("Response"+res);

            String[] pattern={"{","}","anytype","Table",";"};
            String replacement="";
            String array=replaceall(res,pattern,replacement);

                System.out.println(" array element:"+array[i]);

replace all method :
   public String replaceall(String str, String[] pattern, String replacement)
       {
    if(str==null)
    {
        return "";
    }
    StringBuffer sb=new StringBuffer();

    int index=-1;
    String workingSource = str;

        for(int i=0;i<pattern.length;i++)
    {
    while ((index = workingSource.indexOf(pattern[i])) != -1)
    {

        sb.append(workingSource.substring(0, index));
                sb.append(replacement);

        sb.append(workingSource.substring(index + pattern[i].length()));

                workingSource = sb.toString();

                sb.delete(0, sb.length());
    }
    }

    return workingSource;

}

}


text:
Q: Restrict function access ONLY to one other specific contract in Solidity I have a security problem in my Solidity contracts and I can't figure out how to fix it.
The flow goes like this:

*

*First, we create an instance of contract A;

*Create an instance of contract B, which receives the contract A instance in the constructor (its address);

*At some point, contract B calls a function 'foo' from contract A which tells contract A to send money to an address (the address is received as a parameter);

*Contract A sees the msg.sender as the address of contract B;

My problem is:

*

*I want to restrict the access for the function 'foo' in contract B only to be called by contract A (no calls made by humans manually);

*I cannot make a modifier to check the address. Since I create Contract A before Contract B, I cannot know the address of Contract B in Contract A;

*I cannot make the function internal as the contracts are not derived;

Can you please offer me advice on how to fix this problem or explain another approach on this? I am new to Solidity.
Thank you!

A:
I cannot make a modifier to check the address.

You can, but the address needs to be in a variable, set after the contract B has been deployed.
pragma solidity ^0.8;

contract ContractA {
    address contractB;

    modifier onlyContractB {
        require(msg.sender == contractB);
        _;
    }

    function foo() external onlyContractB {
    }

    function setContractBAddress(address _contractB) external {
        contractB = _contractB;
    }
}

pragma solidity ^0.8;

interface IContractA {
    function foo() external;
}

contract ContractB {
    IContractA contractA;

    constructor(address _contractA) {
        contractA = IContractA(_contractA);
    }

    function callFoo() external {
        contractA.foo();
    }

}

*

*Deploy contract A

*Deploy contract B, passing it the "A" address in the constructor

*Set the contractB value in "Contract A".

I left out any auth mechanism while setting the contractB address in ContractA for simplicity. In this example, anyone can set the address, which you probably don't want, and you should add a mechanism allowing only authorized senders to set the contractB value in ContractA.


text:
Q: SQL Text Function for special characters I have a field with text reviews in it and I want to spot where people have used special characters to get offensive words etc past the filters, so instead of typing badword they type b.a.d.w.o.r.d or b*a*d*w*o*r*d,
Is there a way to look for say 3 or more special characters in word in a text review, maybe some sort of count function for special characters?

A: If you have a table with a field containing words you dont want to allow you could add it in your WHERE clause like so using REGEX_REPLACE.
SELECT yourfield
FROM yourtable
WHERE REGEXP_REPLACE(yourfield,'[^a-zA-Z'']','') NOT IN (SELECT badwords
                                                         FROM badwordstable)


text:
Q: Independence of 2 discrete random variables If I have 2 discrete random variables $X$ and $Y$, and I know their probability mass functions, then how do I show that the $2$ random variables are independent? I know that $\mathbb{P}(X=x,Y=y)=\mathbb{P}(X=x)\mathbb{P}(Y=y)$, but I don't quite understand what I can do with this to show that they are independent. I think I am just confused by the LHS. What does that even mean? If I have the $2$ pmfs, and I multiply them together to get the RHS of the equation, how would I show that it equals the LHS and are therefore independent?

A: First you want to calculate $P(X=x,Y=y) = P(X=x \,\&\, Y=y) = P(\{X=x\} \cap \{Y= y\})  $
Next calculate $P(X=x)\cdot P(Y=y)$
If you get the same result then they are independent, denoted $X \perp \!\!\! \perp Y$.
A few ways to possibly compute $P(X=x, Y =y)$:
Bayes Rule: $P(X=x, Y=y) = P(X=x\mid Y=y)P(Y=y)$
Addition/Union Rule: $P(\{X = x \} \cup \{Y=y\}) = P(X=x) + P(Y=y) - P(X=x,Y=y)$

A: Using the intuitive definition of joint probability in terms of conditional probability, we have
$P(X=x, Y=y)=P(X=x|Y=y).P(Y=y)$
$=P(X=x)P(Y=y)$ (given)
Assuming $P(Y=y) \neq 0$ (the trivial case for an impossible event) it implies that $P(X=x|Y=y)=P(X=x)$, which tells us that probability of $X$ does not depend upon the probability of occurence of $Y$, hence they are independent.


text:
Q: Sort list of ints by the first digit of each int I'm trying to figure out how to sort a list of integers by the first digit in each int, (and if the same, move to the next digit, etc.)
I'm sure I can just loop through, (although I've been having issues because it seems like I need to make my list a list of strings in order to grab the first digit and this just hasn't been working out for me), but I'd like to know if there is a way to do this easily with the sorted() method.
EX:
myList = [34254, 2343, 49, 595, 323]

My desired result:
sortedList = [2343, 323, 34254, 49, 595]

A: Sort with a key of strings and you'll get ASCIIbetical sorting.
>>> myList = [34254, 2343, 49, 595, 323]
>>> sorted(myList, key=str)
[2343, 323, 34254, 49, 595]


text:
Q: How do I quit Android emulator when force quit does not work? For me, Android Studio works perfectly fine. I am able to run applications on the Android Studio emulator as well as my genymotion emulator. However, once I decide that I want to close the emulator, it exits, but it stays stuck on my dock. When I try to force quit it with the ALT + COMMAND + ESC dialog, it won't force quit. The emulators also do not show up when I type "top" into the terminal. I'm not sure why this problem persists.
All I want to do is to be able to force quit these icons. I have tried both killall Dock and killall SystemUIServer. Also, the emulators do not show up on my Activity Monitor. It is frustrating because I am still able to open Android Studio and launch new emulators, but they get stuck on my dock.
I am working from a early 2015 Macbook Pro Retina 13-inch. If anyone could offer any help, I'd greatly appreciate it.
This is the picture of my dock
Update: other apps seem to quit just fine, but these apps just stay in the dock no matter what. Now, Mozilla Firefox is not quitting as well.
This is what my dock looks like now

A: This is third party software, but you could try the freeware program RedQuits:
http://www.carsten-mielke.com/redquits.html
It will make it so that clicking the red exit x button will close the program instead of dock it.


text:
Q: Non-integer value to (/sys/class/backlight/intel_backlight/brightness) Some two years ago, I was able to set a very dim backlight brightness by writing a non-integer value to /sys/class/backlight/intel_backlight/brightness.

$ echo 0.3 > /sys/class/backlight/intel_backlight/brightness

But now, it seems that there is some sanity check... so, the system complains:

bash: echo: write error: Invalid argument

Is there anyway I can bypass such sanity check? Is there a way to pass values directly to the driver? I believe the relevant driver is i915.

Linux debiel 5.4.0-4-amd64 #1 SMP Debian 5.4.19-1 (2020-02-13) x86_64 GNU/Linux

Please, let me know if I should have given you any useful information. I do not really know how to properly report the problem.

A: Sounds like an implementation detail of your specific hardware driver. Have you used the exact same hardware when setting float dim values resulted in actually less lit display? Or do you now have simply a less finely configurable backlight, maybe? Probably, you could go to an intel support forum and ask there for the backlight value stepping API. Would be interesting, what their officials tell then. At least intel releases their own linux hardware drivers, so this is officially specified APIs. As I like Arch Linux Wiki for such information, I post a link to their API description here:
https://wiki.archlinux.org/index.php/Backlight#Backlight_PWM_modulation_frequency_(Intel_i915_only)
This Link explains i915 is using PWM to adjust light more accurately. Maybe PWM is disabled in your kernel since it typucally caused flickering on this hardware.


text:
Q: Не работает под меню Bootstrap из под мобильных устроиств На сайте есть под меню, первый уровень кликается, а второе и третье подменю не нажимается, можете подсказать почему на этом сайте?
A: Спасибо ребята, нашел решение, работает, уже проверил:
В файле bootstrap.js найти строку ontouchstart и поменять ее на disable-ontouchstart.
Почему не работает 2-ой уровень? Потому что первый уровень выходит по клику, а второй по :hover, нужно делать 'хитрый' клик, либо ставить костыль, чтобы на мобиле меню выпадало по клику ;)
A: в 3-м бутстрапе подменю вообще не открывается из-за того, что нет скроллинга.
во всяком случае, так на андроиде.

A: В версии Bootstap 5
Вместо:
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

использовал (изменил data-toggle и data-target на data-bs-toggle и data-bs-target соответственно):
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">


text:
Q: how to get correct date diffrence i want to compare a date with the current date and do something if the difference is 2 months or 6 or a year .. but i have a problem how to get the correct difference for example if the current month is 02 2015 and the other month is 10 2014 i will get 8 in difference but the actual difference is 4 .. how to do it ?
    Calendar c = Calendar.getInstance();
        System.out.println("Current time => " + c.getTime());
        SimpleDateFormat d = new SimpleDateFormat("dd");
        SimpleDateFormat m = new SimpleDateFormat("MM");
        SimpleDateFormat ye = new SimpleDateFormat("yyyy");
        String day = d.format(c.getTime());
        String month = m.format(c.getTime());
        String year = ye.format(c.getTime());
        int d1=Integer.parseInt(day);
        int m1=Integer.parseInt(month);
        int d2=25;
        int m2=02;
        int diff=d1-d2;
        String s=String.valueOf(diff);

A: You could just use the difference in milliseconds between the 2 dates. Pre-compute the differences you need/want as constants and compare to the delta you have, for example:
static final long DAY = 1000 * 60 * 60 * 25;
static final long MONTH = DAY * 30;

...

int diff = d1 - d2;
if(diff > MONTH) {
   //more than a month difference
}

If you need something more complex you should perhaps use a library such as Joda Time which will give a more comprehensive set of features to work with time.

A: You are calculating your difference between two int, so it can't work.
You should calculate it between two dates or two long (in secondes or milliseconds)
long oneDay, today, delay;
oneDay = 1000*3600*24; //number of milliseconds in a day
today = Calendar.getInstance().getTimeInMillis();
delay = (TheDateYouWantToCompare - today)/oneDay;
if (delay >= 60*oneDay) { //more than 2 months
    //your code
}else{
    //your code
}

If TheDateYouWantToCompare and today are dates, it's almost the same :
delay = (TheDateYouWantToCompare.getTime() - today.getTime())/oneDay;

Edit :
Here it is how to get time in milliseconds.
String DateString = "31-12-2015";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date myDate = sdf.parse(DateString);
long timeInMilliseconds = myDate.getTime();


text:
Q: How to control size of Parquet files in Glue? I'm loading a data set into a DynamicFrame, perform a transformation and then write it back to S3:
datasink = glueContext.write_dynamic_frame.from_options(
    frame = someDateFrame,
    connection_type = "s3",
    connection_options = {
        "path": "s3://the-bucket/some-data-set"
    },
    format = "parquet"
)

The result is 12 Parquet files with an average size of about 3MB.
First of all, I don't get why Glue/Spark won't by default instead create a single file about 36MB large given that almost all consuming software (Presto/Athena, Spark) prefer a file size of about 100MB and not a pile of small files. If somebody has an insight here, I'd appreciate to hear about it.
But practically speaking I'm wondering if it is possible to make Glue/Spark produce a large file or at least larger files. Is that possible?

A: Using coalesce(1) will deteriorate the performance of Glue in the long run. While, it may work for small files, it will take ridiculously long amounts of time for larger files.
coalesce(1) makes only 1 spark executor to write the file which without coalesce() would have used all the spark executors to write the file.
Also, using coalesce(1) will have bigger cost. 1 executor running for long run time will have bigger cost than all executors running for fraction of the time taken by 1 executor.
Coalesce(1) took 4 hrs 48 minutes to process 1GB of Parquet Snappy Compressed Data.
Coalesce(9) took 48 minutes for the same.
No Coalesce() did the same job in 25 minutes.

A: I haven't tried yet. But you can set accumulator_size in write_from_options.
Check https://github.com/awslabs/aws-glue-libs/blob/master/awsglue/context.py for how to pass value.
Alternatively, you can use pyspark DF with 1 partition before write in order to make sure it writes to one file only.
df.coalesce(1).write.format('parquet').save('s3://the-bucket/some-data-set')

Note that writing to 1 file will not take advantage of parallel writing and hence will increase time to write.

A: You could try repartition(1) before writing the dynamic dataframe to S3. Refer here  to understand why coalesce(1) is a bad choice for merging. It might also cause Out Of Memory(OOM) exceptions if a single node cannot hold all the data to be written.

A:
I don't get why Glue/Spark won't by default instead create a single file about 36MB large given that almost all consuming software (Presto/Athena, Spark) prefer a file size of about 100MB and not a pile of small files.

The number of the output files is directly linked to the number of partitions. Spark cannot assume a default size for output files as it is application depended. The only way you control the size of output files is to act on your partitions numbers.

I'm wondering if it is possible to make Glue/Spark produce a large file or at least larger files. Is that possible?

Yes, it is possible but there is no rule of thumb. You have to try different settings according to your data.
If you are using AWS Glue API [1], you can control how to group small files into a single partition while you read data:
glueContext.write_dynamic_frame.from_options(
frame = someDateFrame,
connection_type = "s3",
connection_options = {
    "path": "s3://the-bucket/some-data-set",
    "groupFiles": "inPartition",
    "groupSize": "10485760" # 10485760 bytes (10 MB)
}
format = "parquet"

)
If your transformation code does not impact too much the data distribution (not filtering, not joining, etc), you should expect the output file to have almost the same size as the read in input (not considering compression rate)  In general, Spark transformations are pretty complex with joins, aggregates, filtering. This changes the data distribution and number of final partitions.
In this case, you should use either coalesce() or repartition() to control the number of partitions you expect.
[1] https://aws.amazon.com/premiumsupport/knowledge-center/glue-job-output-large-files/


text:
Q: Unlogged table in postgres in hot standby database we have a pair of posgresql 9.1 servers operating in streaming replication mode. In each of these server there are 2 databases.
One is a "live" database which has data that must be replicated as close to realtime as possible and one is a "cache" database that has data that is not important and can be regenerated or built up over a period of time.
The "cache" database uses unlogged tables for everything (since we don't care if they get truncated) and we effectively use it as a kind of in-memory database. It works exceptionally well since we have lots of read/writes to these tables. We seen dramatic performance increases on servers with high load and lots of memory using the unlogged tables.
The problem now comes in when we have to create another "cache" database on the slave side. We need this for our web application to work properly. Of source with the database being in read-only mode this is not possible...
Just wondering if anyone else has a similar issue or if there is a way to create an unlogged table on the slave server? Streaming replication seems to be "all or nothing" in postgres and you can't turn it on/off for a particular database.
Perhaps I'm using unlogged tables incorrectly, but so far haven't managed to find anything that works as well as they do.
Any pointers would be much appreciated...

A:
Streaming replication seems to be "all or nothing" in postgres and you can't turn it on/off for a particular database.

Unfortunately, this is correct. WAL replication is for an entire database cluster, and you're asking a database inside the cluster on the master to not be logged, so there's no way to make it appear on the slave.
The best solution I have found is to run a second daemon / cluster on the slave and create the unlogged cache database there. There's no real problem with running multiple daemons of postgres at the same time - you'll just need to make sure you specify a different socket / port for it to listen on.


text:
Q: mongodb mongoose ignore current user from query I'm working on the Edit User Profile page of my website. When a user edits their username and presses save, I want to first check and see if any other users have this username first.
User.findOne({'username' : newUsername }, function(err, user){
    if (!user){ //no user exists with this name
        //code for changing current user's name to newUsername
    } else { //a user exists with this name
        //code for returning to the edit page, and displaying error message to user
    }
});

The problem is when I leave username the same (and edit a different value, like email). It pulls up my document on mongodb when it queries username, and therefore it doesn't change anything (because user exists!). How can I leave a specific document out of the query entirely?

A: If I understand correctly, you want to abstract your method so that it can be used to change any profile property and not just username?
What you can do is create the query map dynamically based on what field the user is changing.
For example, if your user wants to change their email field:
(req.query.type == what field user is trying to change)
(req.query.value == value of field the user is trying to change to)
var query = {};

switch(req.query.type)  // Type is username, email, any profile field
{
case 'username':
    query['username'] = req.query.value  // value of the profile field
    break;
case 'email':
    query['email] = req.query.value
    break;
default:
    break;
}

User.findOne(query, function(err, user) {  // Query will differ depending on inputs
    if (!user) { //no user exists with the type
        //code for changing current user's info
    } else { //a user exists with this name
        //code for returning to the edit page, and displaying error message to user
    }
});


text:
Q: Delete lines in richtextbox that fall under the condition Using this link http://www.yellowpages.ca/search/?stype=si&what=sh&where=Ottawa,+ON&x=0&y=0 and telling HtmlAgilityPack to retrieve both address and place name at the same time ("//span[@class='listingTitle']|//div[@class='address']/text()[normalize-space(.)]"), I can get a list of placenames and addresses like this in a richtextbox:

*

*jh ryder machinery limited

*convenience storage ltd 3344 rideau

*rd, gloucester,  on,  k1g3n4

*kitchen interiors 146 colonnade rd,

*nepean,  on,  k2e7y1

The first line is bad, it doesnt have an address. Line 2 and 4 are good, they have addresses. So what I could do is:
Check each line,
if the following line doesnt contain "numbers + ON" then delete line.
This will leave me with PlaceNames followed by addresses, which I will then split every other line into a new textbox, (so I have one textbox with placenames, and another with addresses).
I hope I made myself clear.
-Dd,

A: I think you could also add a condition in the Xpath to check if text " ON," is there. So, the list is pre-filtered.


text:
Q: Order of Observer notification with notifyObservers() I have this following code:
public class MyObservable extends Observable {
    // ...
    public void doSomething() {
        // do stuff
        setChanged();
        notifyObservers();
    }
}

public class A implements Observer {
    public void update(Observable o, Object arg) {
        // do something
    }
}

public class B implements Observer {
    public void update(Observable o, Object arg) {
        // do something
    }
}

And the main function:
public static void main(String[] args) {
    MyOvervable a = new MyObservable();
    a.addObserver(new A());
    a.addOberser(new B());
    a.doSomething();
}

Is the order the update functions are called by notifyObservers() the same order as I added the observers with addObserver()?

A: Javadoc for Observable says that notification is in the order listeners were registered, however this is incorrect - notification is actually made in reverse order.
Code excerpts with explanatory comments:
// addObserver() adds last-most at end of the list
public synchronized void addObserver(Observer o) {
    ..
    obs.addElement(o);
}

public void notifyObservers(Object arg) {
    ..
    // notifyObservers iterates backwards; last-most first.
    for (int i = arrLocal.length-1; i>=0; i--)
        ((Observer)arrLocal[i]).update(this, arg);
}

I filed a bug report -- https://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8214760 -- however due to Observable being deprecated, it has been closed as 'will not fix'.
My belief is that the behavior as implemented is stable and will not change; changing the order would probably break compatibility for many applications that use this.

A: Yes it is. Here's an excerpt from java java.util.Observable class.
private Vector<Observer> obs;

arrLocal = obs.toArray();

for (int i = arrLocal.length-1; i>=0; i--)
    ((Observer)arrLocal[i]).update(this, arg);

Vector is index based and backed up by an array internally. Vector maintains the insertion order of element. Means you can assume that you will get the object in the order you have inserted if you iterate over a Vector.
So the answer to your question is: YES

A: According to Oracle's docs:

The order in which notifications will be delivered is unspecified. The default implementation provided in the Observable class will notify Observers in the order in which they registered interest, but subclasses may change this order, use no guaranteed order, deliver notifications on separate threads, or may guarantee that their subclass follows this order, as they choose.


text:
Q: How can I achieve an inclined looking path in flutter (taking this picture as example) Path I am trying to achieve

I had been trying to achieve this path, but I am having trouble when clipping, not only it clips the opposite part of the container but also gets my path to be dirty.
I am also looking on achieving the same effect, but with an opposite direction.
This is the code i have done so far(It is an up arc clip path):
class UpArcClip extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    final path = Path();
    path.lineTo(0, size.height);
    path.lineTo(0.0, size.height - 100);
    path.quadraticBezierTo(
        size.width / 2, size.height, size.width, size.height - 100);
    path.lineTo(size.width, 0.0);
    path.close();
    return path;
  }

  @override
  bool shouldReclip(CustomClipper old) => false;
}

A: Already achieved it by myself:
class LeftInclinedArcClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    final path = Path();
    path.moveTo(0, size.height);
    path.lineTo(0, size.height * 0.7);
    path.quadraticBezierTo(
        size.width / 3, size.height * 0.45, size.width, size.height * 0.53);
    path.lineTo(size.width, size.height);
    path.close();
    return path;
  }

  @override
  bool shouldReclip(CustomClipper old) => false;
}


text:
Q: AWK: new column not aligning properly Using awk to create a new column of data in a text file after the last column. My last column is mostly IP addresses but could be some text lines and looks like this:
192.168.50.25
192.168.111.145
Unknown

The command I am using to create the new column is:
 grep '102548' file | awk -v OFS='\t' '{print $0, "2018-10-22"}'

I am grepping for 102548 because I only want awk to work on the lines containing that string. Here is my output from the command:
192.168.50.25   2018-10-22
192.168.111.145         2018-10-22
Unknown         2018-10-22
172.16.15.145           2018-10-22

It seems to be no rhyme or reason as far as whats in the left column, but the new column layout, although not aligned and random, always takes this format
  2018-10-22
          2018-10-22
          2018-10-22
  2018-10-22
          2018-10-22

So it seems the "overlap" is always the same. How can I construct my command so that I always get this kind of separation?
 192.168.50.25        2018-10-22
 192.168.111.145      2018-10-22
 Unknown              2018-10-22
 172.16.15.145        2018-10-22

A: The text on some lines in your first column extends past the first tabstop and, on other lines, it doesn't.
If you want things lined up in a visually nice way, try column -t:
$ awk '{print $0, "2018-10-22"}' file | column -t
192.168.50.25    2018-10-22
192.168.111.145  2018-10-22
Unknown          2018-10-22

The above lines up columns based on any whitespace.  If you want only tabs to separate columns (meaning that a column can include blanks), then try:
$ awk '{print $0, "2018-10-22"}' OFS='\t' file | column -s$'\t' -t
192.168.50.25    2018-10-22
192.168.111.145  2018-10-22
Unknown          2018-10-22


text:
Q: Sort selected contacts as ordered in admin It's possible to sort contacts when using the contact selection content type in SULU Admin.
However, I found no reference or example how the set order can be used in the respective display-loop.
How can I get the contacts in the set order?


text:
Q: shortest digest of a string [Description]
Given a string of char type, find a shortest digest, which is defined as: a shortest sub-string which contains all the characters in the original string.
[Example]
A = "aaabedacd"
B = "bedac" is the answer.
[My solution]

*

*Define an integer table with 256 elements, which is used to record the occurring times for each kind of character in the current sub-string.

*Scan the whole string, statistic the total kinds of character in the given string by using the above table.

*Use two pointers, start, end, which are initially pointing to the start and (start + 1) of the given string. The current kinds of character is 1.

*Expand sub-string[start, end) at the end until it contains all kinds of character. Update the shortest digest if possible.

*Contract sub-string[start, end] at the start by one character each time, try to restore its digest property if necessary by step 4.
The time cost is O(n), and the extra space cost is constant.
Any better solution without extra space?

A: That works very poorly, when you consider the fact that characters are not in fact limited to 256; there are closer to 2^32 codepoints in Unicode; and if you try what you are planning on an UTF-8 string, it is going to blow up. In a big way.
A better approach would be to use a digest algorithm like MD5 or FNV, or doing what you are doing, but rather with a linked list sparse array; adding the codepoints of the characters as you encounter them, and concatenating the codepoints afterwards, converting to, say, UTF-8 as you go.
EDIT:
Counterexample: "På japansk heter regn '雨'."

A: I don't think your algorithm is correct. Consider the string: "baaabedacdc". The correct answer is still "bedac", but your algorithm will advance the start pointer forward until it finds the "e" (the only character with an occurrence count of 1), and then the end pointer backward until it finds the "e" (the only character with an occurrence count of 1), for a result of "e".
I may have misunderstood the algorithm, though.

A: Why not use a simpler algorithm for this question, may not be most time efficient, but it works ;) :
step 1. (Asssuming we are dealing with character set of 26 alphabets), create a boolean array of size 26 and scan through the string and check the boolean corresponding to the character. For instance, set elem[0] = true when you run into a, elem[1] = true when you run into b etc.
step 2. create a string using the characters where elem[x] = true. so, the string for this case would be "abcde" and its length = 5.
step 3. traverse through the given string a second time while extracting sub-strings of length 5, sorting them in ascending order and matching them with the string from step 2.


text:
Q: Blocking button click signals in PyQt I have a program that uses pyqt's .animateClick() feature to show the user a sequence of different button clicks that the user has to copy in that specific order. The problem is I don't want the animateClick() to send a signal, I only want the button click signals from the user. Here is some of my code to demonstrate what I mean, and how I tried to solve that problem (that doesn't work). I simplified my code quite a bit so its easier to read, let me know if you have any questions.
from PyQt4 import QtCore,QtGui
global flag
global ai_states
ai_states = []
user_states = []

class Program(object):
    # Set up the push buttons
    #Code Here.

    # Connect push buttons to function get_state()
    self.pushButton.clicked.connect(self.get_state)
    self.pushButton_2.clicked.connect(self.get_state)
    self.pushButton_3.clicked.connect(self.get_state)
    self.pushButton_4.clicked.connect(self.get_state)

    # Code that starts the start() function

    def start(self):
        flag = 0
        ai_states[:] = []
        i = -1
        # Code here that generates ai_states, numbers 1-4, in any order, based on button numbers.

        for k in ai_states:
            i = i + 1
            # Code here that animates button clicks determined by ai_states

            # Changes the flag to 1 once the loop ends
            if i == len(ai_states):
                flag = 1

    def get_state(self):
        if flag == 1:
            user_states.append(str(self.centralWidget.sender().text()))
        else:
            pass

        if len(user_states) == len(ai_states):
            # Checks to make sure the user inputted the same clicks as the ai_states

Even though the flag does come out to be 1 after the start() function, it is still appending the animatedClick() signals. What am I doing wrong? I'm new to GUI programming, so I'm probably going about this in a very bad way. Any help would be appreciated.

A: Never use global variables unless you really have to. If you need shared access to variables, use instance attributes:
from PyQt4 import QtCore,QtGui

class Program(object):
    def __init__(self):
        self.ai_states = []
        self.user_states = []
        self.flag = 1

        # Set up the push buttons
        # Code Here

        # Connect push buttons to function get_state()
        self.pushButton.clicked.connect(self.get_state)
        self.pushButton_2.clicked.connect(self.get_state)
        self.pushButton_3.clicked.connect(self.get_state)
        self.pushButton_4.clicked.connect(self.get_state)

    # Code that starts the start() function

    def start(self):
        self.flag = 0
        del self.ai_states[:]
        i = -1
        # Code here that generates ai_states, numbers 1-4, in any order, based on button numbers.

        for k in self.ai_states:
            i = i + 1
            # Code here that animates button clicks determined by ai_states

        # Changes the flag to 1 once the loop ends
        self.flag = 1

    def get_state(self):
        if self.flag == 1:
            self.user_states.append(str(self.centralWidget.sender().text()))

        if len(self.user_states) == len(self.ai_states):
            # Checks to make sure the user inputted the same clicks as the ai_states


text:
Q: Display a newly created thumbnail without saving first? I am testing a thumbnail image creator script which creates a thumbnail that can be displayed in the web browser without saving it first.
Currently I have to use the following code to display the image:
include('image.inc.php');

    header('Content-Type: image/png');
    create_thumbnail('me.jpg', false, 200, 200);

But how can I display the dynamically generated thumbnail image on a standard webpage along side html mark-up?
create_thumbnail function:
function create_thumbnail($path, $save, $width, $height){

    // Get the width[0] and height[1] of image in an array
    $info = getimagesize($path);

    // Create a new array that just contains the width and height
    $size = array($info[0], $info[1]);

    // Check what file type the image is
    if($info['mime'] == 'image/png'){

        $src = imagecreatefrompng($path);

    }else if($info['mime'] == 'image/jpeg'){

        $src = imagecreatefromjpeg($path);

    }else if($info['mime'] == 'image/gif'){

        $src = imagecreatefromgif($path);

    }else{
        // If it isn't a good file type don't do anything
        return false;
    }

    // Create a thumbnail with the passed dimensions
    $thumb = imagecreatetruecolor($width, $height);

    $src_aspect = $size[0] / $size[1];

    $thumb_aspect = $width / $height;

    if($src_aspect < $thumb_aspect){

        // Image is tall
        $scale = $width / $size[0];
        $new_size = array($width, $width / $src_aspect);
        $src_pos = array(0, ($size[1] * $scale - $height) / $scale / 2);
    }else if($src_aspect > $thumb_aspect){

        // Image is wide
        $scale = $height / $size[1];
        $new_size = array($height * $src_aspect, $height);
        $src_pos = array(($size[0] * $scale - $width) / $scale /2, 0);

    }else{

        // Image is square
        $new_size = array($width, $height);
        $src_pos = array(0, 0);
    }

    // Stop the new dimensions being less than 1 (this stops it breaking the code). Takes which ever value is higher.
    $new_size[0] = max($new_size[0], 1);
    $new_size[1] = max($new_size[1], 1);

    // Copy the image into the new thumbnail
    // Newly created thumbnail, image copying from, starting x-coord of thumbnail, starting y-coord of thumbnail(0,0 will fill up entire thumbnail), x-coord of original image, y-coord of original image,  width of new thumbnail, height of new thumbnail, width of original image, height of original image
    imagecopyresampled($thumb, $src, 0, 0, $src_pos[0], $src_pos[1], $new_size[0], $new_size[1], $size[0], $size[1]);

    if($save === false){
        return imagepng($thumb);
    }else{

    // Create the png image and save it to passed location
    return imagepng($thumb, $save);
    }

A: If I understand your question correctly, you just need to insert an img tag and set its src attribute to your php script.
Something like:

A: Convert it to base64 (using base64_encode) and then display it with: