text:
Q: jquery Validation is not working for validate dates I am modifying an existing project, where I want to validate the start date(From) and end date(To) using jquery. The requirement is that End date(To) cannot be less than the Start date(from). Below is my html code and I add the jquery code I've written. But the date is not validated and it doesn't display any error message. Once I click the submit button it submit successfully without any error. I refer the following question to write the jquery part, but does not work. I really appreciate if some one can help me to resolve this. Thanks in advance.
Using jquery Validation 'greaterthan' function

var validator = $("#add_cetificate").validate();

$("#valid_to").rules('add', { greaterThan: "#valid_from" });

 $.validator.addMethod('greaterThan', function(value, element, param){
        var startDate =  $(param).val();
         var endDate = value ;
        return endDate > startDate;

 });

    Valid From *

        <input type="text" class="form-control datepicker" name="valid_from[]" id="valid_from" required="required">

     To  *

        <input type="text" class="form-control datepicker" name="valid_to[]" id="valid_to" required="required">


text:
Q: Selenium WebDriver issues with Material UI select fields (dropdown list) Hi I need to access to a Select Field component from the Material UI library. I'm using the traditional way but as expected is throwing an error because this library generates div elements instead of select.
Please any idea of how to select elements with this component?
WebSite Url: http://www.material-ui.com/#/components/select-field
Error: "org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "div".
The code I used is the follow:
public class MaterialUITest {

private WebDriver driver;
By selectFieldLocator = By.xpath("//div[contains(@id,'undefined-undefined-Frequency')]/div[1]/div[2]");

@Before
public void setUp() throws Exception {
    System.setProperty("webdriver.chrome.driver", "./src/test/resources/drivers/chromedriver.exe");
    driver = new ChromeDriver();
    driver.get("http://www.material-ui.com/#/components/select-field");
}
@After
public void tearDown() throws Exception {
}
@Test
public void test() {
    WebElement selectField = driver.findElement(selectFieldLocator);
    Select dropdown = new Select(selectField);
    dropdown.selectByVisibleText("Weekly");
    WebElement option = dropdown.getFirstSelectedOption();
    System.out.println(option.getText());
}
}

A: As I understand problem that you're having is not related to material itself it's more related to custom implementation of select, i.e. this is not select, you should treat this 'select' as regular web element and handle it respectively in other words you need to click on it to expand and then perform another click on required element to select it.

A: Inspect element and copy full xpath.
Try with Full xpath it will work you need take the xpath of full tab because  inner elements are not enabled because of parent elements.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there forward declaration of function in shell script -bash
Possible Duplicate:
Forward declarations in bash?

I have lot many functions in a shell script source file in which one calls other so Always I have to place the functions in the correct order.
Isn't there any thing like forward declaration of function in shell script as we have in C/C++ ?
EDIT : Or, is there any way to implement it ?


text:
Q: Handsontable Customize Existing Context Menu Items I am trying to customise a pre-existing handsontable context menu item.
Specifically I would like to add a password prompt to to the 'Read only' option in the context menu so only authorized users can modify the data in the table. I have developed the following code for the customizing the context menu as follows:
hot.updateSettings({
  contextMenu: {
    items:  {
            "make_read_only": {
              //how to I keep the exisiting functionality but add a
              //password prompt?
            }
          }
  }
});


text:
Q: Process Start Did Not Work I have a windows service which is writing in C#.
When I start debug the program it is working without any problem. But if I publish it does not work and I am not getting any error in my log file or eventviwer.
I checked the UAC to never notify.
Also my code is like this:
using (Process tvProcess = new Process())
{
   tvProcess.StartInfo.WorkingDirectory = installationPath;
   tvProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
   tvProcess.StartInfo.UseShellExecute = true;
   tvProcess.StartInfo.FileName = TVAppFileName;

   bool started = tvProcess.Start();
   tvProcess.WaitForInputIdle();
   Logger.TraceFormat("TV - TV was started from the path {0}. Status : {1}",
       System.IO.Path.Combine(installationPath, TVAppFileName),
       started);
}

Also my installationPath = @"C:\Program Files (x86)\TeamViewer\Version8\"
TVAppFileName = "TeamViewer.exe"
How can I start this process without debug?
Thanks


text:
Q: Tornado: how to dispatch different requests to a same class I'm using Tornado to build a web server. I need to dispatch different requests into a same class. Here is an example:
application.add_handlers(r"^(example).*", [
(r"/(mark)/(auth)"), MarkHandler,
(r"/(mark)"), MarkHandler,
])

And the class MarkHandler:
class MarkHandler(tornado.web.RequestHandler):
    def get(self, mark):   # /(mark)
        print('1111')

    def get(self, mark, auth):    # /(mark)/(auth)
        print('2222')

However, it doesn't seem to work...
When I visit the link: www.example.com/mark, the server gives me an error:

TypeError: get() missing 1 required positional argument: 'auth'

What I need as above is impossible?

A: Python doesn't allow method overloading the way C++ or Java does. Defining the same method get twice in Python simply overwrites the first method with the second one.
Instead, you want a default value for the second argument:
class MarkHandler(tornado.web.RequestHandler):
    def get(self, mark, auth=None):
        if auth is not None:
            print('2222')
        else:
            print('1111')


text:
Q: How to check whether a url has valid feeds in simplepie I want to check whether a  url contains feeds or not with simplepie, before saving the root url for further purpose.
I have already tried :
if ($feed->error()){
//Its not working
}

and validatefeed() is of no use as it checks the url strictly.
I am using 1.3.1 version of simplepie.


text:
Q: Implementing Factory Pattern and Gettingt NullPointerException, unable to figure out can somebody help me to fix I am posting this code in which I implemented factory method,Code is compiled successfully but null pointer exception occurs at run time and I am unable to figure it out, I know when an object reference points to nothing then this Exception occurs but in my case I am unable to figure out,Can somebody suggest me the fix here I am posting the code.
import java.util.Scanner;
abstract class Plan
{
 protected double rate;

public abstract void getRate();

public void calculateBill(int totalUnitsConsume)
{
    System.out.println(totalUnitsConsume*rate);
}

}

  class DomesticPlan extends Plan
  {
   public void getRate()
   {
    rate=3.5;
    }
  }

 class CommercialPlan extends Plan
 {
public void getRate()
 {
 rate=7.50;
 }

 }

class InstitutionalPlan extends Plan
 {
 public void getRate()
 {
  rate=5.50;
  }

  }

 class PlanFactory
 {
  public static Plan getPlan(String planType)
  {
  if(planType==null)
 {
  return null;
  }

   if (planType.equalsIgnoreCase("DOMESTIC PLAN"))
  {
   return new DomesticPlan();
  }
   else if(planType.equalsIgnoreCase("COMMERCIAL PLAN"))
    {
     return new CommercialPlan();
      }
       else if (planType.equalsIgnoreCase("INSTITUTION PLAN"))
        {
        return new InstitutionalPlan();
          }

     return null;

    }
    }

    public class ElectricityBill
    {
       public static void main(String ... qwe)
     {

     int choice;
    System.out.println("Choose The Plan type");
    System.out.println("1.Domestic Plan");
    System.out.println("2.Commercial Plan");
    System.out.println("3.Institution Plan");

    Scanner sc=new Scanner(System.in);

    choice=sc.nextInt();
    if(choice>3)
    {
      System.out.println("Wrong choice entered");
    }
    else
    {
     System.out.println("You chose Plan no.:"+ choice);
    }
     switch(choice)
    {
    case 1 : Plan p=PlanFactory.getPlan("DomesticPlan");
             p.getRate();
             p.calculateBill(100);
             break;

   case 2 : Plan p2=PlanFactory.getPlan("CommercialPlan");
            p2.getRate();
            p2.calculateBill(300);
            break;

   case 3 : Plan p3=PlanFactory.getPlan("InstitutionalPlan");
            p3.getRate();
            p3.calculateBill(250);
            break;
  default : System.out.println("May be you entered wrong choice");
       }

       }
       }
 Output

 I:\Data>java ElectricityBill
 Choose The Plan type
 1.Domestic Plan
 2.Commercial Plan
 3.Institution Plan
 1
 You chose Plan no.:1
 Exception in thread "main" java.lang.NullPointerException
    at ElectricityBill.main(ElectricityBill.java:96)

A: 51. planType.equalsIgnoreCase("DOMESTIC PLAN")
...
96. PlanFactory.getPlan("DomesticPlan")

Here none of the if...else block is getting executed, thus getPlan is returning null.
Please change "DomesticPlan" to "DOMESTIC PLAN" in line 96

A: You missed a space inside 'DomesticPlanin your code, so your factory can not match any string and returns null, just correct it toDomestic Plan`

A: It's because your factory is not returning a plan in that case.  You are doing PlanFactory.getPlan("DomesticPlan") (no space in DomesticPlan) but within your getPlan method you are looking for "DOMESTIC PLAN" (with space) and therefore Plan p is null.  The exception is thrown immediately after, where you are calling the getRate method on the null Plan.
You should null-check when you get a value from the factory, e.g. if (p != null) { p.getRate(); ... }


text:
Q: Yasg schema generation for nested serializer shows incorrect requests/responses I have a Django API and I try to create the documentation with drf-yasg. I'm having trouble with the automatically generated schema for my nested serializer and ListAPIview. It looks like this:
serializers.py
class SlideDataSerializer(serializers.ModelSerializer):
    description = SlideDataDescriptionSerializer(many=True, read_only=True, source='slidedatadescription_set')
    class Meta:
        model = SlideData
        fields = ['catch', 'title', 'description', 'icon']

class SlideSerializer(serializers.ModelSerializer):
    datas = SlideDataSerializer(many=True, read_only=True, source='slidedata_set')
    class Meta:
        model = Slide
        fields = ['datas']

class PlanDataDescriptionSerializer(serializers.ModelSerializer):
    class Meta:
        model = PlanDataDescription
        fields = ['description']

class PlanDataSerializer(serializers.ModelSerializer):
    description = PlanDataDescriptionSerializer(many=True, read_only=True, source='plandatadescription_set')
    class Meta:
        model = PlanData
        fields = ['stripColor', 'name', 'description', 'pricePerMonth', 'currency', 'picture']

class PlanSerializer(serializers.ModelSerializer):
    datas = PlanDataSerializer(many=True, read_only=True, source='plandata_set')
    class Meta:
        model = Plan
        fields = ['mainTitle', 'datas']

views.py
class ProjectList(generics.ListAPIView):
    permission_classes = [permissions.AllowAny]
    serializer_class_slide = SlideSerializer
    serializer_class_plan = PlanSerializer

    def get_queryset_object(self, Table, campaign, lang):
        queryset = Table.objects.filter(campaign__name=campaign).filter(language__alpha2=lang)
        return queryset[0]

    def list(self, request):
        Tables = [Slide,
                Plan]

        campaign = self.request.query_params.get('campaign') or "default"
        lang = self.request.query_params.get('lang') or "en"

        if not all(Table.objects.filter(campaign__name=campaign).filter(language__alpha2=lang) for Table in Tables):
            campaign = "default"

        if not all(Table.objects.filter(campaign__name=campaign).filter(language__alpha2=lang) for Table in Tables):
            lang = "en"

        slides = self.serializer_class_slide(self.get_queryset_object(Slide, campaign, lang))
        plans = self.serializer_class_plan(self.get_queryset_object(Plan, campaign, lang))

        return Response({
            "slides": slides.data,
            "plans": plans.data,
        })

and the urls.py:
openapi_info = openapi.Info(
        title="Projectname",
        default_version="v1",
        description="Endpoints",
        terms_of_service="TBD",
        contact=openapi.Contact(email="abc@123.com"),
        license=openapi.License(name="BSD License"),
    )

schema_view = get_schema_view(
    openapi_info,
    public=True,
    permission_classes=(permissions.AllowAny,),
)

API_VERSION = 'v1'
urlpatterns = [
    path('swagger/', schema_view.with_ui(
        'swagger', cache_timeout=0), name='schema-swagger-ui'),
    path('swagger/api.json', schema_view.without_ui( cache_timeout=0), name='schema-swagger-json'),
]

The endpoint is working fine but swagger does not create the right requests or responses and when I access it it gives me this error message:
view's ProjectList raised exception during schema generation; use `getattr(self, 'swagger_fake_view', False)` to detect and short-circuit this
Traceback (most recent call last):
  File "/home/projects/env/lib/python3.8/site-packages/drf_yasg/inspectors/base.py", line 42, in call_view_method
    return view_method()
  File "/home/projects/env/lib/python3.8/site-packages/rest_framework/generics.py", line 108, in get_serializer
    serializer_class = self.get_serializer_class()
  File "/home/projects/env/lib/python3.8/site-packages/rest_framework/generics.py", line 122, in get_serializer_class
    assert self.serializer_class is not None, (
AssertionError: 'ProjectList' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method.

I can not include a serializer class name because I use multiple serializers, I can not create a single serializer for this because they are split up over different models. Overriding the get_serializer_class() has not worked because I don't know how to incorporate these serializers there neither. How could I make this representation work? Thanks in advance

A: it is because you didn't add your class's Serializer . those serializers you added aren't built in ones . simply add
serializer_class = SlideSerializer

to your class variables even if you don't want to use that . as in error mentioned , you need to add a serializer_class to your ListAPIView .


text:
Q: MouseListener is not working My Mouse Released is not working.
In my code there are two JPanels(p1 and p2) in another JPanel(p).
and there are two Buttons named RED and GREEN. My Code should work like when someone click the Buttons, The Panels should be changed Dynamically .
But unfortunately When I am running my program, the Button "RED" and "GREEN" is not responding. Here I have Added my codes.
Thank you.
package animat;

import java.awt.Color;
import java.awt.event.*;

import javax.swing.*;

public class Animat extends JFrame{

Animat(){

JFrame j=new JFrame();

j.setSize(400,400);
j.setVisible(true);
JPanel p=new JPanel();

p.setSize(300,400);
p.setLayout(null);
p.setBackground(Color.BLACK);
p.setVisible(true);
j.add(p);

JPanel p1=new JPanel();
p1.setBounds(0,50,400,350);
p1.setBackground(Color.red);
p1.setVisible(true);
p.add(p1);

JPanel p2=new JPanel();
p2.setBounds(0,50,400,350);
p2.setBackground(Color.GREEN);
p2.setVisible(true);
p.add(p2);

JButton b=new JButton("RED");
b.setBounds(0,0,100,50);
b.setVisible(true);
p.add(b);

JButton b1=new JButton("GREEN");
b1.setBounds(100,0,100,50);
b1.setVisible(true);
p.add(b1);

b.addMouseListener(new MouseAdapter(){
public void MouseReleased(MouseEvent e){
p.removeAll();
p.repaint();
p.revalidate();
p.add(p1);
}
});

b1.addMouseListener(new MouseAdapter(){
public void MouseReleased(MouseEvent e){
p.removeAll();
p.repaint();
p.revalidate();
p.add(p2);
}
});
}
public static void main(String[] args) {
   new Animat();
   }

}

A: You are - by accident - not overriding the function you meant to.
With this code:
b1.addMouseListener(new MouseAdapter(){
   public void MouseReleased(MouseEvent e){
      p.removeAll();
      p.repaint();
      p.revalidate();
      p.add(p2);
   }
});

You are adding a new function, instead of overriding the mouseReleased function. Hence it is never called. Just change the function-name to start with lower-case and it will work.
Note #1: You can verify my statement below by adding the @Override annotation to your function. You will be told by your IDE that you are in fact not overriding anything (due to the typo)
Note #2: You should be probably using mousePressed instead. It is more logical in this case (but your code works as well)


text:
Q: xxx.cmi is not a compiled interface for this version of OCaml There is two files a.cmo and a.cmi which are compiled by ocaml 4.13.1.
I write a file test.ml which only contains one line code: open A
Now, I want to use command: ocamlc -o test.exe a.cmo test.ml to compile the test.ml in the ocaml 4.14.0 environment(cygwin), and I got an error: a.cmi is not a compiled interface for this version of OCaml, I know this error is caused by ocaml version.But I want to know :
Is there any way to compile to get the a.cmo and a.cmi file independent of the ocaml version? In other words, how can I compile the test.ml file linked with a.cmo file and don't need to consider who uses which ocaml version to compile to get this a.cmo?
Does such a method exist? Or do I have to change the version of ocaml?

A: The compiled artifacts of the OCaml compiler are versioned to avoid consistency issues and cross-version bugs. By design, there is no way around this security net.


text:
Q: React hooks keyboard navigation I'm trying to implement keyboard navigation for a list using react-hooks.
important - This list can shrink/grow based on a search.
My issue is around the Enter key which should run some callback.
The activeCursor does not change, which I understand since its not in the useEffect array, but how can I get the current state inside handleKeyPress without having to re-run useEffect ?
Also, I would ideally want to run my useEffect only on mount ([]) but since the filteredMessages changes I must re-call it, which is also something I find strange since its eventListeners so I'm not even sure what happens to them each time...
    const useKeyboardNavigation = (filteredMessages, onMessageSelection) => {
        const [activeCursor, setActiveCursor] = React.useState(0);
        const size = filteredMessages.length

        const handleKeyPress = (event) => {
            if (event.key === 'ArrowDown') {
                setActiveCursor(prev => prev < size ? prev + 1 : 0)
            }
            else if (event.key === 'ArrowUp') {
                setActiveCursor(prev => prev > 0 ? prev - 1 : size)
            }
            else if (event.key === 'Enter') {
                const msg = filteredMessages[activeCursor] // ??? Always 0
                onMessageSelection(msg)
            }
        };

        React.useEffect(
            () => {
                // Each time the list changes I reset the cursor
                setActiveCursor(0)

                document.addEventListener('keydown', handleKeyPress);

                return () => document.removeEventListener('keydown', handleKeyPress);
            },
            [filteredMessages]
        );

        return [activeCursor, setActiveCursor];

    }

A: Going to post my solution, ended up using a mixture of state and refs. Would still be open to hearing a solution with better performance for large lists.
const useKeyboardNavigation = (size: number) => {
    const [activeCursor, setActiveCursor] = React.useState(0);

    const handleKeyPress = event => {
        if (event.key === 'ArrowDown') {
            setActiveCursor(prev => (prev < size ? prev + 1 : 0));
        } else if (event.key === 'ArrowUp') {
            setActiveCursor(prev => (prev > 0 ? prev - 1 : size));
        }
    };

    // Reset when size changes
    React.useEffect(() => setActiveCursor(0), [size]);

    React.useEffect(
        () => {
            document.addEventListener('keydown', handleKeyPress);

            return () => document.removeEventListener('keydown', handleKeyPress);
        },
        [size, activeCursor]
    );

    return [activeCursor, setActiveCursor];
};

Usage:
const [activeCursor, setActiveCursor] = useKeyboardNavigation(messages.length);

Then when I render each ListItem (using messages.map):

const useFocus = (isActive: boolean) => {
    const itemRef = React.useRef<HTMLDivElement>(null);

    React.useEffect(
        () => {
            isActive && itemRef && itemRef.current && itemRef.current.focus();
        },
        [isActive]
    );

    return itemRef;
};

Usage:
 const myRef = useFocus(activeCursor === index);
<li ref={myRef} ...>


text:
Q: Design question for handling large volumes of messages in multi-tenant queue I have a system with two applications interacting via a message queue.  Let's call them Producer and Consumer.  Some key context is that this a multi-tenancy scenario.
Producer produces events based on various inputs (user interactions, api, etc...) and Consumer does down stream processing on these.  One of our key constraints is that Consumer can only process events one-at-a-time-per-tenant.
Our current solution (a bit naive) is that multiple worker threads are pulling from the queue and processing events, and if a tenant has another event in progress later worker thread(s) just waits.  This has been fine for a couple years given our thread pools and typical event production patterns, but we had a scenario where thousands of events for a single tenant were generated in Producer, and all of Consumer's worker threads except one were stuck waiting.  Consumer was therefore processing events from the queue one at a time, and our "eventual consistency" lag time became suboptimal.
We've got some candidate ideas for managing this:

*

*Load balancing across queues - new messages go to the most empty queue, but tenants are locked to a single queue (how we achieve this exactly TBD)

*Create a "slow lane" queue - if during processing of an event, the tenant is already in use, move the events to the "slow lane".  This will drain the primary queue quickly but has implications for event processing idempotency I'm not sure will be valid for our scenario.

Before we start digging on these options and looking for others, I'm curious if anyone here has experience with patterns for dealing with this type of situation.
Appreciate any info/advice/guidance.  Thanks!!

A: This sounds like a variation of the 'process events in order' problem.
You can solve the ordering by having a queue per tenant, but with multiple workers you will also need an extra system to 'lock' queues.
Add a "worker.router" program which hands out work to the workers. When a new worker instance starts it contacts the router to say "hi i am ready for work" the router adds it to its list and sends back "please work on queue x". When the worker finishes a message it sends back "finished, please send more work" and the loop continues.
Because the router knows about the list of workers and the list of tenants, it can prevent two workers being assigned to the same queue and detect crashed workers.
You have some hoops to jump through to prevent the router being a single point of failure but its all solvable.
This is a variation of the general pattern where you have the router listen to a single queue and create worker queues for subscribed workers as required. It can hold a buffer of messages to allow reordering and prioritization.

A: This approach may be viable in scenarios where the message volume is relatively stable for a tenant.
Create N number of queues, start with say 5 queues, and allocate multiple tenants to a queue based on their volume of messages.
For example
500 tenants with a message volume of low       are assigned to queue 1.
200 tenants with a message volume of medium    are assigned to queue 2.
...
  5 tenants with a message volume of very high are assigned to queue 5.

If message distribution is such that each queue averages the same number of messages per tenant, it should even out your eventual consistency time lag.


text:
Q: Oracle with Entity framework I'm using Entity framework 5 with Oracle.ManagedDataAccess 19.11.0, and when i'm trying to add migration i'm getting this error :
    at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
    An error occurred while getting provider information from the database.
This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.

my connection string is  as below :
<add name="myDB" connectionString="Data Source=PAD;Persist Security Info=True;User ID=USRX;Password=XXXX;" />

please note that application works fine, only the add-migration that doesn't work .


text:
Q: Opencart 3.0 - how to add in-line javascript code from catalog controller with event system? How to add inline js code from controller ?
admin module controller
$this->model_setting_event
     ->addEvent("one_two_three","catalog/view/common/header/before","extension/module/oone_two_three/inject_abc_javascript");

and in catalog module controller
public function inject_abc_javascript(&$route, &$data){
    $code = $this->config->get("module_one_two_three_code");
    $data["scripts"] = "";
}

Is there any way to add inline javascript in OpenCart header?

A: Yes, you can do it.
First of all you have an error/typo in addEvent parameters, change oone_two_three to one_two_three.
Then you need a third parameter for your function:
public function inject_abc_javascript($route, &$data = false, &$output = false){
    // Before closing tag
    $hook = '';
    $js = '';
    $output = str_replace($hook, $js, $output);
}


text:
Q: What is the alternative to cursors to retrieve large amounts of data from a database? Searching through stackoverflow I found a large number of answers condemning the use of cursors in database programming. However I don't really understand what the alternative is.
I'm creating a program which reads a large number of rows (hundreds of thousands) from the database and keeps them in memory, for performance reasons. I can't really run a SELECT * FROM table and process all the results at once, can I?
The best way I have found is to use cursors and retrieve the rows in increments, for example 10 at a time.
Could someone enlighten me? I use PostgreSQL 9 on linux.
Thanks

A: A CURSOR is the best option when you have to deal with large amounts of data. You could also use the LIMIT .. OFFSET .. method, but this will get slower and slower, depending on the amount of data. PostgreSQL doesn't have any problems with cursors, use them when you handle large amounts of data.
SQL Server has/had problems with cursors, MySQL can't handle cursors outside stored functions, that might be the reason some dba's don't like cursors.

A: You can straightly use the for loop using record:
do
$$
declare r record;

begin

    for r in select product_id, name from products loop
        raise notice '% %', r.product_id, r.jname;
    end loop;

end$$

A: I suppose that the best way is to use COPY to get needed data directly to your client application.
I also did not have any problem when using cursors. I far as I understand, cursor is keeping a snapshot of data for you, and formally it (and COPY) is the only correct way to page through the results as otherwise when using LIMIT..OFFSET can lead to the inconsistencies, as the offset is changed by the newly inserted records.

A: Have a look at LIMIT and OFFSET

A: It should be rare to need a cursor. Maybe if your logic changes as each previous row is updated, then you may need a cursor.
Do you really need to open a cursor for your problem? Can you give the specifics of what you are trying to do? Large data sets are a good reason to avoid cursors, not a reason to use them.
You should try to do set-based processing. Just regular updates on the tables, with joins and where filters.
Can a simple update replace your cursor loop?

A: If you're just downloading data why not use select? You are not saving any memory by pulling 10 rows at a time because your caching it all in memory anyway.
Am I missing something?


text:
Q: Adding two tabs to text in R string I am replacing " o " with new line character, a carriage return and two tabs and the o. It works except I'm only getting one tab, why? How can I specify two tabs since \t\t does not work.
data.frame(lapply(dfClean[,selectCols], gsub, pattern = " o ", replacement = "\r\n\t\to ", perl = TRUE))


text:
Q: VBA - Replace with find one word in a specific cell works, how do I find one word or another? First I should apologize for my very limited VBA coding skills.  So the code I have basically does what I want it to do:  I have hundreds of Excel files I need to modify at a time repeatedly.  If a specific cell ("B1") has the word string "draw" in it, nothing is to happen.  If the cell doesn't have the word string "draw", the word "tank" is to be inserted before the word "prep" in the cell.  The macro runs through all the files in a given folder, changes the format, outputs to a new folder, etc.  This all works beautifully.  But on occasion, the cell may contain the word string "pool" instead of "draw".  In that case, I don't want to change the cell contents at all.  So basically, if "pool" or "draw" is in the cell, do nothing.  If they're both not present, add "Tank" before the word string "prep" in the cell.  Here's the code I have:
Sub SIS_ALIMS()

Dim wbOpen As Workbook
Dim MyDir As String
MyDir = "C:\Processed data"
strExtension = Dir(MyDir & "\*.xls")
While strExtension <> vbNullString
Set wbOpen = Workbooks.Open(MyDir & "\" & strExtension)
With wbOpen

Set rgFound = Range("B1").Find("draw", MatchCase:=False)

If rgFound Is Nothing Then

Range("B1").replace What:="prep", Replacement:="Tank prep"

Else

End If

Dim SaveName As String
    SaveName = ActiveSheet.Range("B8").Text
    ActiveWorkbook.SaveAs fileName:="C:\Processed data\ALIMS data\" & _
    SaveName & ".txt"

.Close SaveChanges:=False

End With
strExtension = Dir
Wend

Application.ScreenUpdating = True

End Sub

A: First an observation: Your code does not specify a worksheet in wbOpen, so you may run into problems if a workbook happens not to open on the worksheet you expect. Better to use something like With wbOpen.Sheets(1).
As for your question, instead of using Find you may find it easier to work with the cell value as a string variable:
Dim CellData As String

With wbOpen.Sheets(1)
    CellData = .Range("B1").Value

    If CellData = "draw" Or CellData = "pool" Then
        'do nothing

    ElseIf CellData = "prep" Then
        .Range("B1").Value = "Tank prep"

    Else
        'add other conditionals as needed

    End If

End With

Finally, if the VBA doesn't need to perform any action when the cell value is "draw" or "pool," then testing for those values is superfluous. The If ... End If block can be replaced with just the conditional that is of interest:
If .Range("B1").Value = "prep" Then .Range("B1").Value = "Tank prep"


text:
Q: Use editable div on multiple inputs I want to manipulate inputs, and for that I need to create editable divs that will replace them.

let exemplo = document.getElementById("exemplo");
exemplo.style.display = "none";

let editableDiv = document.createElement("divEditable");

editableDiv.contentEditable = true;
editableDiv.style.border = "1px solid black";
editableDiv.style.width = "300px";

exemplo.parentNode.insertBefore(editableDiv, exemplo.nextSibling);
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

      <input type="text" id="exemplo" style="width: 400px; height: 50px;">

From this div I'll do some manipulations. The problem is that I can only use this editable div only on one input, and I have MANY inputs.
How could I do it without polluting my code by creating multiple divs?

A: You can select all input using querySelectorAll() and the iterate and apply the same logic that you have used.

let inputs = [...document.querySelectorAll('input')];

inputs.forEach(el => {

  el.style.display = "none";

  let editableDiv = document.createElement("divEditable");
  editableDiv.contentEditable = true;
  editableDiv.style.border = "1px solid black";
  editableDiv.style.width = "300px";

  el.parentNode.insertBefore(editableDiv, el.nextSibling);
});
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

    <input type="text" style="width: 400px; height: 50px;">

    <input type="text" style="width: 400px; height: 50px;">

    <input type="text" style="width: 400px; height: 50px;">

    <input type="text" style="width: 400px; height: 50px;">

    <input type="text" style="width: 400px; height: 50px;">

A: You need grouped selector of input like
document.getElementsByClassName("exemplo");//is Array
//or
document.querySelectorAll(".exemplo");//is Array ('.' mean class)
//Need to change id="exemplo" --> class="exemplo"

or (Example on Nidhin Joseph's answer) by tag
x.getElementsByTagName("input"); //is Array
//or
document.querySelectorAll("input"); //is Array

let exemplo_list = document.getElementsByClassName("exemplo");

for (i = 0; i < exemplo_list.length; i++) {
  input_div(exemplo_list[i])
}

function input_div(exemplo) {
  exemplo.style.display = "none";

  let editableDiv = document.createElement("divEditable");

  editableDiv.contentEditable = true;
  editableDiv.style.border = "1px solid black";
  editableDiv.style.width = "300px";

  exemplo.parentNode.insertBefore(editableDiv, exemplo.nextSibling);
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

    input 1

    <input type="text" class="exemplo" style="width: 400px; height: 50px;">

 input 2

    <input type="text" class="exemplo" style="width: 400px; height: 50px;">


text:
Q: why can't I call a println after a while in defn body in Clojure? I have a function that looks like,
(defn app [server]
  (println "before while...."))
  (while test
    while-body)
  (println "...after while."))

However when I call the fn I just see the "before while" at the REPL, and then when the while fails its test, "nil".
If I write a test foo at the repl like
(defn foo []
  (println "testing before")
  (loop [i 100]
    (when (> i 10)
      (prn i)
      (recur (- i 2))))
  (println "after..."))

It works as I'd expect.
I've put the actual code up in a paste here, https://www.refheap.com/paste/12147 , if it helps.
What explains the difference in behavior here?
edit
Apologies for not trying this before, but this does work at the REPL:
(defn bar []
  (let [i (atom 100)]
    (println "before...")
    (while (> @i 10)
      (swap! i dec))
    (println "after...")))

So there's something else going on.
edit #2
Testing more at the repl, if I comment out the while loop, the println before and after will print. I was mistaken before about the 'nil', this is the return value of a different function called after the while was called. So it seems to have something to do with the while loop.
I noticed that if I change the while to this
(loop []
  (if test
    (do things and recur...)
    (println "test failed")))

The "test failed" never prints to the repl.

A: You've got an extranious ) at the end of the first println.
(defn app [server]
  (println "before while....")
  (while test
    while-body)
  (println "...after while."))

But since this is obviously example code that you didn't run, I expect the problem to be in the code that you did run. Please copy & paste that code exactly as is if this doesn't fix the problem.

A: The problem wasn't what I thought it was. I was blocking on a select call (called in the while loop) and that was causing problems with my shutdown function which ended the while loop. Adding a timeout to the select fixes it.

A: In Clojure function definitions, the last thing to be evaluated is what's returned, and (println ...) returns nil


text:
Q: Serialize an object to JSON How can I serialize an object that contains a list of objects to JSON
The error I get :

TypeError: Object of type person is not JSON serializable

import json

class person:
    def __init__(self, name, cars):
        self._name = name
        self._cars = cars

class car:
    def __init__(self, brand, color):
        self._brand = brand
        self._color = color

Jason = person("Jason", [car("Toyota", "Blue"), car("Honda", "Red")])

json = json.dumps(Jason)
print(json)

The output I want :
    {
        "name": "Jason",
        "cars":[
            {
                "brand": "Toyota",
                "color": "Blue"
            },
            {
                "brand": "Honda",
                "color": "Red"
            }
        ]
    }


text:
Q: compile command across emacs sessions how do i maintain a compile command across emacs sessions for a given file?
so, suppose I have file1.x, and I would like to use tool XComp to compile it. To do this, I need to run the following hypothetical command:
Xcomp file1.x && extract file1.x && Xlink file1.obj

So I do M-x compile, and write that thing. Now I have it available until I close emacs. How do I make that compile command persistent across emacs sessions, maybe a
% -*-

line somewhere? Any help appreciated.

A: The variable is "compile-command" so you could put this on the first line in your file:
// -*- compile-command: "Xcomp file1.x && extract file1.x && Xlink file1.obj" -*-

You may want to change the "//" for whatever you need to do for comments.


text:
Q: Copy an Excel Sheet to another Workbook in C# I have an excel sheet which contains a Signature Line. I tried to copy this sheet to another workbook, but the values of the sheet can be copied, except the signature line. I think this copy method is based on cells.
How to get signature line to another workbook. Here is my code
        Excel._Application xlApp;
        Excel.Workbook xlTemplateWB;
        Excel.Workbook xlTempWB;
        object missing = System.Reflection.Missing.Value;

        xlApp = new Excel.Application();
        xlApp.Visible = true;

        //Open Bench Sheet Template
        xlTemplateWB = xlApp.Workbooks.Open(@"C:\TempProjects\test.xlsx", 0, true, 5, "",
        "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);

        //Save As a temporary workbook
        xlTemplateWB.SaveAs(@"C:\\TempProjects\mytmp.xlsx");

        //Open temporary workbook
        xlTempWB = xlApp.Workbooks.Open(@"C:\TempProjects\my.xlsx", 0, false, 5, true, "",
        true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

        xlTemplateWB.Worksheets.Copy(xlTempWB.Worksheets["Sheet1"]);
        xlTemplateWB.Close(true, missing, missing);
        releaseObject(xlTemplateWB);

        xlTempWB.Save();

        //Close Workbooks
        xlTempWB.Close(true, missing, missing);
        xlApp.Quit();

        //Release Objects
        releaseObject(xlTempWB);
        releaseObject(xlApp);


text:
Q: How are React Native modules different from Cordova plugins? I was looking into comparison between Cordova based hybrid apps vs React Native and was confused how are React Native modules different from Cordova plugins?
(in case both are same, then why is FB reinventing the wheel)
Does React Native modules support all devices feature like Cordova does?
Thanks,
Rohit

A:
How are React Native modules different from Cordova plugins?

React Native Modules and Cordova Plugins both perform the same task: they allow the calling framework (React Native or Cordova) to invoke specific native functionality which is not available by default in the framework.
As such, the native functionality provided by a React Native module may be the same as provided by a Cordova plugin, but they will have a different interface to the framework which sits above.
Therefore, it's possible to factorise out the common native code and have a native component which is made available as both a React Native module and a Cordova plugin.
For example react-native-background-geolocation vs cordova-background-geolocation.
Since only the interface to the native functionality differs, there have been some attempts to write a bridge to allow Cordova plugins to be used as modules in React Native, for example react-native-cordova.

A: The main difference is that Cordova uses HTML5 + CSS + JS for building hybrid apps. Your app will still run inside of webview. Although I've never worked with it, I can comment something
What does it mean?

*

*I'm not sure about support of important features, like bluetooth, graphics, images (Core Graphics, Core Image), other core features

*Performance also won't be the same as native app

React Native is different here, because all it does - translates your JS code into native code for platforms. The performance still can't be the same, but it's comparatively high.
Also, you can use native modules for your application in case you can't find one already created by others, so every feature accessible under platforms still be reached from React Native


text:
Q: Customer can not redirect to my account page after create and login post action Site does not redirect to my account page after create account or login button click. New account mail is sending properly at the time of registration. But the page still redirect to login page itself.
It works properly in localhost, but shows this error in live server
Does anyone know the solution?


text:
Q: unable to connect to mongodb atlas with mongoose i need help!!! I tried connecting to mongodb atlas with my connection string but I'm unable to. I'm not sure how to proceed. i have a barebones application. I'm getting a connection error (a mongooseServerSelectionError) and an unhandled Promise Rejection Warning.
Here is the error:
 connection error:  MongooseError [MongooseServerSelectionError]: connect ECONNREFUSED 127.0.0.1:27017
   at new MongooseServerSelectionError (/Users/jagnoorg/Documents/personal-projects/monkey-den/project2/node_modules/mongoose/lib/error/serverSelection.js:22:11)
   at NativeConnection.Connection.openUri (/Users/jagnoorg/Documents/personal-projects/monkey-den/project2/node_modules/mongoose/lib/connection.js:808:32)
   at Mongoose.connect (/Users/jagnoorg/Documents/personal-projects/monkey-den/project2/node_modules/mongoose/lib/index.js:333:15)
   at Object.<anonymous> (/Users/jagnoorg/Documents/personal-projects/monkey-den/project2/server/db/index.js:4:10)
   at Module._compile (internal/modules/cjs/loader.js:1157:30)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:1177:10)
   at Module.load (internal/modules/cjs/loader.js:1001:32)
   at Function.Module._load (internal/modules/cjs/loader.js:900:14)
   at Module.require (internal/modules/cjs/loader.js:1043:19)
   at require (internal/modules/cjs/helpers.js:77:18)
   at Object.<anonymous> (/Users/jagnoorg/Documents/personal-projects/monkey-den/project2/server/bin.js:33:10)
   at Module._compile (internal/modules/cjs/loader.js:1157:30)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:1177:10)
   at Module.load (internal/modules/cjs/loader.js:1001:32)
   at Function.Module._load (internal/modules/cjs/loader.js:900:14)
   at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12) {
 message: 'connect ECONNREFUSED 127.0.0.1:27017',
 name: 'MongooseServerSelectionError',
 reason: TopologyDescription {
   type: 'Single',
   setName: null,
   maxSetVersion: null,
   maxElectionId: null,
   servers: Map { 'localhost:27017' => [ServerDescription] },
   stale: false,
   compatible: true,
   compatibilityError: null,
   logicalSessionTimeoutMinutes: null,
   heartbeatFrequencyMS: 10000,
   localThresholdMS: 15,
   commonWireVersion: null
 },
 [Symbol(mongoErrorContextSymbol)]: {}
}
(node:9182) UnhandledPromiseRejectionWarning: MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
   at new MongooseServerSelectionError (/Users/jagnoorg/Documents/personal-projects/monkey-den/project2/node_modules/mongoose/lib/error/serverSelection.js:22:11)
   at NativeConnection.Connection.openUri (/Users/jagnoorg/Documents/personal-projects/monkey-den/project2/node_modules/mongoose/lib/connection.js:808:32)
   at Mongoose.connect (/Users/jagnoorg/Documents/personal-projects/monkey-den/project2/node_modules/mongoose/lib/index.js:333:15)
   at Object.<anonymous> (/Users/jagnoorg/Documents/personal-projects/monkey-den/project2/server/db/index.js:4:10)
   at Module._compile (internal/modules/cjs/loader.js:1157:30)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:1177:10)
   at Module.load (internal/modules/cjs/loader.js:1001:32)
   at Function.Module._load (internal/modules/cjs/loader.js:900:14)
   at Module.require (internal/modules/cjs/loader.js:1043:19)
   at require (internal/modules/cjs/helpers.js:77:18)
   at Object.<anonymous> (/Users/jagnoorg/Documents/personal-projects/monkey-den/project2/server/bin.js:33:10)
   at Module._compile (internal/modules/cjs/loader.js:1157:30)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:1177:10)
   at Module.load (internal/modules/cjs/loader.js:1001:32)
   at Function.Module._load (internal/modules/cjs/loader.js:900:14)
   at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
(node:9182) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:9182) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Here is my code:
i give directions for which uri to connect to, set up the connection through mongoose, export the db and open the connection in app.js...
inside db/index.js:
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
// const uri = require('../../keys.js').mongodb.dbURI;
mongoose.connect("mongodb://localhost/test", { useNewUrlParser: true, useUnifiedTopology: true});
// mongoose.connect(process.env.MONGODB_URL || uri, { useNewUrlParser: true, useUnifiedTopology: true});
var db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error: "));

module.exports = db;

Inside app.js:
console.log('NODE_ENV :::', process.env.NODE_ENV);
if (process.env.NODE_ENV === 'PRODUCTION') {
    var app = require('./prod.app.js');
} else {
    var app = require('./dev.app.js');
}
var express = require('express');
var path = require('path');
var routes = require('./db/routes/index.js');
var http = require('http');
var favicon = require('serve-favicon');
var PORT = 3000;

/*
 * shared code in production and development
*/

// favicon - 3 ways - middleware, static, html
app.use(favicon(path.join(__dirname, '../public/images/favicon.ico')));
// app.use('/favicon.ico', express.static(path.join(__dirname, '../public/images/favicon.ico')));
// app.use('images/favicon.ico', express.static(path.join(__dirname, '../public/images/favicon.ico')));

app.use(express.json());
app.use(express.urlencoded({ extended: true}));

// static files
app.use(express.static(path.join(__dirname, "../client")));
app.use(express.static(path.join(__dirname, "../public")));

// db - mongo
var db = require('./db/index.js');
db.once("open", function (err) {
    // console.log('db::: ', db);
    if (err) {
        return console.error(err);
    } else {
        console.log("Successfully connected to mongodb");
    }
})

// routes
app.use(routes);

// serve index.html if can't find the route
app.use('*', function (req, res, next) {
    console.log("...serving index.html file from the public folder")
    res.sendFile(path.join(__dirname, '../public/index.html'));
});

// create server
var server = http.createServer(app);
server.listen(PORT);
console.log(`server listening on post ${PORT}`);

thank you for looking into this for me

A: Did you have this line in your app.js app.use(cors())?
Try to delete this line and delete everything that involves cors.
If this don't work, check your IP Whitelist inside Network Access in MongoDB Atlas and add your current IP or write this 0.0.0.0/0 to allow all IPs.

A: check your IP is enabled by mongodb atlas.
you should give access to your computer IP address from mongodb atlas.
go to the network access (left side bar) enter your IP or enter 0.0.0.0 to access all IP.

A: set your current ip address as 0.0.0.0/0 in mongoDB ATLAS in Connection ip address. It will allow to connect all ip address.

A: Try to add the url provided by Atlas to connect your app:
mongoose.connect("<URLprovidedByAtlas>", { useNewUrlParser: true, useUnifiedTopology: true});

A: bro update the (ip) address in mongodb atlus.IT WILL HELP YOU

A: Try to check your internet connection and if you having your IP address correctly.
https://github.com/Automattic/mongoose/issues/8180#issuecomment-552161146

A: This worked for me. I first changed the ip address to 0.0.0.0/0 and removed app.use(cores()). Then I downloaded mongoDB compass and connected to the data base. After that the same URI was used in index.js. There is a difference in inputting password in the URI and Compass. In compass you don't need to encode the password(if you have special characters). If you connect using compass and paste that link in the index.js you don't need to encode the password.

A: Check if you had started database in a terminal by
./mongod


text:
Q: How get current canvas position after zoom in/out or drag codesandbox link: https://codesandbox.io/s/canvas-zoom-in-out-drag-5moy48
HI!
I need to click on particular item on the canvas while zooming and moving functionalities also enable for canvas
But now i need to calculate the rectangle position relative to the canvas, after zoom the canvas. Whats the maths behind the zooming. If anyone knows please help in this. Thank you.
124 line
downHandler(ev: PointerDownEvent) {
    const { clientX, clientY } = ev;
    // How get current canvas position after zoom in/out or drag
    const startX = ?;
    const endX = ?;
    const startY = ?;
    const endY = ?;
    if (
      startX < clientX &&
      endX > clientX &&
      startY < clientY &&
      endY > clientY
    ) {
      // image canvas
    }
  }


text:
Q: Contact Form with Text Area filling remaining content I am trying to create a contact form similar to the design bellow, but can't seem to get the correct result. I thought I could do this with flex-box, but I am having trouble getting the Text Area to Display correctly. If there is a better way to do this with keeping the HTML structure the same, I am open to suggestions.
CodePen

<form class="flex-container">

    <input type="text" placeholder="left">

    <input type="text" placeholder="left">

    <input type="text" placeholder="left">

    <input type="text" placeholder="right">

    <input type="text" placeholder="left">

    <textarea placeholder="right"></textarea>

</form>

A: Maybe there is a more quick solution but you can do that with bootstrap :
<form class="container">

            <input type="text" placeholder="left">

            <input type="text" placeholder="left">

            <input type="text" placeholder="left">

            <input type="text" placeholder="left">

            <input type="text" placeholder="left">

            <textarea placeholder="right"></textarea>

CSS :
.heightCSS{
height: 8em;
width: 14em;

}


text:
Q: C# - error when applying numbering system to lists I'm working on a program that builds and allows use of a  simulation of a chip-coin car park. To build the car park, I ask the user to input the name of the car park, the number of levels in the car park, and the number of parking spaces on each level.
There are several classes at work here:
ParkingSpace (represents a single space)
ParkingSpaces (collection class - public interface of a List)
Level (contains a ParkingSpaces instance as part of composition relationship)
Levels (collection class - public interface of a List)
CarPark (contains a 'Levels' instance as park of a composition relationship)
Basically, a car park contains a number of levels, and there are a number of spaces on each level.
This works fine so far, and they all construct properly (tested using output to inform how many levels and spaces created), but I have just tried to implement a numbering system (to give each space a unique ID) and run into a bit of a problem.
The carPark has an attribute carParkID, each LevelID has a LevelID and each ParkingSpace has a SpaceID. The carParkID should be assigned through user input when creating the carpark, and the rest should be worked out using a numbering algorithm.
Each level is given the ID "carParkID-L(level#)", so that level 1 is "carParkID-L1", level 2 is "carParkID-L2" etc. This works as expected.
However, the problem occurs when trying to assign names to the spaces on the level, because for some reason the spaces on every level then take the levelID of the highest level in the list, for example (assuming the carpark has 3 levels):
Level 2, Space 1 should have the spaceID "carParkID-L2-0001", but ends up with the spaceID "carParkID-L3-0001". This happens on every level, meaning that the first space on each level has the same ID instead of taking the actual level number into account.
The code that numbers the levels and spaces is shown below, I have stepped through it and everything but can't find the root of the problem. If you have any insight, please let me know!
    //apply numbering system to all levels in car park
    public void numberLevels(string carParkID)
    {
        //access all instances in collection
        for (int levelIndex = 0; levelIndex < Length(); levelIndex++)
        {
            //assign level at current index to variable
            Level l = At(levelIndex);
            //use formula to create level name
            string levID = carParkID + "-L" + Convert.ToString(levelIndex + 1);

            //apply created ID to level
            l.setLevelID(levID);

            for (int spaceIndex = 0; spaceIndex < l.getNumSpaces(); spaceIndex++)
            {
                //construct new space
                //hold state of instance at current index
                ParkingSpace ps = l.getSpacesOnLevel().At(spaceIndex);

                //const to set consistent ID
                //4 figures, any blanks default to 0
                //1 = 0001
                //123 = 0123
                //length of figure
                const int WIDTH = 4;
                //default number
                const char PADCHAR = '0';

                //extend formula to create space unique ID
                //include car park and level ID
                string psID = levID + "-" + Convert.ToString(spaceIndex + 1).PadLeft(WIDTH, PADCHAR);

                //apply numbering system to space
                ps.setSpaceID(psID);
            }
        }
    }

Please let me know if you spot where I'm going wrong, or reply in the comments if you need any of the nested functions clarifying!
Thanks,
Mark


text:
Q: How to stream binary data into a PostgreSQL BYTEA column using the Golang lib/pq API? I'd like to insert some binary data into a BYTEA column,
How would I go about streaming the contents of somefile.tar.gz into a table with a BYTEA column?
Is it possible to stream to/from postgres from/to golang?

A: If one would be willing to switch to github.com/jackc/pgx, Large Objects (PostgreSQL docs) can be streamed. The pgx.LargeObject type implements:

io.Writer
io.Reader
io.Seeker
io.Closer

Large Objects are stored in a system table, there is no Large Object type which can be used in a column of a table. Large Objects are referenced by their object identifier. So a separate table needs to be maintained with file metadata and oid mapping.
Example program:
package main

import (
    "context"
    "io"
    "log"
    "os"
    "time"

    "github.com/jackc/pgx/v4"
)

const (
    // files table maps Large Object oid to file names
    createFileTable = `CREATE TABLE files (
        id oid primary key,
        name varchar,
        unique(name)
    );`
)

func main() {
    ctx, cancel := context.WithTimeout(context.TODO(), time.Minute)
    defer cancel()

    conn, err := pgx.Connect(ctx, "user=postgres host=/run/postgresql dbname=postgres")
    if err != nil {
        panic(err)
    }
    defer conn.Close(ctx)

    if _, err = conn.Exec(ctx, createFileTable); err != nil {
        panic(err)
    }

    written, err := storeFile(ctx, conn, "somefile.bin")
    log.Printf("storeFile written: %d", written)
    if err != nil {
        panic(err)
    }

    read, err := loadFile(ctx, conn, "somefile.bin")
    log.Printf("loadFile read: %d", read)
    if err != nil {
        panic(err)
    }
}

// storeFile as Large Object in the database.
// The resulting object identifier is stored along with the file name in the files table.
// The amount of written bytes and an erorr is returned, if one occured.
func storeFile(ctx context.Context, conn *pgx.Conn, name string) (written int64, err error) {
    file, err := os.Open(name)
    if err != nil {
        return 0, err
    }
    defer file.Close()

    // LargeObjects can only operate on an active TX
    tx, err := conn.Begin(ctx)
    if err != nil {
        return 0, err
    }
    defer tx.Rollback(ctx)

    lobs := tx.LargeObjects()

    // Create a new Large Object.
    // We pass 0, so the DB can pick an available oid for us.
    oid, err := lobs.Create(ctx, 0)
    if err != nil {
        return 0, err
    }

    // record the oid and filename in the files table
    _, err = tx.Exec(ctx, "INSERT INTO files (id, name) VALUES ($1, $2)", oid, name)
    if err != nil {
        return 0, err
    }

    // Open the new Object for writing.
    obj, err := lobs.Open(ctx, oid, pgx.LargeObjectModeWrite)
    if err != nil {
        return 0, err
    }

    // Copy the file stream to the Large Object stream
    written, err = io.Copy(obj, file)
    if err != nil {
        return written, err
    }

    err = tx.Commit(ctx)
    return written, err
}

// loadFile loads the file identified by name as Large Object
// and writes the contents to a local file by the same name.
// The amount of bytes read or an error is returned.
func loadFile(ctx context.Context, conn *pgx.Conn, name string) (read int64, err error) {
    tx, err := conn.Begin(ctx)
    if err != nil {
        return 0, err
    }
    defer tx.Rollback(ctx)

    var oid uint32
    err = conn.QueryRow(ctx, "SELECT id FROM files WHERE name = $1", name).Scan(&oid)
    if err != nil {
        return 0, err
    }

    file, err := os.Create(name)
    if err != nil {
        return 0, err
    }

    lobs := tx.LargeObjects()
    obj, err := lobs.Open(ctx, oid, pgx.LargeObjectModeRead)
    if err != nil {
        return 0, err
    }

    return io.Copy(file, obj)
}


text:
Q: How can I convert "Mon, 23 Sep 2013 07:00:00 GMT" as a string into "2013-09-23" using STR_TO_DATE in MySQL? I've got a long query with comparisons between tables, and one table has this format:
"Mon, 23 Sep 2013 07:00:00 GMT"

And another table has this format:
"2013-09-23"

How can I do a query where I can essentially do a
SELECT * from table1, table2
WHERE table1.date = table2.date

Something like this?
select column1, column2, DATE_FORMAT(STR_TO_DATE(table2.`column2`,'%a, %d %m %Y %I:%i:%s'),'%Y-%m-%d') as convert_date
FROM table1, table2

A: Given that the two dates are in the same timezone you could do something like this:
SELECT
    something
FROM
    longformat,
    shortformat
WHERE
    STR_TO_DATE(longformat.date,"%a, %d %b %Y") =
    STR_TO_DATE(shortformat.date, "%Y-%m-%d");

where longformat contains the date on the format "Mon, 23 Sep 2013 07:00:00 GMT" and shortformat contains the date on the format "2013-09-23".


text:
Q: What about the solutions of $z^{1/3} +1 = 0$? I'm trying to find the zeros of the equation $$z^{1/3} +1 = 0.$$
My professor said that the solutions are the third roots of unity multiplied by $-1$. My problem is that when I calculate the cubic root of one of the numbers  $$\bigg\{e^{i \pi},e^{i \pi/3},e^{-i \pi/3}\bigg \},$$ in order to verify that these numbers are really the numbers that give me $z^{1/3}+1=0$, I obtain one of the following sets: $$(e^{i \pi})^{1/3} = \bigg\{e^{i \pi},e^{i \pi/3},e^{-i \pi/3}\bigg \},$$ $$(e^{i \pi/3})^{1/3} = \bigg \{ e^{i \pi/9},e^{7 i \pi/9},e^{-5 i \pi/9}  \bigg \},$$ $$(e^{-i \pi/3})^{1/3} = \bigg \{ e^{-i \pi/9},e^{-7 i \pi/9},e^{5 i \pi/9}  \bigg \}.$$
First of all, if I consider the sum of a complex and a set element-wise, only one of the sets gives me $0$ when one is added to it (it is $(e^{i \pi})^{1/3}.$)
If the sum of a set and a complex number isn't element-wise, what means, for example, $(e^{i \pi})^{1/3} + 1 = 0$ (supposing it is a root as my professor said)? We are comparing a set with a number, must be interpreted $0$ as the set $\{0\}$?
Furthermore, if I interpret $0$ as a set, I don't have the equality of the sets, and for $(e^{i \pi/3})^{1/3}, (e^{-i \pi/3})^{1/3}$ I have that $\{0\}$ is not a subset of $(e^{i \pi/3})^{1/3}+1, (e^{-i \pi/3})^{1/3}+1$, respectively.

Note: When I'm considering the cubic root of the solutions proposed is only in order to see that these are roots really, and then I get stuck since the complex cubic root is a multivalued function.

Thanks to everyone!

A: It seems you are looking for something different that is
$$z^{3} +1 = 0 \iff z^3=-1 $$
and the suggestion by your professor is simply to evaluate $w^3=1$ and then obtain the solution from here using that
$$w_i^3=1 \implies (-1\cdot w_i)^3=-1\cdot (w_i)^3=-1$$

A: If you want to explicitly account for the possibility that $-1$ may not be the only solution to $z^{1 / 3}=-1$ you could proceed as follows:
$-1 = e^{(2n+1)\pi} \space n\in \mathbb{Z}$
$\Rightarrow z = (z^{1/3})^3 = e^{(6n+3)\pi} \space n\in \mathbb{Z}$
but $6n+3 = 2m+1$ where $m=3n+1$
$\Rightarrow z = e^{(6n+3)\pi} = e^{(2m+1)\pi} = -1 \space \forall n \in \mathbb{Z}$

A: $$z^{1/3}+1=0\implies z=(-1)^3$$

$$z^3+1=0\implies z=(-1)^{1/3}=-1^{1/3}=-(e^{i2k\pi})^{1/3}$$
and
$$z=-1\lor-\cos\frac{2\pi}3-i\sin\frac{2\pi}3\lor-\cos\frac{2\pi}3+i\sin\frac{2\pi}3.$$


text:
Q: what is the minimum dataset size needed for good performance with doc2vec? How does doc2vec perform when trained on different sized datasets? There is no mention of dataset size in the original corpus, so I am wondering what is the minimum size required to get good performance out of doc2vec.

A: A bunch of things have been called 'doc2vec', but it seems to most-often refer to the 'Paragraph Vector' technique from Le and Mikolov.
The original 'Paragraph Vector' paper describes evaluating it on three datasets:

*

*'Stanford Sentiment Treebank': 11,825 sentences of movie-reviews (which were further broken into 239,232 fragment-phrases of a few words each)

*'IMDB Dataset': 100,000 movie-reviews (often of a few hundred words each)

*Search-result 'snippet' paragraphs: 10,000,000 paragraphs, collected from the top-10 Google search results for each of the top 1,000,000 most-common queries

The 1st two are publicly available, so you can also review their total sizes in words, typical document sizes, and vocabularies. (Note, though, that no one has been able to fully-reproduce that paper's sentiment-classification results on either of those first two datasets, implying some missing info or error in their reporting. It's possible to get close on the IMDB dataset.)
A followup paper applied the algorithm to discovering topical-relationships in the datasets:

*

*Wikipedia: 4,490,000 article body-texts

*Arxiv: 886,000 academic-paper texts extracted from PDFs

So the corpuses used in those two early papers ranged from tens-of-thousands to millions of documents, and document sizes from a few word phrases to thousands-of-word articles. (But those works did not necessarily mix wildly-differently-sized documents.)
In general, word2vec/paragraph-vector techniques benefit from a lot of data and variety of word-contexts. I wouldn't expect good results without at least tens-of-thousands of documents. Documents longer than a few words each work much better. Results may be harder to interpret if wildly-different-in-size or -kind documents are mixed in the same training – such as mixing tweets and books.
But you really have to evaluate it with your corpus and goals, because what works with some data, for some purposes, may not be generalizable to very-different projects.


text:
Q: efficient way to convert list of points to table I have a list in memory/in a csv file of points...
x1,y1,z1
x1,y2,z2
...
x4,y38,z
...
xn,yn,zn

Is there an efficiënt way to convert this dataset to a 2d table in another csv file with the x-values in the first row and the y values in the first column and the z value on the corresponding place?
It's possible with for/while loops, but maybe there's a better way to address this problem?


text:
Q: Qt QTreeWidget Context Menu: Add items under another o delete items. I managed to create a context menu that gets activated after a right click on each item of a QTreeWidget tree:
contextMenu = new QMenu(ui->treeWidget);
ui->treeWidget->setContextMenuPolicy(Qt::ActionsContextMenu);

addElement = new QAction("Add Element",contextMenu);
deleteElement = new QAction("Delete Element",contextMenu);

ui->treeWidget->addAction(addElement);
ui->treeWidget->addAction(deleteElement);

connect(addElement,    SIGNAL(triggered()), this, SLOT(addElementHandler()));
connect(deleteElement, SIGNAL(triggered()), this, SLOT(deleteElementHandler()));

My intention is to add new items under another in the tree or delete them by right clicking on a specific item using this context menu.
However I'm not sure how to realize from the handlers on exactly which item of the tree the right click was made.
Could you please give me a clue?
Thanks in advance!

A: If you are not going to change the TreeWidget selection behavior or set the current item by your own -  you can use just the native behavior. While context menu requesting the tree selects the item, on which the right click was performed and that is the currentItem. So in addElementHandler slot the currentItem() will give you exact item you want.


text:
Q: Why is an environment variable not updated in a loop? I would like my variable res to be updated inside the loop, but it does not update until after the second iteration.
Here is my code:
@echo off
set /a res=10

:loop
if %res% gtr 100 (
    goto endLoop
) else (
    set /a res=res*10
    rem Here the 'res' shouldn't it be 100?
    echo the result is : %res%
    rem Here the first iteration display 10 not 100.
    goto loop
)

:endLoop
pause > nul

Is there an explanation for this?

A: As an example of usage of delayed expansion here's your modified code:
@Echo Off
SetLocal EnableDelayedExpansion

Set "res=10"

:loop
If %res% Lss 100 (
    Set/A res*=10
    Echo the result is : !res!
    GoTo loop
)

Pause>Nul

There is an alternative without using delayed expansion in this case, but I'd suggest you stick with the former until you are confident enough to understand the order in which things are read and parsed:
@Echo Off

Set "res=10"

:loop
If %res% Lss 100 (
    Set/A res*=10
    Call Echo the result is : %%res%%
    GoTo loop
)

Pause>Nul


text:
Q: cant get equation solved Hello I am having trouble solving this equation. I know the answer is $10.663$, but I am getting $1.146485093853515e-5$, for the top I get $29.904$ and the bottom I get $2608320$. Where do you think I am not correctly solving the equation? I must be doing something wrong I didn't think I was this bad at math. Any help is appreciated thanks
$$ \frac{(12 -0.3-3.3)\times (0.26 + 3.3)}{(12 - 0.3 + 0.26) \times 380\,000 \times 0.3 \times 2} $$

A: You messed up somewhere in the denominator,
\begin{align}
 &= \frac{ (8.4) \times (3.56) }{ (11.96) \times 380\,000 \times 0.6 } \\
 &= \frac{ 29.904 }{ 2\,726\,880 } \\
 &= 0.00001096637, \\
\end{align}
which is also expressible as $10.96637 \times 10^{-6}$. This can be shown here.


text:
Q: closability of the Malliavin derivative when $p=1$ Let $H$ be a separable Hilbert space and $W=(W(h))_{h\in H}$ be an isonormal Gaussian process on a probability space $(\Omega,\mathscr F,P)$, where $\mathscr F$ is generated by $W$.
Let $\mathscr S $ (resp. $\mathscr S_b$) be the space of all random variable $X$ of the form
$$X=f(W(h_1),\cdots, W(h_n))$$
where $n=1,2,\cdots,\,h_1,\cdots,h_n \in H$ and $f\in C^\infty_p(\mathbb R^n)$ (resp. $f\in C_b^\infty(\mathbb R^n)$). Note that $\mathscr S$ and $\mathscr S_b$ are dense in $L^p(\Omega)$ for all $p\in [1,\infty)$.
If $X=f(W(h_1),\cdots, W(h_n)) \in \mathscr S$, define the Malliavin derivative $DX$ as
$$DX:= \sum_{j=1}^n \partial_jf(W(h_1),\cdots, W(h_n))h_j. $$
I want to prove the operator $D:\mathscr S\,(\subset L^p(\Omega)) \to L^p(\Omega;H) $ is closable for any $p\in[1,\infty) $, i.e. if $(X_n)_{n=1}^\infty$ is a sequence in $\mathscr S$ which converges to $0$ in $L^p(\Omega)$ and $(DX_n)_{n=1}^\infty$ converges to $\xi$ in $L^p(\Omega; H)$, then I want to conclude $\xi=0$. Under that assumption, we can prove that for all $Y \in \mathscr S_b$ and $h\in H$
$$E[Y\langle \tilde\xi,h\rangle_H]=0,$$
where $\tilde \xi := \exp(-|W(h)|^2)\xi$. If $1<p<\infty$, using the density of $\mathscr S_b$ in $L^q(\Omega)$ where $1/p +1/q =1 $, we can conclude $\langle \tilde\xi,h\rangle_H=0$ almost surely, which implies $\langle \xi,h\rangle_H=0$ almost surely, and since $h$ is arbitraly and $H$ is separable, it follows $\xi=0$ almost surely.
If $p=1$, how do we prove $\xi=0$ ?


text:
Q: How to make code compatible for both IOS 5 and IOS 4 [iphone] I am on a new project. I want my code compatible to be for both IOS4 and IOS5 SDKs. I need all my functionalities work both in IOS4 and IOS5. That said, i am not planning to use new features in IOS5 (feature wise) and disable that feature for IOS4.
I have 2 options. Let me know which is best ?

*

*Target and code for IOS4. and that will work fine in IOS5 also, i think.

*BaseSDK IOS5 and target IOS4 .(I am not planning to use ARC or storyboard for now anyway ).

I think with method #2, i have to be extra careful while using each usages at the same time as i am not using story board and ARC , there are no benefits. So hope #1 is better.
Let me know expert opinion.
Note: in future if need to switch to IOS5 new features , hope only this ARC will be the blocking and that is also an optional thing and i can easily switch rt?

A: I use this code to support my app on multiple iOS versions (3.0, 4.0, 5.0) ..
put this at the top (along with imports)

#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)

then if there are some OS specific features, use them like this (I am using AlertView as an example. Pre iOS5, UIAlertView does not support a custom textView inside it, so I had my own custom AlertView. In iOS5, that hack does not work and I have to use UIAlertView as it supports custom textViews):
if (SYSTEM_VERSION_LESS_THAN(@"5.0")) {

    TextAlertView *alert = [[TextAlertView alloc] initWithTitle:@"xxxYYzz"
                                                        message:@""
                                                       delegate:self cancelButtonTitle:@"Add"
                                              otherButtonTitles:@"Cancel", nil];
    alert.textField.keyboardType = UIKeyboardTypeDefault;
    alert.tag = 1;
    self.recipeNameTextField = alert.textField;
    [alert show];
    [alert release];
}
else {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"xxYYzz"
                                               message:@""
                                               delegate:self cancelButtonTitle:@"Add"
                                      otherButtonTitles:@"Cancel", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
self.recipeNameTextField = [alert textFieldAtIndex:0];

[alert show];
[alert release];
}

Hope it helps

A: Go with the first one. If you're making your app for iOS4 and you're not using anything new from iOS5 then don't make things more complicated for yourself.
The only real time you want to use the second option is when you want to use some of the new features in iOS5 but you still want it to be compatible on iOS4, in which case you will have to put in conditional checks for the iOS version that your program is currently being run on.
By the way, ARC is compatible to iOS4 anyway.

A: At work we build our apps like Option 2 when we need backwards compatibility


text:
Q: How do I set docker-credential-ecr-login in my PATH before anything else in GitLab CI I'm using AWS ECR to host a private Dockerfile image, and I would like to use it in GitLab CI.
Accordingly to the documentation I need to set docker-credential-ecr-login to fetch the private image, but I have no idea how to do that before anything else. That's my .gitlab-ci file:
image: 0222822883.dkr.ecr.us-east-1.amazonaws.com/api-build:latest

tests:
  stage: test
  before_script:
    - echo "before_script"
    - apt install amazon-ecr-credential-helper
    - apk add --no-cache curl jq python py-pip
    - pip install awscli
  script:
    - echo "script"
    - bundle install
    - bundle exec rspec
  allow_failure: true # for now as we do not have tests

Thank you.

A: I confirm the feature at stake is not yet available in GitLab CI; however I've recently seen it is possible to implement a generic workaround to run a dedicated CI script within a container taken from a private Docker image.
The template file .gitlab-ci.yml below is adapted from the OP's example, using the Docker-in-Docker approach I suggested in this other SO answer, itself inspired by the GitLab CI doc dealing with dind:
stages:
  - test

variables:
  IMAGE: "0222822883.dkr.ecr.us-east-1.amazonaws.com/api-build:latest"
  REGION: "ap-northeast-1"

tests:
  stage: test
  image: docker:latest
  services:
    - docker:dind
  variables:
    # GIT_STRATEGY: none  # uncomment if "git clone" is unneeded for this job
  before_script:
    - ': before_script'
    - apt install amazon-ecr-credential-helper
    - apk add --no-cache curl jq python py-pip
    - pip install awscli
    - $(aws ecr get-login --no-include-email --region "$REGION")
    - docker pull "$IMAGE"
  script:
    - ': script'
    - |
      docker run --rm -v "$PWD:/build" -w /build "$IMAGE" /bin/bash -c "
        export PS4='+ \e[33;1m($CI_JOB_NAME @ line \$LINENO) \$\e[0m '  # optional
        set -ex
        ## TODO insert your multi-line shell script here ##
        echo \"One comment\"  # quotes must be escaped here
        : A better comment
        echo $PWD  # interpolated outside the container
        echo \$PWD  # interpolated inside the container
        bundle install
        bundle exec rspec
        ## (cont'd) ##
      "
    - ': done'
  allow_failure: true # for now as we do not have tests

This example assumes the Docker $IMAGE contains the /bin/bash binary, and relies on the so-called block style of YAML.
The above template already contains comments, but to be self-contained:

*

*You need to escape double quotes if your Bash commands contain them, because the whole code is surrounded by docker run … " and ";

*You also need to escape local Bash variables (cf. the \$PWD above), otherwise these variables will be resolved prior running the docker run … "$IMAGE" /bin/bash -c "…" command itself.

*I replaced the echo "stuff" or so commands with their more effective colon counterpart:
set -x
: stuff
: note that these three shell commands do nothing
: but printing their args thanks to the -x option.

[Feedback is welcome as I can't directly test this config (I'm not an AWS ECR user), but I'm puzzled by the fact the OP's example contained at the same time some apt and apk commands…]
Related remark on a pitfall of set -e
Beware that the following script is buggy:
set -e
command1 && command2
command3

Namely, write instead:
set -e
command1 ; command2
command3

or:
set -e
( command1 && command2 )
command3

To be convinced about this, you can try running:
bash -e -c 'false && true; echo $?; echo this should not be run'
  → 1
  → this should not be run
bash -e -c 'false; true; echo $?; echo this should not be run'
bash -e -c '( false && true ); echo $?; echo this should not be run'

A: From GitLab documentation. In order to interact with your AWS account, the GitLab CI/CD pipelines require both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY to be defined in your GitLab settings under Settings > CI/CD > Variables. Then add to your before script:
image: 0222822883.dkr.ecr.us-east-1.amazonaws.com/api-build:latest

tests:
  stage: test
  before_script:
    - echo "before_script"
    - apt install amazon-ecr-credential-helper
    - apk add --no-cache curl jq python py-pip
    - pip install awscli
    - $( aws ecr get-login --no-include-email )
  script:
    - echo "script"
    - bundle install
    - bundle exec rspec
  allow_failure: true # for now as we do not have tests

Also, you had a typo is awscli, not awsclir.Then add the builds, tests and push accordingly.

A: I think that you have some sort of logic error in the case. image in the build configuration is a CI scripts runner image, not image you build and deploy.
I think you don't have to use it in any case since it is just an image which has utilities & connections to the GitLab CI & etc. The image shouldn't have any dependencies of your project normally.
Please check examples like this one https://gist.github.com/jlis/4bc528041b9661ae6594c63cd2ef673c to get it more clear how to do it a correct way.

A: I faced the same problem using docker executor mode of gitlab runner.
SSH into the EC2 instance showed that docker-credential-ecr-login was present in /usr/bin/. To pass it to the container I had to mount this package to the gitlab runner container.
gitlab-runner register -n \
--url '${gitlab_url}' \
--registration-token '${registration_token}' \
--template-config /tmp/gitlab_runner.template.toml \
--executor docker \
--tag-list '${runner_name}' \
--description 'gitlab runner for ${runner_name}' \
--docker-privileged \
--docker-image "alpine" \
--docker-disable-cache=true \
--docker-volumes "/var/run/docker.sock:/var/run/docker.sock" \
--docker-volumes "/cache" \
--docker-volumes "/usr/bin/docker-credential-ecr-login:/usr/bin/docker-credential-ecr-login" \
--docker-volumes "/home/gitlab-runner/.docker:/root/.docker"

More information on this thread as well: https://gitlab.com/gitlab-org/gitlab-runner/-/issues/1583#note_375018948

A: We have a similar setup where we need to run CI jobs based off of an Image that is hosted on ECR.
Steps to follow:-

*

*follow this guide here>> https://github.com/awslabs/amazon-ecr-credential-helper

*gist of this above link is if you are on "Amazon Linux 2"
sudo amazon-linux-extras enable docker
sudo yum install amazon-ecr-credential-helper

*open the ~/.docker/config.json on your gitlab runner in VI editor

*Paste this code in the ~/.docker/config.json
{
"credHelpers":
{
"aws_account_id.dkr.ecr.region.amazonaws.com": "ecr-login"
}
}

*source ~/.bashrc

*systemctl restart docker

*also remove any references of DOCKER_AUTH_CONFIG from your GitLab>>CI/CD>> Variables
That's it


text:
Q: Define size of css classes inside css using twitter bootstrap I am migrating my small business website to use bootstrap in order to be mobile friendly. I am still getting to know the bootstrap framework and I am not an expert in css either...
My question is a conceptual one. Today with my old website, using html and css, I define in my css both the size (yes, fixed sizes) and styles (colour, etc.) of the divs I use.
On the other hand, in all the examples I've seen of bootstrap, in the css one can only define the style of the divs, while the size is defined in the html when choosing the bootstrap column's size (e.g. col-sm-4). [Note: I am following the approach of having two css, bootstrap's and my custom one.]
The way I see it, I am losing the capacity to define the size of the divs centrally from the css and hence losing maintainability. Also, the site will be harder to develop since the col-sm-* classes are semantically poor. Is this correct? Am I missing something here?
Is there a way to define css classes that reference the bootstrap classes? e.g. To define a .menu css class that can behave as .col-sm-4.
Any suggestion or recommendation is welcome.
Thanks in advance


text:
Q: Loading a jpeg using BitmapRegionDecoder gives checkerboard distortion I'm loading a big jpeg file from a url using an InputStream from a URLConnection. The goal is to get an int[] with the image data as this is more efficient than using a Bitmap for further use. There are two options here.
The first is to create a Bitmap object and to copy the results in an int[]. This works in my application but the full image is in memory twice upon loading as the image data is copied into the int[] image.
Bitmap full = BitmapFactory.decodeStream(conn.getInputStream());
full.getPixels(image, 0, width, 0, 0, width, height);

To save memory, I'm trying to perform this process in a tiled fashion using a BitmapRegionDecoder.
int block = 256;
BitmapRegionDecoder decoder = BitmapRegionDecoder.
    newInstance(conn.getInputStream(), false);
Rect tileBounds = new Rect();
// loop blocks
for (int i=0; i<height; i+=block) {
    // get vertical bounds limited by image height
    tileBounds.top = i;
    int h = i+block<height ? block : height-i;
    tileBounds.bottom = i+h;
    for (int j=0; j<width; j+=block) {
        // get hotizontal bounds limited by image width
        tileBounds.left = j;
        int w = j+block<width ? block : width-j;
        tileBounds.right = j+w;
        // load tile
        tile = decoder.decodeRegion(tileBounds, null);
        // copy tile in image
        int index = i*width + j;
        tile.getPixels(image, index, width, 0, 0, w, h);
    }
}

Technically this works and I get the full image in the int[] image. Also the tiles are seemlessly inserted into the image.
Now my problem. The second method results in an image which has some kind of strange checkerboard distortion. Pixels seem to alternate between being slightly darker or slightly lighter. BitmapRegionDecoder is supposed to support jpeg, and BitmapFactory.decodeStream has no problems. What is the problem here?

A: Found it! apparently if you feed null into decoder.decodeRegion(tileBounds, null); it returns a Bitmap with quality Bitmap.Config.RGB_565 (not sure if this is device dependant). Simply feeding it a new options set returns a Bitmap of Bitmap.Config.RGB_ARGB8888 quality. By default this preferred quality is set.
BitmapFactory.Options options = new BitmapFactory.Options();
...
// load tile
tile = decoder.decodeRegion(tileBounds, options);

A: Thanks for your self-investigation!
Though I would recommend avoid relying on some default and make it clear:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig=Config.ARGB_8888;   //explicit setting!
result_bitmap=regionDecoder.decodeRegion(cropBounds, options);

Thanks!


text:
Q: Emacs auto-formatting php code (on indent) I'm looking for a way to format the spaces between symbols and keywords in emacs.
For example I'd like to change the following php code :
foreach($a as $b) {
}

into
foreach ($a as $b) {
}

All I've been able to find thus far are external tools to run from emacs.
Related : Auto formatting a PHP file in emacs.
I'd prefer that it did the formatting on indent, is this possible?

A: Indeed, I don't know of any such tool within Emacs.  I'd be happy to accept submission for a package that does something like that on the fly. Maybe it could work a bit like electric-layout-mode?


text:
Q: Ubuntu 12.10 detecting wrong graphics card I have just done a fresh install of 12.10 on my laptop details are below and it is detecting the wrong graphics cards so now the fan is running very loud.
If any could help me I would be very thankful
HP Pavilion dv6-6b05tx Entertainment Notebook PC2nd generation Intel(R) Core(TM) i7-2670M Processor (2.2GHz, Dual Core, 4T, 6MB L3)8GB DDR3 RAM 750GB SATA HDD Blu-ray ROM DVD+/-R/RW SuperMulti DL Drive 15.6 inch (1920 x 1080) LED Backlit BrightView display ATI Radeon HD 6770M (2 GB dedicated)

A: Do you have two graphics cards? One onboard and one discrete? Or what do you mean with "detecting the wrong one"? Is it just the fans, or is the unit getting hot as well?
Linux has still trouble with laptops having hybrid graphics, but you can try a few things with vgaswitcheroo, if you have two graphics cards.

A: As I said here:
Overheating on VAIO SB36

Usually, the overheating problem in Ubuntu is related to the graphic
  card, and in your case, you have an Hybrid graphic card with the open
  source drivers. In this case, by default, you have both graphic cards
  connected but you are only using the integrated (Intel). If you want
  to use only one and when you want, you need to install the privative
  drivers following this answer:
What is the correct way to install proprietary ATI Catalyst Video Drivers (fglrx) directly from AMD?
And using the latest driver:
(6 jun)
  http://www2.ati.com/drivers/linux/amd-driver-installer-catalyst-13-4-linux-x86.x86_64.zip


text:
Q: Yum is not respecting `Requires` maximum version. How can I debug and check what yum thinks the dependency version is? I manage an RPM package and there are versions numbered like:
my-package-1.1.1-1, my-package-1.1.2-1, my-package-1.1.3-1, my-package-1.2.0-0.alpha01.1.
I'm now trying to get another package to depend on my-package < 1.2 so that only a 1.1 version is installed. However when I install with yum, it will always install the latest version (my-package-1.2.0-0.alpha01) instead of one that satisfies the requirement.
How can I check what yum thinks my package's version is?
Here is the spec for the package with the requirement:
Name:       test
Version:    1
Release:    1
Requires: my-package < 1.2

%description
%prep
%build
%install
%files

I also tried Requires: my-package < 0:1.2 with no success.
The rpm spec for my-package 1.2 starts with:
Name: my-package
Provides: my-package
Version: 1.2.0
Release: 0.alpha01.1%{?dist}

and for the 1.1 versions:
Name: my-package
Provides: my-package
Version: 1.1.3
Release: 1%{?dist}

Only the Version: line is changed to set different versions numbers. No epoch is set, so I assume it will default to 0:.
rpmdev-vercmp "1.2.0-0.alpha01.1" "1.2" correctly returns 1.2.0-0.alpha01.1 > 1.2. So I don't think the numbering is incorrect.
Weirdly: even if I set Epoch: 200  on my 1.2 version of my-package and set the test package to require my-package < 10:1.2 it installs the 200:1.2.0 version.
I think the problem is that yum isn't correctly parsing the built my-package.rpm's version. How can I check?
EDIT 1
Here are some diagnostics using rpm -q, it looks like version dependencies are correct?:
$ rpm -qp  --requires test-1-1.x86_64.rpm
my-package < 1.2
rpmlib(FileDigests) <= 4.6.0-1
rpmlib(PayloadFilesHavePrefix) <= 4.0-1
rpmlib(CompressedFileNames) <= 3.0.4-1
rpmlib(PayloadIsXz) <= 5.2-1

$ rpm -qp --provides my-package-1.1.3-1.noarch.rpm
my-package
my-package = 1.1.3-1

$ rpm -qp --provides my-package-1.2.0-0.alpha01.1.noarch.rpm
my-package
my-package = 1.2.0-0.alpha01.1

EDIT Reproduction steps!
I made reproduction code! Tested it on Centos7 running from home dir.
Requires rpmdevtools and createrepo to be installed.
#/bin/bash
echo "Name:       my-package
Provides:   my-package
Version:    \${VERSION}
Release:    \${RELEASE}
Summary:    NA
License:    NA

%description
%prep
%build
%install
%files
" | tee template.spec

echo "Name:       has-requirement
Version:    1
Release:    1
Summary:    NA
License:    NA

Requires: my-package < 1.2

%description
%prep
%build
%install
%files
" | tee has-requirement.spec

vers=("1.1.1" "1.1.2" "1.1.3" "1.2.0")

rpmdev-setuptree
for v in ${vers[@]}; do
    VERSION=$v RELEASE="1" envsubst '$${VERSION} $${RELEASE}' < template.spec > my-package.spec
    rpmbuild -ba my-package.spec
done
rpmbuild -ba has-requirement.spec

repodir="$PWD/repo"
mkdir -p $repodir
mv ./rpmbuild/RPMS/x86_64/my-package* $repodir
createrepo $repodir

echo "[temp]
name=temp repo
baseurl=file://$repodir
enabled=1
gpgcheck=0" | sudo tee /etc/yum.repos.d/temp.repo

sudo yum clean all; sudo rm -rf /var/cache/yum
sudo yum search my-package --show-duplicates
sudo yum localinstall --assumeno $PWD/rpmbuild/RPMS/x86_64/has-requirement-1-1.x86_64.rpm

A: you can ask rpm to tell you the requirement for your test package:
if it is installed:
rpm -q test --requires

if it is not installed:
rpm -qp /path/to/test.rpm --requires

that could help you out.
You error is indeed strange; are you sure the correct test.rpm is being installed; with the correct depencency?

A: For the sake of anyone else facing this problem of yum not recognising dependency versions, this is how I fixed the dependency resolution.
In my dependency package, the rpm spec header started with:
Name:       my-package
Provides:   my-package
Version:    1.2.0
Release:    0

The line Provides: my-package was redundant and it was confusing yum because it meant all versions of the package were providing my-package. I don't entirely know why that was causing version and epoch numbers to be ignored, but there you go.
Removing the my-package package name from the list of stuff it provides, made yum observe versioning requirements as expected.
I think this is probably a bug in yum. I haven't tested if dnf does the same thing.


text: Q: Backing up Windows 8 OS and files without invalidating license I am trying to dual boot my PC. It came with a valid version of Windows 8, Is there a way to backup the actual OS with the valid license? So that whenever I try reinstalling it again I don't get an invalid Win8 version message etc.. What utilities do I need?


text:
Q: Define (not use default) for shapes in ggplot I am trying to make a scatterplot with three shapes (small circle, large circle, and cross).
I am able to get to the point where I have almost what I want, except that I can't figure out how to specify the shapes:
AData=as.data.frame(cbind(x=rnorm(5, 10, 1),y=rnorm(5,10,1)))
AData["Type"] = rep(1,dim(AData)[1])
BData=as.data.frame(cbind(x=rnorm(5, 20, 1),y=rnorm(5,20,1)))
BData["Type"] = rep(2,dim(BData)[1])
CData=as.data.frame(t(c(0,0,3)))
colnames(AData) = c("Ankle.dif", "Knee.dif", "Type")
colnames(BData) = c("Ankle.dif", "Knee.dif", "Type")
colnames(CData) = c("Ankle.dif", "Knee.dif", "Type")
dataFramePlot = rbind(AData, BData, CData)
ggplot(dataFramePlot, aes(x=Ankle.dif, y=Knee.dif)) + geom_point(aes(shape = factor(Type)))

I get a circle, triangle, and square here, but I prefer to specify a small circle, large circle, and crossbar for the three types. Any ideas? THanks!

A: Here is one way using scale_shape_manual. For shape, you can find more information in many places. Here is a link for you. As the OP requested in the comment below, I modified the legend.
ggplot(dataFramePlot, aes(x=Ankle.dif, y=Knee.dif)) +
geom_point(aes(shape = factor(Type)))+
scale_shape_manual(name = "Data",
                   values=c(20, 19, 3),
                   breaks=c("1", "2", "3"),
                   labels=c("First data", "Second data", "Third data"))


text: Q: Topology of $3$-dimensional noncompact Alexandrov space with sec $\ge 0$ For any noncompact $3$-dimensional smooth manifold $M$ with sec $\ge 0$, it follows from soul's theorem that $M$ is diffeomorphic to $\mathbb R^3, S^2 \times \mathbb R$ or their quotients. Can we have a similar topological conclusion for $3$-dimensional noncompact Alexandrov space with sec $\ge 0$?


text:
Q: How does Eclipse run .java files as applets? I've been trying to run a simple applet that I created from the command line. I tried just doing:
C:\java Applet

It obviously didn't work; however, I noticed that Eclipse lets me run the applet if I select the class and select run as java applet. How does Eclipse do this?

A: you need to use appletviewer command from the command line to run an Applet

A: I believe IDEs typically launch applets using the appletviewer, but using an unrestricted security policy (the appletviewer when launched from the command line is sand-boxed).
To launch the applet viewer from the command line, try this:

*

*In the source, add a comment at the top along the lines of a standard applet element.

*Run the applet viewer using the command.
prompt> appletviewer TheApplet.java Note particularly that rather than provide HTML as the argument to the applet viewer (the old way), applet viewer will now parse the applet element directly out of the source.

See also the applet info. page for an example of using the applet element at the top of the source:  E.G.
/* <!-- Defines the applet element used by the appletviewer. -->
<applet code='HelloWorld' width='200' height='100'></applet> */
import javax.swing.*;

/** An 'Hello World' Swing based applet.

To compile and launch:
prompt> javac HelloWorld.java
prompt> appletviewer HelloWorld.java  */
public class HelloWorld extends JApplet {

    public void init() {
        // Swing operations need to be performed on the EDT.
        // The Runnable/invokeLater() ensures that happens.
        Runnable r = new Runnable() {
            public void run() {
                // the crux of this simple applet
                getContentPane().add( new JLabel("Hello World!") );
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

When launched from the command line, the applet viewer will have an even more restrictive sand-box than is applied to an applet deployed in a browser.

An alternative to appletviewer is Appleteer which I can highly recommend, because it is better than appletviewer ( and I wrote it ;).

A: Applet is a graphic component that extends Panel and has Applet context.
It is not a big problem to emulate this environment. You just have to create application with main method that creates frame with border layout and puts applet in the center of this frame. This application should also implement applet context that provides API to retrieve parameters.
As was mentioned by @Satya JDK has such utility named appletvieer that can be executed from command line. Eclipse can either use appletvieer directly or implement is own viewer as described above.


text:
Q: Entity Framework Save not working I am using Entity Framework to save some data in a SQLite database file.
This is my table in DB file
ID  Name    Username    Pwd

ID is autoincrement, and rest of columns are of Text type
This is how I am saving my data into the database:
UserInfo userInfo=new UserInfo();
userInfo.Name="abc";
userInfo.Username="xyz";
userInfo.Pwd="123456";

using (var context = new ApplicationContext())
{
    context.UserInfo.Add(userInfo);
    context.SaveChanges();
}

The problem is, this code is not inserting any new row into the table. I also tried this before saving, but no luck
context.Entry<UserInfo>(userInfo).State = EntityState.Added;
context.ChangeTracker.DetectChanges();

I tried debugging and no exception is occurring.
How can I insert new row into a table using Entity Framework?

A: Possibilities that may cause an issue.

*

*Right Click on your Entity Data Model and Update Model From Database. To make sure you have updated till the last change.

*Make sure you are looking at the correct Database and Table. Every one makes this mistake once in a while.

*Make sure you are using the valid connection string. Pointing the proper databases. Make sure its not a old db /  some other backup db.

*Make sure you are using the proper entity which is up to date.

The above code you have, its perfectly working fine to me. I just did a workout to sort out this issue.
The above points are guesses.
Refer this Link Entity Data Model Example & One More Example Code available here

A: I had a similar problem once and it can be a pain to determine what exactly causes this. One issue that might be causing such a behavior in EF is having multiple instances of the Context object such that when  you call SaveChanges on your Context, you are actually calling it on a different instance than the one you added the entity on (and EF does not detect any changes in the entities or the new entity is not attached to the right context, causing SaveChanges to not send any SQL requests to the database).
I suggest debugging this in VS (using the object id feature) in order to see if you have multiple context instances. Using the Unit Of Work pattern together with repositories is a way to have a better control over the lifetime of the context objects in your application