text:
Q: Check for empty form fields in this field only I have this code:
$("form").submit(function() {
  $(":input").each(function() {
    if($(this).val() === "")
    alert("Empty Fields!!");
  });
});

It works great but when I have more than one form on a page, it checks all forms. I wan't to check only the submitted form using the "this" selector. How shall I implement the "this" selector in my code to check only the submitted form?
I cannot use any id's or classes, only the "this" selector.

A: Within the form submit handler you can use the this keyword to refer to the form which raised the event. Once you have that you could use find:
$("form").submit(function() {
    $(this).find(":input").each(function() {
        if ($(this).val() === "")
            alert("Empty Fields!!");
    });
});

Or a contextual selector:
$("form").submit(function() {
    $(":input", this).each(function() {
        if ($(this).val() === "")
            alert("Empty Fields!!");
    });
});

To retrieve the related input elements.


text:
Q: How to retrieve the JSON object key which having numbered name I'm trying to pass a number of JSON objects from my server which have names appended with a number to differentiate each other.
I am getting a problem while retrieving these objects. It is unable to append a number with its common name.
Objects look like this:
  {"shareInfo":[{"uname1":"abc","uname2":"sds","uname3":"uuh",.....}]}

I tried appending an integer variable to it.
 data.shareInfo[i].uname+''+i;

But it is not reading the variable together. I mean it is not taking it like uname0,uname1,...
Please anyone tell me how to append the number to retrieve the data, thanks.

A: data.shareInfo[i]["uname" + i] should work.
It's worth noting that your example data only contains one array element in data.shareInfo, so what you might actually need is:
data.shareInfo[0]["uname" + i]
But I can't tell which would be correct from your test data.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pass data from java to cups filter I'm working on the printing system, and need to add arbitrary text to each printed document (like author, document hash, some sysvars and else). We use Java Printing Service (javax.print) as printing client and Cups as server.
Cups has some procedures of document postprocessing called "filters".
Filter - is a program, that will be launched by Cups. Cups passes filter some params - "job attributes" among them.
So, I decided to pass custom attributes from java to cups and add attributes as text to document in filter. Everything works without exception, document is printed, but I don't get my attributes in filter. They are not even passed to Cups (saw that in packet sniffer).
I already used getSupportedAttributeCategories() to see the list of supported (by printer?) attributes. Maybe I should somehow add mine to that list, but I don't understand how.
I'm not limited to "attributes", I just need to pass arbitary data from java to Cups filter. How can I do it?
My java code is like:
MyAttrSet attrs = new MyAttrSet();
attrs.add(new MyAttr(42));
attrs.add(new Copies(18));

PrintService service = PrintServiceLookup.lookupDefaultPrintService();
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
Doc doc = new SimpleDoc(is, flavor, null);
DocPrintJob job = service.createPrintJob();

job.print(doc, attrs);

Filter is a simple bash script, that prints everything passed to it:
#!/bin/bash
echo "All args:" > /tmp/f1.log
for var in "$@"
do
        echo "$var, " >> /tmp/f1.log
done

/tmp/f1.log looks like:
All args:
87,
oroboros,
 Java Printing,
18, <- number of pages is passed! But not MyAttr
some useless crap like job uuid and else...

MyAttr:
class MyAttr extends IntegerSyntax implements PrintRequestAttribute {

    protected MyAttr(int value) {
        super(value);
    }

    public Class<? extends Attribute> getCategory() {
        // TODO Auto-generated method stub
        return MyAttr.class;
    }

    public String getName() {
        // TODO Auto-generated method stub
        return "somemycustop5";
    }

}

A: You can use cups4j
Map attributes = new HashMap();
attributes.put("job-attributes", "print-quality:enum:3#media:keyword:iso_a5_148x210mm");
printJob.setAttributes(attributes);

See the following article of how CUPS upgrade on Linux broke Java libraries and CUPS libraries:
http://www.cups.org/articles.php?L433+TFAQ+Q
Now, since you can print I assume its not an issue. But I am not sure what MyAttrSet is, it should be a HashPrintRequestAttributeSet.
try:
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new Copies(2));

See if this attribute is read in, then try adding yours to such a set, does it work or not.
You might want to try implementing other Attributes:
The Sides attribute looks like this:
public class Sides
  extends EnumSyntax
  implements DocAttribute, PrintRequestAttribute, PrintJobAttribute
  {
  public final Object getCategory()
    {
    return Sides.class;
    }
  ...
  }

Similarly Copies:
public final class Copies
extends IntegerSyntax
implements PrintRequestAttribute, PrintJobAttribute

perhaps try adding the additional implements of PrintJobAttribute


text:
Q: Python | Sorting out redundant text from screen scraper application I'm writing a screen scraper application monitoring a text-only chat window. Text is added at the bottom of the window.
The application takes screenshot of the chat window. If a change has occurred since last screenshot (new_screenshot != old_screenshot), the screenshot is saved.
After X time, all images are merged to one image, where the oldest image is on the top. This large image is send to a server for OCR, and a string of text is returned.
Problem: How to sort out redundant text?
Example:

*

*Chat window is 5 lines high and is initially empty.

*The solution must work with empty and not-empty initial chat window.

*More than one line can be added at each screenshot. The same line can come multiple times, but never two times in a row so just deduplicating is not enough (so using sorted(set(text.split('\n'))) would not be sufficiant)

Input to algorithm:
1 Lorem ipsum dolor sit amet,
1 Lorem ipsum dolor sit amet,
2 consectetur adipiscing elit
1 Lorem ipsum dolor sit amet,
2 consectetur adipiscing elit
3 Mauris porttitor enim sed tincidunt interdum.
1 Lorem ipsum dolor sit amet,
2 consectetur adipiscing elit
3 Mauris porttitor enim sed tincidunt interdum.
4 Morbi elementum erat nec nulla auctor, eget porta odio aliquet.
1 Lorem ipsum dolor sit amet,
2 consectetur adipiscing elit
3 Mauris porttitor enim sed tincidunt interdum.
4 Morbi elementum erat nec nulla auctor, eget porta odio aliquet.
5 Nam aliquet velit vel elementum tristique.
2 consectetur adipiscing elit
3 Mauris porttitor enim sed tincidunt interdum.
4 Morbi elementum erat nec nulla auctor, eget porta odio aliquet.
5 Nam aliquet velit vel elementum tristique.
6 Donec ac tincidunt urna.
3 Mauris porttitor enim sed tincidunt interdum.
4 Morbi elementum erat nec nulla auctor, eget porta odio aliquet.
5 Nam aliquet velit vel elementum tristique.
6 Donec ac tincidunt urna.
7 Proin pretium, metus non porttitor lobortis, tortor sem rhoncus urna
4 Morbi elementum erat nec nulla auctor, eget porta odio aliquet.
5 Nam aliquet velit vel elementum tristique.
6 Donec ac tincidunt urna.
7 Proin pretium, metus non porttitor lobortis, tortor sem rhoncus urna
8 quis finibus leo lorem sed lacus.
5 Nam aliquet velit vel elementum tristique.
6 Donec ac tincidunt urna.
7 Proin pretium, metus non porttitor lobortis, tortor sem rhoncus urna
8 quis finibus leo lorem sed lacus.
1 Lorem ipsum dolor sit amet,
Expected result:
1 Lorem ipsum dolor sit amet,
2 consectetur adipiscing elit
3 Mauris porttitor enim sed tincidunt interdum.
4 Morbi elementum erat nec nulla auctor, eget porta odio aliquet.
5 Nam aliquet velit vel elementum tristique.
6 Donec ac tincidunt urna.
7 Proin pretium, metus non porttitor lobortis, tortor sem rhoncus urna
8 quis finibus leo lorem sed lacus.
1 Lorem ipsum dolor sit amet,

A: Here is the code from what I understood you want (add new lines seen but keeping a history of 5 lines to avoid repeats):
history = 5
lastSeen = dict()
result = []
for idx, line in enumerate(text.split('\n')):
    if line not in lastSeen:
        result.append(line)
    else:
        if lastSeen[line] + history < idx:
            result.append(line)
    lastSeen[line] = idx


text:
Q: Unmarshaling the nested xml data giving null values     <bas:person>

             <req:vehicleinfo>
                <!--Zero or more repetitions:-->
                <bas:item>
                   <sch:modelno>k10</sch:modelno>
                   <sch:type>bs4</sch:type>
                </bas:item>
 <bas:item>
                   <sch:modelno>k12</sch:modelno>
                   <sch:type>bs5</sch:type>
                </bas:item>
             </req:extensionInfo>
    </bas:person>

Assume namespace for bas is some http://xxxxx.person.com
 for req is http://xxxxx.request.com
 for bas http://xxxxx.bas.com
for sch http://xxxxx.sch.com

Here for vehicle info as i may have multiple values, in my Java object i need to have vehicle info as array do to some project dependencies.
Here is my java class
 @XmlRootElement(name="person")
@XmlAccessorType(XmlAccessType.FIELD)
    public class Person implements Serializable{

        @XmlElement(name="vehicleinfo",namespace="http://xxxxx.request.com")
        private VehicleInfo[] vehicleinfo;

// getter & setter

    }

vehicle Info
@XmlAccessorType(XmlAccessType.FIELD)
    public class  VehicleInfo{

        @XmlAttribute(name="modelno",namespace="http://xxxxx.sch.com")
        private String key;
        @XmlAttribute(name="type",namespace="http://xxxxx.sch.com")
        private String value;

 //getter and setter

    }

i am using the following code to unmarshalling
SOAPMessage message = MessageFactory.newInstance().createMessage(null,
                new ByteArrayInputStream(xmlInput.getBytes()));
        JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        Person person= (Person) jaxbUnmarshaller.unmarshal(message.getSOAPBody().extractContentAsDocument());

but m getting key and value as nul for vehicle info

A: JAXB does not work with arrays by nature because Java does not have dynamic arrays. Instead declare your VehicleInfo as ArrayList.


text:
Q: Fatal Exception: android.app.RemoteServiceException with Xiaomi device I'm getting below mention error, i am tried to call service from AppWidgetProvider and the service work in background to update Widget every specific time, some device work normally but on most Xiaomi device this error appeared in crashlytics dashboard
Fatal Exception: android.app.RemoteServiceException
Context.startForegroundService() did not then call Service.startForeground():
ServiceRecord{9229291 u0 /.widgetproviders.UpdateService}

exception detaile
Fatal Exception: android.app.RemoteServiceException: Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{9229291 u0
/.widgetproviders.UpdateService}
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2155)
       at android.os.Handler.dispatchMessage(Handler.java:106)
       at android.os.Looper.loop(Looper.java:236)
       at android.app.ActivityThread.main(ActivityThread.java:8131)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:620)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1011)

this is declartion in mainfest
   <service
            android:name=".widgetproviders.UpdateService"
            android:enabled="true"
            android:exported="true"
            android:permission="android.permission.BIND_JOB_SERVICE" />

i am call this service from AppWidgetProvider
<receiver
            android:name=".widgetproviders.UpdatingWidget"
            android:enabled="true"
            android:exported="true" >
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
                <action android:name="android.intent.action.DATE_CHANGED" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/updating_widget_info" />
</receiver>

this is the AppWidgetProvider  that call service

public class UpdatingWidget extends AppWidgetProvider {

public static final String ACTION_BUTTON_REFRESH = "ACTION_BUTTON_REFRESH";

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    Log.e("UpdatingWidget: ","onUpdate");

    try{
        restartService(context);
    }catch (Exception e){

    }
}

@Override
public void onReceive(Context context, Intent intent) {
    try{
        Log.e("UpdatingWidget: ","onReceive");
        if (intent != null) {
            if (intent.getAction().equals(ACTION_BUTTON_REFRESH)) {
                //make some logic here on button refresh
                Log.e("ACTION_BUTTON_REFRESH: ","ACTION_BUTTON_REFRESH");
                restartService(context);
            } else {
                super.onReceive(context, intent);
            }
        }else{
            super.onReceive(context, intent);
        }
    }catch (Exception e){

    }

}

private void restartService(Context context) {

    Log.e("restartService","restartService");
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        try{
            Intent intent1 = new Intent(context.getApplicationContext(),
                    UpdateService.class);

            ContextCompat.startForegroundService(context, intent1);
        }catch (Exception e3){
        }
    }else{
        try{
            Intent intent1 = new Intent(context.getApplicationContext(),
                    UpdateService.class);

            context.startService(intent1);
        }catch (Exception e1){
        }
    }
}

@Override
public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions) {
    super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions);
    Log.e("UpdatingWidget: ","onAppWidgetOptionsChanged");

    try{
        restartService(context);
    }catch (Exception e){

    }

}

@Override
public void onDeleted(Context context, int[] appWidgetIds) {
    super.onDeleted(context, appWidgetIds);
    Log.e("UpdatingWidget: ","onDeleted");
}

@Override
public void onEnabled(Context context) {
    super.onEnabled(context);
    Log.e("UpdatingWidget: ","onEnabled");
    try{
        restartService(context);
    }catch (Exception e){

    }
}

@Override
public void onDisabled(Context context) {
    super.onDisabled(context);
    Log.e("UpdatingWidget: ","onDisabled");
   try{
       stopService(context);
   }catch (Exception e){

   }
}

private void stopService(Context context) {
    try{
        Intent intent = new Intent(context.getApplicationContext(),
                UpdateService.class);
        context.stopService(intent);
    }catch (Exception e){
    }
}

@Override
public void onRestored(Context context, int[] oldWidgetIds, int[] newWidgetIds) {
    super.onRestored(context, oldWidgetIds, newWidgetIds);
    Log.e("UpdatingWidget: ","onRestored");
    try{
        restartService(context);
    }catch (Exception e){

    }
}
}

please help me to avoid this exception in all device type


text:
Q: I want to sort a json and put it in a for loop to list on web, how can I do?
*

*I have a json
var Model = {
  listAll: function() {
    var boxes = [{
      you:'128';
      him:'250';
      me:'56'
    }, {
      you:'72';
      him:'8';
      me:'101'
    }, {
      you:'224';
      him:'97';
      me:'35'
    }, {
      you:'81';
      him:'35';
      me:'688'
    }];
    return boxes;
  }
};

*and I want to SORT it according to property "him" ascendingly.

*then I want to throw it in a "for" loop to list all the data of the json ascendingly accordingly to "him" on webpage. The code goes like this:
<% for(var i=0; i
 <%= boxes.him %>
 <%= boxes.you %>
 <%= boxes.me %>

 <% } %>
Can anyone teach me how to do it?

A: You have errors in that JSON, values shouldn't be terminated with ";" but ",". Here is working example that extends your model and returns sorted list:
var Model = {
  listAll: function() {
    var boxes = [{
      you:'128',
      him:'250',
      me:'56'
    }, {
      you:'72',
      him:'8',
      me:'101'
    }, {
      you:'224',
      him:'97',
      me:'35'
    }, {
      you:'81',
      him:'35',
      me:'688'
    }];
    return boxes;
  },
  listSorted: function() {
    var sortedBoxes = this.listAll();
    return sortedBoxes.sort(function(a,b) {
        return a['him'] - b['him'];
    });
  }
};
console.log(Model.listSorted());

A: You can do it like this, and you have an example of "for" loop.
var Model = {
    listAll: function () {
        var boxes = [{
            you: '128',
            him: '250',
            me: '56'
        }, {
            you: '72',
            him: '8',
            me: '101'
        }, {
            you: '224',
            him: '97',
            me: '35'
        }, {
            you: '81',
            him: '35',
            me: '688'
        }];

        return boxes;
    }
};

var sortByHim = function (a, b) {
  return a.him - b.him;
}

var sortedList = Model.listAll().sort(sortByHim);

for (var i = 0; i < sortedList.length; i++){
  console.log(sortedList[i].him);
}


text:
Q: Getting Values from Database in Ruby on Rails I have a simple doubt.
I've two drop down fields one for states and other for cities. Im loading these two from my database where I have two tables with name states and cities. Also when I select one state cities are changed acordingly as I have written a jquery code too..
This is how I load all states into my select tag
<%= jl.select :state_id , State.all.map{|j| [j[:name], j[:id]]}, {class: 'select2'} %>

What I want is when I load that page intialy I dont want my cities field to be blank. I want it to be a dropdown list full of cities corresponding to some particular state_id.
So how should my select tag for cities should Look. City table contains name,id and state_id.

A: Add id to your states dropdown
<%= jl.select :state_id , State.all.map{|j| [j[:name], j[:id]]}, {class: 'select2',id:'states_dropdown'} %>

Then your Cities dropdown should look as the following:
<%= jl.select :city_id , City.where(:state_id=> "specific_id").map{|j| [j[:name], j[:id]]}, {class: 'select2'} %>

and add this in your coffee script file
$("#states_dropdown").change ->
        $.ajax
            url: '/category/childrens'
            type: 'GET'
            data :
                state_id: $(this).val()
            success: (data, status, response) ->
                #update cities dropdown
            error: ->
                # Hard error

A: you should write code on load.
var cities_obj_arr = <%= @cities.to_json %>;

$(document).on('change', "#state_select_box", function(){
  var state_id = $(this).val();
  var str_option = '';
  $.each(cities_obj_arr, function(index, city_obj){
     if(state_id == city_obj['city']['state_id']){
       str_option = str_option + "<option value='"+city_obj['city']['name']+"'">"+city_obj['city']['name']+"</option>"; /*city_obj['city']['name'] city is object name for cities*/
     }
  });
  $(this).html(str_opotion);
});

please have a look on image, it will help more.


text:
Q: Is there anyway to annotate only required fields for JAXB I'm working on to convert Hibernate objects to XML using JAXB. In our classes, we've around 50 fields from which I would need only 10 of them.
Basically, I'd defined XmlType#propOrder with 2 properties. JAXB complained that some public getters are not part of proporder.
I see that if I don't mark a property with either of XmlTransient/XmlElement, JAXB complains about it. Is there any way to skip writing 'XmlTransient' on every field?

A: You can use @XmlAccessorType(XmlAccessType.NONE) so that only the annotated fields/properties are marshalled to XML.  JAXB does not require any annotations.  Annotations are only required to override the default behaviour.  What exceptions are you seeing?
For More Information

*

*http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html


text:
Q: How to convert the following optimization problem to quadratic program? Given positive constants $C$ and $\epsilon$ and points $\{ (x^i,b_i)\} _{i=1}^I \subset \mathbb{R}^{n+1}$, how can we rewrite the following optimization problem as minimizing a convex quadratic objective subject to linear constraints?
$$\min _{w\in \mathbb{R}^n} \Big[ \frac{C}{2}w^Tw+ \sum_{i=1}^I \max \{ |w^Tx^i-b_i|-\epsilon,0 \} \Big]$$


text:
Q: Телеграмм-бот, который напоминает тебе о распорядке Лазал по гуглу и так и не смог понять, а как же все-таки заставить бота в фоне делать какие-то дела и отправлять их мне, когда наступает час X. Есть разные предположения: cron, while + sleep. Но второй способ не совсем рабочий, а первый я пока не пробывал, но даже если так, в документации telebot того же не увидел как отправлять сообщения просто без обращения к боту.
В общем, помогите. Потратил вчера вечер, но так и не нашел решения, хотя знаю, что это возможно, так как есть куча ботов, которые постят что-то в чат без обращения к ним :)

A: Читайте доку больше.
Вот пример популярной библиотеки - https://github.com/eternnoir/pyTelegramBotAPI
Ниже кусок простого кода, где text - текст вашего сообщения строкой, а chat_id - это ваш айдишник в телеге. Айдишник можно получить у этого бота @getmyid_bot. С токеном, думаю, все понятно и так.
tb = telebot.TeleBot(TOKEN)
tb.send_message(chat_id, text)

Хотя бы одно сообщение своему боту отправьте, после чего он сможет вам писать.


text:
Q: dynamic method binding in java - why this method? public class A {

    public void m1(A a) {
        System.out.println("m1(A) in A");
    }

    public void m4() {
        System.out.println("m4() in A");
    }
}

public class B extends A{

    public void m1(B b) {
        System.out.println("m1(B) in B");
    }

    public void m4() {
        System.out.println("m4() in B");
    }

}

public class Test {

    public static void main(String[] args) {

        B b = new B();
        A a = b;
        a.m1(b); // returns m1(A) in A
        a.m4();  // returns m4() in B
    }

}

Can someone please explain why a.m1(b) uses the method of A and a.m4() uses the method of B?
I particularly don't understand how this one variable (a) invokes methods of two different classes. I thought that at runtime, a is either seen as an A or a B, which then should result in either both methods from A or both methods from B.

A: It's because B.m1(B) doesn't override A.m1(A). It's an overload instead because its parameter is a different type.
In order to override it, you would need to change the parameter type to A.
Note that it's always a good idea to annotate methods that you think you are overriding with @Override: then the compiler will tell you if you aren't really overriding the method.
Note also that if you called b.m1(b); it would call the method on B, since that overload is more specific that A.m1(A). However, with the current code the only method which can be matched at compile time is A.m1(A), since all is known is that a is either an instance of A or one of its subtypes: the only methods which are known to be available are the methods on A.
The invoked method is chosen at compile time, not runtime.

A: Lets start with the basics of object declaration.
Let's consider a class Animal.
Animal anim=new Animal();

Anim anim tells JVM to create a new reference variable of type Animal and the new Animal() asks the JVM to create a new Animal object. Both these statements combined by = tells JVM to create a reference variable of type Animal and assign a animal object to it.
What does anim ?

*

*anim is similar to a remote control which controls the behaviour of an object of type Animal. We use it to refer to the object.

I hope it's clear till now.
Now let us move on to Inheritance and Polymorphism. Consider a new class Dog which extends Animal. Dog becomes a sub-class of Animal .
In case of inheritance, you could consider the IS A rule. In this case, since Dog has extended Animal , Dog IS A Animal. I hope you got me. This is where polymorphism comes into picture. Polymorphism means you can actually use a super class reference variable to refer to a sub class object.
Animal anim1=new Dog();

We have created a remote control anim1 which controls a Dog object. This anim1 reference (remote control) can only control Animal specific methods of class Dog. This remote control can also control the over-ridden methods but can not control any new method in Dog which is not inherited or over-ridden.
Now, Let us move on to your classes A and B. B IS-A  A  since it has extended A.
This means A a= new B(); is true by polymorphism. This is similar to what yoh have done using the below code:
B b=new B();
A a=b;

Now why does a.m1(b); go to method in A
and a.m4(); go to B?
Let us look at something else before going to that:
You have a method in class A as:
public void m1(A a)
You have a method in class B as:
public void m1(B b)
Overriding means you are actually redefining a inherited method in the sub class. So in your case, m1(B b) in class B is not over-riding since the paraneter it has is different. The parameter it has is of type B while the original m1(A a) in A looks for argument of type A. In short, your class B has 2 methods named as m1.
One which is inherited from A and a new method or over-loaded method with a parameter type B.
Like I have already mentioned, our remote control a can only see the method which is specific to class A. It can't see the over-loaded method. That's the reason, it's actually going to the inherited method m1(A a).
Now, a.m4(); goes to m4() in B. why?

*

*Because m4() in B is an over-ridden method and a can see it.

Had you called b.m1(b), method in B would have been used.
Summing up:
You can use a super class reference variable/remote to refer/point to a sub-class object but this remote can only see inherited methods including over-ridden but not over loaded.
But a reference of sub class type will be able to see all the methods.
To help you identify over-ridden and overloaded methods:
Over-ridden method are like:

*

*Arguments must be same and parameters must be same or compatible.

*Method can not be less accessible. That is public cannot be made private.

Overloaded methods like:

*

*Returns types can be different.

*There should be some change in argument type or number of arguments should be different.

*Access levels can be changed

Using the above rules, you can easily idebtify that m1(B b) in B was actually a overloaded method since the parameter type varies from m1(A a).
Finally, B possessed 3 methods:

*

*m1(A a) inherted

*m1(B b) overloaded

*m4() over-ridden

Please comment if you have any doubts or in case of an error.


text:
Q: About Gap between two adjacent  I have created two div. But when I refresh the page i found gap between the two div. I made sure that margin top of both are 0px. But there is no change. Now I want to reduce the gap between two div.

A: in your CSS, at the top, add
* { margin: 0px; padding: 0px;}Simply removes all padding and margins, which by default are set at 5px.


text:
Q: why the below code is taking two input on single execution of scanf funcion #include<stdio.h>
#include<conio.h>

int main()
{
    int Dividend,divisor;

    printf("Checking Divisiblity of 1st number with 2nd number \n\n") ;

    printf("Enter Number \n") ;
    scanf("%d",&Dividend);

    printf("Enter Divisor = ");
    scanf("%d",&divisor) ;

    if(Dividend % divisor == 0)
    {
        printf("Number %d is divisible by %d",Dividend,divisor) ;
    }
    else
    {
        printf("Number %d is not divisible by %d",Dividend,divisor) ;
    }

    getch();
    return 0;
}

Above is my code that i have written in C ;
on running this program  . Only on first  execution  of scanf   function if i give two input  space seperated , the second input is going on right variable . and on hitting enter i am getting result . I am not understanding how is this happing .

A: When space is pressed, scanf doesn't see anything yet. Something happens only after enter is pressed. It then takes everything to the left of the space character and assigns it to the first variable, and everything to the right of the space character and assigns it to the second variable.
If you don't press the spacebar, scanf will interpret everything you type as a single number and will assign it to the first variable.
Instead what you may want to do is use the %c format specifier to read a single character at a time. You can then check if the character is a space character and if it is, you can break out of the loop. Otherwise, you can keep reading characters until you reach a space character.

A: stdin is line based by default. Your program gets nothing until you press enter. Then your program has the entire line of text available.
Result of this is, that scanf, getchar, fgets, etc calls will not return until you press enter. After enter press, entire line is available and the function starts to process it.

scanf is kinda special, that if you have int parsed_count = scanf("%d%d", &a, &b);, it will read two integers, no matter how many times you press enter, so you can either do
1 2<enter>

Or you can do
<enter>
1<enter>
<enter>
2<enter>

and scanf will still read these two integers (it returns early if there is parse error, which is why you need to check the return value!).

And vice versa, if there is already input available, then scanf may return immediately, so if you have this code
scanf("%d",&Dividend);
printf("Enter Divisor = ");
scanf("%d",&divisor) ;

and enter text
1 2<enter>

Then first scanf will wait for enter press, then consume the first integer, leaving  2<enter> still unread. Then there's print, and then 2nd scanf starts reading, skipping the whitespace and immediately getting 2nd integer. So you see
1 2  <- this is your typing echoed, not print from your program
Enter Divisor =   <- printf printed this

If you want to take only one input per enter press, you can simply read characters until newline, because scanf leaves them there. Example loop to read until newline, or exit program at end of file/error:
while(true) {
    int ch = getchar();
    if (ch == EOF) exit(1);
    if (ch == '\n') break;
}


text:
Q: Crystal Lang project directory structure conventions Are there any conventions regarding project directory structure?
I have a project that was initialized with crystal init app [project-name]. Inside of that is the src directory which has the folders for modules and classes. However, now I want to add an ORM which will require a models directory. What conventions are there for laying this out?
Right now I've created a sub-directory inside of src called modules where classes and modules are going.

A: There is no direct answer here. It very much depends on the pattern you want to follow. If you are using a framework like lucky or amber, I would suggest referring to their documentation as both prefer a conventional (rather than configurable) approach. Both follow a rails'esque convention.
[root]
  ⌙ /src
    ⌙ /models
    ⌙ /controllers
    ⌙ /views

If you are implementing services DDD like modules, then I would suggest:
[root]
  ⌙ /src
    ⌙ /[service/module a]
    ⌙ /[service/module b]


text:
Q: multiple choice quiz in javascript using arrays I have to create a multiple choice state capitals quiz in javascript. I have an array of all 50 states (stateArray) and an array of all 50 capitals (capitalArray) in the correct order. I have a table with the question "What is the capital of (blank)" and I want (blank) to be populated with a state from the stateArray. I then have 4 radio buttons where I want one populated with the correct answer from the capitalArray and the other 3 populated with random capitals from the capitalArray. How do I do this?
I've been looking all over the internet for the answer, but I can't seem to find it. I know how to code the question/radio buttons if I were to type in the text I wanted displayed next to each one, but I don't know how to get it to pull from the arrays. Please help.
EDIT: Ok, maybe I asked this the wrong way. I don't want someone to do my homework for me. There is much more to the assignment, I just can't figure out how to do this one part of it - specifically pulling the data from the arrays to populate the question and radio buttons. I can't find the information in my text book or on the internet. I'm just frustrated and confused at this point and I don't know where to go for help. If someone knows WHERE I can find a tutorial or info on how to do this, that would help too.

To whomever marked down my question: If you're going to mark it down, it would be immensely helpful if you would leave a comment telling me why so I can improve my future questions. Thank you! :-)

A:
I don't know how to get it to pull from the arrays

For every row in your table pick a random index from any array (e.g. states):
var questionIndex = Math.round(Math.random(stateArray.length));

Then use the obtained question index to get the values from both arrays provided that both are in correct order:
var question = stateArray[questionIndex],
    answer = capitalArray[questionIndex];

You can now populate the HTML fields of your row.
Edit:
To get the "incorrect" answers for your radio buttons you can simply:
var incorrectAnswerIndices = [],
    incorrectAnswerIndex;

while (incorrectAnswerIndices.length < 3) {
    incorrectAnswerIndex = Math.round(Math.random(stateArray.length));
    // Check for collisions with the correct answer,
    // and make sure there are no identical answers:
    if (incorrectAnswerIndex !== questionIndex &&
            incorrectAnswerIndices.indexOf(incorrectAnswerIndex) === -1) {
        incorrectAnswerIndices.push(incorrectAnswerIndex);
    }
}

You can now iterate incorrectAnswerIndices array and create/populate values of your false question radio buttons with values, e.g.: capitalArray[incorrectAnswerIndices[0]] which is the first of three incorrect capital names for the given state.


text:
Q: How to declare Arrays in runtime in Vb.net How can I re-declare arrays in VB.NET at runtime?
Example:
When I run my program, I will have 100 arrays then I have my button that says "add", if I click it, a text box will appear and I can type there what ever I want to add in my arrays, also I can delete an existing array, but the problem is for example I want to delete an item, and that item is in array number 6, if I delete it, a new item will replace the array, how will I do it?

A: To re-dimension an array use ReDim Preserve


text:
Q: First steps with threading failed Hi: please further down find my code.
I compiled using mingw with parameters -Wmain;-pedantic;-std=c++11;-Wall.
Codelite set the semicola between the compiler options
Here I tried to learn how to use thread and mutex: https://en.cppreference.com/w/cpp/thread/mutex
The main module contains the global variable std::mutex mtx after the include section
The thread functions are declared and joined in the main() function; the function definitions for friend class SL can be found here as well. Class and method definitions are spread over the next two modules.
These are the error messages, which I cannot handle:
Message 1
C:/Program Files/CodeBlocks/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/thread:240:2: error: no matching function for call to 'std::thread::_Invoker<std::tuple<void (*)(int, int, SL&), int, int, SL> >::_M_invoke(std::thread::_Invoker<std::tuple<void (*)(int, int, SL&), int, int, SL> >::_Indices)'
  operator()()
  ^~~~~~~~

Message 2
C:/Program Files/CodeBlocks/MinGW/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/thread:233:29: error: no matching function for call to '__invoke(std::__tuple_element_t<0, std::tuple<void (*)(int, int, SL&), int, int, SL> >, std::__tuple_element_t<1, std::tuple<void (*)(int, int, SL&), int, int, SL> >, std::__tuple_element_t<2, std::tuple<void (*)(int, int, SL&), int, int, SL> >, std::__tuple_element_t<3, std::tuple<void (*)(int, int, SL&), int, int, SL> >)'
    -> decltype(std::__invoke(_S_declval<_Ind>()...))
     __invoke(_Callable&& __fn, _Args&&... __args)
     ^~~~~~~~

*Message 2 seems to make reference to some type of move constructor ...
I had the idea that the friend function is cause of the dilemma, but was not able to verify
Please help with this.
main module
#include <mutex>
#include <thread>
#include "sl.h"
std::mutex mtx;

void play(int die1, int die2, SL& p){
  std::this_thread::sleep_for(std::chrono::seconds(1));
  mtx.lock();
  if (p.dice.size() > 0) {
    p.dice.resize(0);
    }
  p.set_dice(die1, die2);
  rollDice(p);
  mtx.unlock();
  }

void rollDice(SL& p) {
  int iFound = -1;
  int iAdd = p.dice[0] + p.dice[1];
  p.addPosition(iAdd);
  p.bounceBack();
  if (p.position == 100) {
    printResult(p, iFound);
    std::cout << "Game over" << std::endl;
    return;
    }
  if ((iFound = p.check(SL::ladders, p.position)) != -1) {
      p.setPosition(SL::ladders[iFound].second);
      iFound += 100;
      }
  else if ((iFound = p.check(SL::snakes, p.position)) != -1) {
      p.setPosition(SL::snakes[iFound].second);
      }// snakes, position + iAdd
  printResult(p, iFound);
  if (p.dice[0] == p.dice[1]) {
    mtx.unlock();
    play(rand() %6 + 1, rand() % 6 + 1, p);
    }
  }

void printResult(SL& p, int iFound) {
  std::cout << ++p.iTimes << ") "
            << p.get_name() << "<<<< "
            << p.dice[0] << "|"
            << p.dice[1] << " position: "
            << p.position;

  if (iFound != -1) {
    if (iFound > 100) { // this is a ladder field
      iFound -= 100;
      std::cout << " LADDER from "
                << SL::ladders[iFound].first << "|"
                << SL::ladders[iFound].second;
        }
    else {
      std::cout << " SNAKE from "
                << SL::snakes[iFound].first  << "|"
                << SL::snakes[iFound].second;
        }
      }
    std::cout << std::endl;
    }

int main()
  {
  srand(time(NULL));
  SL one("Player 1"),
                two("Player 2");
  std::thread t1 (play, rand() %6 + 1, rand() %6 + 1, one);
  std::thread t2 (play, rand() %6 + 1, rand() %6 + 1, two);
  while((one.get_position() != 100) && (two.get_position() != 100)) {
    t1.join();

    t2.join();
    }
  return 0;
  }

// Class Declaration
#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <ctime>
#include <iomanip>

class SL {
  public:
  SL(const std::string& strName) : player(strName), position(0), iTimes(0) {}
  ~SL() = default;

  private:
    friend void play(int die1, int die2, SL& p);
    friend void rollDice(SL&);
    friend void printResult(SL&, int);
    static const std::pair<int, int> snakes[];
    static const std::pair<int, int> ladders[];
    std::string player;
    int position;
    int iTimes;
    std::vector<int> dice;
  protected:
    int check(const std::pair<int, int> field[], const int iField);
  public:
    void addPosition(const int iPosition);
    void setPosition(const int iPosition);
    void bounceBack();
    void set_dice(int die1, int die2);
    const int get_position() const;
    const std::string& get_name() const;
    const std::vector<int> get_dice() const;
    };
// friend function
void play(int die1, int die2, SL& p);
void rollDice(SL&);
void printResult(SL&, int =-1);

// Class methods - static variables
#include <mutex>
#include <thread>
#include "sl.h"

inline void SL::addPosition(const int iPosition) {
  position += iPosition;
  }
inline void SL::setPosition(const int iPosition) {
  position = iPosition;
  }
inline void SL::bounceBack() {
  if (position > 100) {
    int iBounceBack = position - 100;
    position -= iBounceBack;
    }
  }
inline void SL::set_dice(int die1, int die2){
  if (dice.size() > 0) {
    dice.erase(dice.begin(), dice.end());
    }
  dice.push_back(die1);
  dice.push_back(die2);
  }
const int SL::get_position() const {return position;}
const std::string& SL::get_name() const {return player;}
const std::vector<int> SL::get_dice() const {return dice;}

int SL::check(const std::pair<int, int> field[], const int iField) {
  const int end = 10;
  int result = -1;
  for ( size_t idx = 0; idx < end; idx++) {
    if (field[idx].first == iField){
      result = idx;
      break;
      }
    else if (iField > field[idx].first)
      break;
    }
  return result;
}

const std::pair<int, int> SL::ladders[] {
      std::make_pair( 2, 38),
      std::make_pair( 7, 14),
      std::make_pair( 8, 31),
      std::make_pair(15, 26),
      std::make_pair(28, 84),
      std::make_pair(36, 44),
      std::make_pair(51, 67),
      std::make_pair(71, 91),
      std::make_pair(78, 98),
      std::make_pair(87, 94)
      };

const std::pair<int, int> SL::snakes[] {
      std::make_pair(16,  6),
      std::make_pair(46, 25),
      std::make_pair(49, 11),
      std::make_pair(62, 19),
      std::make_pair(64, 60),
      std::make_pair(74, 53),
      std::make_pair(89, 68),
      std::make_pair(92, 88),
      std::make_pair(95, 75),
      std::make_pair(99, 80)
      };

A: I tried to go along with G.M.s suggestion and truly I was not able to make it.
For multi threading beginners this is a good stop:
https://hackernoon.com/learn-c-multi-threading-in-5-minutes-8b881c92941f
After reading through all of this I decided for the std::lock guard as so using the mutex mtx global variable from the main module:
void play(int die1, int die2, SL& p){
  std::lock_guard<std::mutex> guard(mtx);
  if (p.dice.size() > 0) {
    p.dice.resize(0);
    }
  p.setDice(die1, die2);
  int iGameOver = 0;
  rollDice(p, iGameOver);
  if (iGameOver)
    return;
  }

In the rollDice function I used to have a recursive call to the rollDice function via play. This configuratin caused a dead lock and I got rid of that logic and replaced the recursion into two loops inside main.
int main()
  {
  srand(time(NULL));
  SL one("Player 1"),
     two("Player 2");
  while((one.getPosition() != 100) && (two.getPosition() != 100)) {
    int die1 = 0,
        die2 = 0;
    if (!two.gameOver()) {
      do {
        die1 = rand() % 6 + 1;
        die2 = rand() % 6 + 1;
        play(die1, die2, one);
        }while(die1 == die2);
      std::cout << "-----------------" << std::endl;
      }
    if (!one.gameOver()) {
      do {
        die1 = rand() % 6 + 1;
        die2 = rand() % 6 + 1;
        play(die1, die2, two);
        }while(die1 == die2);
      std::cout << "-----------------" << std::endl;
      }
    }
  return 0;
  }

The respective logic making another call to rollDice() via play from rollDice was taken off the rollDice function, which now looks like this.
void rollDice(SL& p, int& gameOver) {
  int iFound = -1;
  int iAdd = p.getAdded();
  p.addPosition(iAdd);
  p.bounceBack();
  if (p.getPosition() == 100)
    p.setGameOver();
  if (p.gameOver()) {
    printResult(p, iFound);
    std::cout << "Game over" << std::endl;
    return;
    }
  if ((iFound = p.check(SL::ladders, p.getPosition())) != -1) {
      p.setPosition(SL::ladders[iFound].second);
      iFound += 100;
      }
  else if ((iFound = p.check(SL::snakes, p.getPosition())) != -1) {
      p.setPosition(SL::snakes[iFound].second);
      }// snakes, position + iAdd
  printResult(p, iFound);
  }

I am not really sure, where I went wrong with my original approach, but my first multi threaded test code is successfully implemented and without me posting and getting G.M.s suggestion, it just would not have taken place. Thank you.


text:
Q: IIS8 Default Document yields 404 not found error I have a new Windows Server 2012 machine with IIS 8.
I have installed an application that uses Windows Authentication for the login page.
The application uses .NET 2.0 (which was a bit of a pain to configure, but that is a different story)
The application works perfectly if you specify the login page in the URL.
This login page is the default document for the application which verifies the user and logs them in automatically if they are registered. If they are not registered then it redirects them to a Forms authentication login page where they can enter local application credentials.
The problem I have is that the login page only works when you browse to it directly I.E. type the name in the URL. If you use the Default document from IIs it returns a 404 error.
I have seen other articles here which are for IIS 7 or IIS 7.5 which appear on the surface to be the same as IIS 8 but the solutions for those problems do not resolve my problem.
The application pool is currently configured as Classic (have also tried Integrated) and uses NetworkService as the application Account and has 32 bit enabled. It is configured for .NET Framework v2.0. Default documents are enabled for both the site and the application virtual directory.

A: I think I have solved this problem.  IIS 8 does not seem to respect the order of documents in the list of default documents and was always selecting default.aspx which was shown as the last document in the list.
My main application does not have a default.aspx page.  When I removed all the entries in the list of default documents so that only the one and only document I needed for the main application was shown it worked correctly.
This is a bit of a pain as my application has lots of sub-applications that use different landing pages. One of which uses default.aspx. We usually specified them all at the top level and used inheritance on the sub-applications, but now it seems each sub-application will need to be configured individually.

A: This led me to an answer for my situation. Indeed changing the order of the default documents got my index.html working after I moved it to the top of the list. I did not need to truncate the list any further.
However, the reason I was getting the error is I previously had index.aspx at the top and I did indeed have an index.aspx file in the website. But it turns out ASP.Net was not yet installed on the server. So the server returned a very misleading 404 error on the index.aspx (which was actually there) when it should have either ignored it and gone onto my test index.html file, or given me some message that it could not read .aspx file.

A: We can specify default document in web.config. Specify your default document in web.config and it should work.


text:
Q: How to attach to remote R kernel in VS Code? I am using both R and python for a research project. The computations and all analyses are done in a remote server which I access using SSH. I do not have root privileges to the server.
I have a Conda virtual environment for the project. My usual workflow is connecting to the server through the SSH features of Visual Studio Code and then editing code and running it in the terminal iteratively (using the Remote - SSH extension from Microsoft). When editing Python scripts, everything works great: I can edit the files and run them in the terminal with no error messages and so on.
However, as soon as I start editing an R script, I get some weird error messages although I believe R is correctly set up. See the output of a quick check (out of a simple Terminal shell):

The Conda environment I am working on is r_conda. It shows that it sees R and it's loading it from the correct binary. Even radian seems to be correctly installed in the Conda environment.
When I open an R file in VS Code, I get the following errors:

I am using this R extension.
I have already edited the settings of the extension to point it to the correct binaries:

Does anyone know what is going on? How to solve this?

Following the suggestion from @merv, here is what is installed in the r_conda environment:
(r_conda) [rgr6291@klc0201 ~]$ conda list
# packages in environment at /home/rgr6291/.conda/envs/r_conda:
#
# Name                    Version                   Build  Channel
_libgcc_mutex             0.1                 conda_forge    conda-forge
_openmp_mutex             4.5                       1_gnu    conda-forge
_r-mutex                  1.0.1               anacondar_1    conda-forge
backports                 1.0                        py_2    conda-forge
backports.functools_lru_cache 1.6.4              pyhd8ed1ab_0    conda-forge
binutils_impl_linux-64    2.36.1               h193b22a_2    conda-forge
binutils_linux-64         2.36                 hf3e587d_4    conda-forge
bwidget                   1.9.14               ha770c72_1    conda-forge
bzip2                     1.0.8                h7f98852_4    conda-forge
c-ares                    1.18.1               h7f98852_0    conda-forge
ca-certificates           2021.10.8            ha878542_0    conda-forge
cairo                     1.16.0            ha00ac49_1009    conda-forge
cffi                      1.15.0                   pypi_0    pypi
curl                      7.81.0               h494985f_0    conda-forge
font-ttf-dejavu-sans-mono 2.37                 hab24e00_0    conda-forge
font-ttf-inconsolata      3.000                h77eed37_0    conda-forge
font-ttf-source-code-pro  2.038                h77eed37_0    conda-forge
font-ttf-ubuntu           0.83                 hab24e00_0    conda-forge
fontconfig                2.13.1            hba837de_1005    conda-forge
fonts-conda-ecosystem     1                             0    conda-forge
fonts-conda-forge         1                             0    conda-forge
freetype                  2.10.4               h0708190_1    conda-forge
fribidi                   1.0.10               h36c2ea0_0    conda-forge
gcc_impl_linux-64         9.4.0               h03d3576_11    conda-forge
gcc_linux-64              9.4.0                h391b98a_4    conda-forge
gettext                   0.19.8.1          h73d1719_1008    conda-forge
gfortran_impl_linux-64    9.4.0               h0003116_11    conda-forge
gfortran_linux-64         9.4.0                hf0ab688_4    conda-forge
graphite2                 1.3.13            h58526e2_1001    conda-forge
gsl                       2.7                  he838d99_0    conda-forge
gxx_impl_linux-64         9.4.0               h03d3576_11    conda-forge
gxx_linux-64              9.4.0                h0316aca_4    conda-forge
harfbuzz                  3.2.0                hb4a5f5f_0    conda-forge
icu                       69.1                 h9c3ff4c_0    conda-forge
jbig                      2.1               h7f98852_2003    conda-forge
jpeg                      9d                   h36c2ea0_0    conda-forge
kernel-headers_linux-64   2.6.32              he073ed8_15    conda-forge
krb5                      1.19.2               h48eae69_3    conda-forge
ld_impl_linux-64          2.36.1               hea4e1c9_2    conda-forge
lerc                      3.0                  h9c3ff4c_0    conda-forge
libblas                   3.9.0           12_linux64_openblas    conda-forge
libcblas                  3.9.0           12_linux64_openblas    conda-forge
libcurl                   7.81.0               h494985f_0    conda-forge
libdeflate                1.8                  h7f98852_0    conda-forge
libedit                   3.1.20191231         he28a2e2_2    conda-forge
libev                     4.33                 h516909a_1    conda-forge
libffi                    3.4.2                h7f98852_5    conda-forge
libgcc-devel_linux-64     9.4.0               hd854feb_11    conda-forge
libgcc-ng                 11.2.0              h1d223b6_11    conda-forge
libgfortran-ng            11.2.0              h69a702a_11    conda-forge
libgfortran5              11.2.0              h5c6108e_11    conda-forge
libglib                   2.70.2               h174f98d_1    conda-forge
libgomp                   11.2.0              h1d223b6_11    conda-forge
libiconv                  1.16                 h516909a_0    conda-forge
liblapack                 3.9.0           12_linux64_openblas    conda-forge
libnghttp2                1.43.0               ha19adfc_1    conda-forge
libnsl                    2.0.0                h7f98852_0    conda-forge
libopenblas               0.3.18          pthreads_h8fe5266_0    conda-forge
libpng                    1.6.37               h21135ba_2    conda-forge
libsanitizer              9.4.0               h79bfe98_11    conda-forge
libssh2                   1.10.0               ha35d2d1_2    conda-forge
libstdcxx-devel_linux-64  9.4.0               hd854feb_11    conda-forge
libstdcxx-ng              11.2.0              he4da1e4_11    conda-forge
libtiff                   4.3.0                h6f004c6_2    conda-forge
libuuid                   2.32.1            h7f98852_1000    conda-forge
libwebp-base              1.2.1                h7f98852_0    conda-forge
libxcb                    1.13              h7f98852_1004    conda-forge
libxml2                   2.9.12               h885dcf4_1    conda-forge
libzlib                   1.2.11            h36c2ea0_1013    conda-forge
lineedit                  0.1.6              pyhd8ed1ab_0    conda-forge
lz4-c                     1.9.3                h9c3ff4c_1    conda-forge
make                      4.3                  hd18ef5c_1    conda-forge
ncurses                   6.2                  h58526e2_4    conda-forge
openssl                   3.0.0                h7f98852_2    conda-forge
pandoc                    2.17                 h7f98852_0    conda-forge
pango                     1.50.3               h9967ed3_0    conda-forge
pcre                      8.45                 h9c3ff4c_0    conda-forge
pcre2                     10.37                h032f7d1_0    conda-forge
pip                       21.3.1             pyhd8ed1ab_0    conda-forge
pixman                    0.40.0               h36c2ea0_0    conda-forge
pthread-stubs             0.4               h36c2ea0_1001    conda-forge
pycparser                 2.21               pyhd8ed1ab_0    conda-forge
pygments                  2.11.2             pyhd8ed1ab_0    conda-forge
python                    3.10.2          h543edf9_0_cpython    conda-forge
python_abi                3.10                    2_cp310    conda-forge
r-askpass                 1.1               r41hcfec24a_2    conda-forge
r-assertthat              0.2.1             r41hc72bb7e_2    conda-forge
r-backports               1.4.1             r41hcfec24a_0    conda-forge
r-base                    4.1.2                h2553ce4_1    conda-forge
r-base64enc               0.1_3           r41hcfec24a_1004    conda-forge
r-bayestestr              0.11.5            r41hc72bb7e_0    conda-forge
r-bit                     4.0.4             r41hcfec24a_0    conda-forge
r-bit64                   4.0.5             r41hcfec24a_0    conda-forge
r-blob                    1.2.2             r41hc72bb7e_0    conda-forge
r-brio                    1.1.3             r41hcfec24a_0    conda-forge
r-broom                   0.7.11            r41hc72bb7e_0    conda-forge
r-callr                   3.7.0             r41hc72bb7e_0    conda-forge
r-cellranger              1.1.0           r41hc72bb7e_1004    conda-forge
r-checkmate               2.0.0             r41hcfec24a_1    conda-forge
r-cli                     3.1.0             r41h03ef668_0    conda-forge
r-clipr                   0.7.1             r41hc72bb7e_0    conda-forge
r-colorspace              2.0_2             r41hcfec24a_0    conda-forge
r-cpp11                   0.4.2             r41hc72bb7e_0    conda-forge
r-crayon                  1.4.2             r41hc72bb7e_0    conda-forge
r-curl                    4.3.2             r41hcfec24a_0    conda-forge
r-data.table              1.14.2            r41hcfec24a_0    conda-forge
r-datawizard              0.2.2             r41hc72bb7e_0    conda-forge
r-dbi                     1.1.2             r41hc72bb7e_0    conda-forge
r-dbplyr                  2.1.1             r41hc72bb7e_0    conda-forge
r-desc                    1.4.0             r41hc72bb7e_0    conda-forge
r-diffobj                 0.3.5             r41hcfec24a_0    conda-forge
r-digest                  0.6.29            r41h03ef668_0    conda-forge
r-dplyr                   1.0.7             r41h03ef668_0    conda-forge
r-dtplyr                  1.2.0             r41hc72bb7e_0    conda-forge
r-ellipsis                0.3.2             r41hcfec24a_0    conda-forge
r-evaluate                0.14              r41hc72bb7e_2    conda-forge
r-fansi                   1.0.2             r41hcfec24a_0    conda-forge
r-farver                  2.1.0             r41h03ef668_0    conda-forge
r-fastmap                 1.1.0             r41h03ef668_0    conda-forge
r-forcats                 0.5.1             r41hc72bb7e_0    conda-forge
r-fs                      1.5.2             r41h03ef668_0    conda-forge
r-gargle                  1.2.0             r41hc72bb7e_0    conda-forge
r-gdtools                 0.2.3             r41h42e24d8_0    conda-forge
r-generics                0.1.1             r41hc72bb7e_0    conda-forge
r-ggplot2                 3.3.5             r41hc72bb7e_0    conda-forge
r-ggsci                   2.9             r41hc72bb7e_1003    conda-forge
r-glue                    1.6.0             r41hcfec24a_0    conda-forge
r-googledrive             2.0.0             r41hc72bb7e_0    conda-forge
r-googlesheets4           1.0.0             r41h785f33e_0    conda-forge
r-gtable                  0.3.0             r41hc72bb7e_3    conda-forge
r-haven                   2.4.3             r41h2713e49_0    conda-forge
r-here                    1.0.1             r41hc72bb7e_0    conda-forge
r-highr                   0.9               r41hc72bb7e_0    conda-forge
r-hms                     1.1.1             r41hc72bb7e_0    conda-forge
r-htmltools               0.5.2             r41h03ef668_0    conda-forge
r-httr                    1.4.2             r41hc72bb7e_0    conda-forge
r-ids                     1.0.1             r41hc72bb7e_1    conda-forge
r-insight                 0.15.0            r41hc72bb7e_0    conda-forge
r-isoband                 0.2.5             r41h03ef668_0    conda-forge
r-jquerylib               0.1.4             r41hc72bb7e_0    conda-forge
r-jsonlite                1.7.3             r41hcfec24a_0    conda-forge
r-kableextra              1.3.4             r41hc72bb7e_0    conda-forge
r-knitr                   1.37              r41hc72bb7e_1    conda-forge
r-labeling                0.4.2             r41hc72bb7e_1    conda-forge
r-lattice                 0.20_45           r41hcfec24a_0    conda-forge
r-lifecycle               1.0.1             r41hc72bb7e_0    conda-forge
r-lubridate               1.8.0             r41h03ef668_0    conda-forge
r-magrittr                2.0.1             r41hcfec24a_1    conda-forge
r-mass                    7.3_55            r41hcfec24a_0    conda-forge
r-matrix                  1.4_0             r41he454529_0    conda-forge
r-mgcv                    1.8_38            r41he454529_0    conda-forge
r-mime                    0.12              r41hcfec24a_0    conda-forge
r-modelr                  0.1.8             r41hc72bb7e_0    conda-forge
r-modelsummary            0.9.5             r41hc72bb7e_0    conda-forge
r-munsell                 0.5.0           r41hc72bb7e_1004    conda-forge
r-nlme                    3.1_155           r41h859d828_0    conda-forge
r-openssl                 1.4.6             r41he82ab30_0    conda-forge
r-parameters              0.16.0            r41hc72bb7e_0    conda-forge
r-performance             0.8.0             r41hc72bb7e_0    conda-forge
r-pillar                  1.6.4             r41hc72bb7e_0    conda-forge
r-pkgconfig               2.0.3             r41hc72bb7e_1    conda-forge
r-pkgload                 1.2.4             r41h03ef668_0    conda-forge
r-praise                  1.0.0           r41hc72bb7e_1005    conda-forge
r-prettyunits             1.1.1             r41hc72bb7e_1    conda-forge
r-processx                3.5.2             r41hcfec24a_0    conda-forge
r-progress                1.2.2             r41hc72bb7e_2    conda-forge
r-ps                      1.6.0             r41hcfec24a_0    conda-forge
r-purrr                   0.3.4             r41hcfec24a_1    conda-forge
r-r6                      2.5.1             r41hc72bb7e_0    conda-forge
r-rappdirs                0.3.3             r41hcfec24a_0    conda-forge
r-rcolorbrewer            1.1_2           r41h785f33e_1003    conda-forge
r-rcpp                    1.0.8             r41h03ef668_0    conda-forge
r-readr                   2.1.1             r41h03ef668_0    conda-forge
r-readxl                  1.3.1             r41h2713e49_4    conda-forge
r-rematch                 1.0.1           r41hc72bb7e_1004    conda-forge
r-rematch2                2.1.2             r41hc72bb7e_1    conda-forge
r-reprex                  2.0.1             r41hc72bb7e_0    conda-forge
r-rlang                   0.4.12            r41hcfec24a_0    conda-forge
r-rmarkdown               2.11              r41hc72bb7e_1    conda-forge
r-rprojroot               2.0.2             r41hc72bb7e_0    conda-forge
r-rstudioapi              0.13              r41hc72bb7e_0    conda-forge
r-rvest                   1.0.2             r41hc72bb7e_0    conda-forge
r-sandwich                3.0_1             r41hc72bb7e_0    conda-forge
r-scales                  1.1.1             r41hc72bb7e_0    conda-forge
r-selectr                 0.4_2             r41hc72bb7e_1    conda-forge
r-stringi                 1.7.6             r41h337692f_1    conda-forge
r-stringr                 1.4.0             r41hc72bb7e_2    conda-forge
r-svglite                 2.0.0             r41h03ef668_0    conda-forge
r-sys                     3.4               r41hcfec24a_0    conda-forge
r-systemfonts             1.0.3             r41hef9c87a_0    conda-forge
r-tables                  0.9.6             r41hc72bb7e_0    conda-forge
r-testthat                3.1.1             r41h03ef668_0    conda-forge
r-tibble                  3.1.6             r41hcfec24a_0    conda-forge
r-tidyr                   1.1.4             r41h03ef668_0    conda-forge
r-tidyselect              1.1.1             r41hc72bb7e_0    conda-forge
r-tidyverse               1.3.1             r41hc72bb7e_0    conda-forge
r-tinytex                 0.36              r41hc72bb7e_0    conda-forge
r-tzdb                    0.2.0             r41h03ef668_0    conda-forge
r-utf8                    1.2.2             r41hcfec24a_0    conda-forge
r-uuid                    1.0_3             r41hcfec24a_0    conda-forge
r-vctrs                   0.3.8             r41hcfec24a_1    conda-forge
r-viridislite             0.4.0             r41hc72bb7e_0    conda-forge
r-vroom                   1.5.7             r41h03ef668_0    conda-forge
r-waldo                   0.3.1             r41hc72bb7e_0    conda-forge
r-webshot                 0.5.2             r41hc72bb7e_1    conda-forge
r-withr                   2.4.3             r41hc72bb7e_0    conda-forge
r-xfun                    0.29              r41h03ef668_0    conda-forge
r-xml2                    1.3.3             r41h03ef668_0    conda-forge
r-yaml                    2.2.1             r41hcfec24a_1    conda-forge
r-zoo                     1.8_9             r41hcfec24a_1    conda-forge
radian                    0.5.12             pyhd8ed1ab_0    conda-forge
rchitect                  0.3.35                   pypi_0    pypi
readline                  8.1                  h46c0cb4_0    conda-forge
sed                       4.8                  he412f7d_0    conda-forge
setuptools                60.5.0                   pypi_0    pypi
six                       1.16.0             pyh6c4a22f_0    conda-forge
sqlite                    3.37.0               h9cd32fc_0    conda-forge
sysroot_linux-64          2.12                he073ed8_15    conda-forge
tk                        8.6.11               h27826a3_1    conda-forge
tktable                   2.10                 hb7b940f_3    conda-forge
tzdata                    2021e                he74cb21_0    conda-forge
wcwidth                   0.2.5              pyh9f0ad1d_2    conda-forge
wheel                     0.37.1             pyhd8ed1ab_0    conda-forge
xorg-kbproto              1.0.7             h7f98852_1002    conda-forge
xorg-libice               1.0.10               h7f98852_0    conda-forge
xorg-libsm                1.2.3             hd9c2040_1000    conda-forge
xorg-libx11               1.7.2                h7f98852_0    conda-forge
xorg-libxau               1.0.9                h7f98852_0    conda-forge
xorg-libxdmcp             1.1.3                h7f98852_0    conda-forge
xorg-libxext              1.3.4                h7f98852_1    conda-forge
xorg-libxrender           0.9.10            h7f98852_1003    conda-forge
xorg-libxt                1.2.1                h7f98852_2    conda-forge
xorg-renderproto          0.11.1            h7f98852_1002    conda-forge
xorg-xextproto            7.3.0             h7f98852_1002    conda-forge
xorg-xproto               7.0.31            h7f98852_1007    conda-forge
xz                        5.2.5                h516909a_1    conda-forge
zlib                      1.2.11            h36c2ea0_1013    conda-forge
zstd                      1.5.1                ha95c52a_0    conda-forge


text:
Q: Error while trying to "Export to Excel" a custom list in SharePoint Online I am using SharePoint Online and Excel 2016. When I try to "Export to Excel" a custom list, I get the following errors:

My version of Excel 2016 comes from Microsoft Office Professional Plus 2016.
I am the SharePoint Admin, so it shouldn't be a permission error.
Please advise. Thank you.

A: first of all, try using a different browser like Chrome/ Firefox, where the 'query.iqy' file will be downloaded automatically to your 'Downloads' folder. Now, go to the download location and right click on the *.iqy file to go to 'Properties' menu.

Here, you will see on check box called 'Unblock'. This is a security feature from Windows which prevents file downloaded from other location to execute scripts in your machine. You can click on the 'Unblock' check box to tell windows that you trust the file and then open the file and click 'Enable' in the security notice to load the data in Excel sheet properly.

A: I can reproduce your issue, When I "Export to Excel" a custom list, I get the following notification:"data connections have been blocked. if you choose to enable......"

Choose Enable, it will open the excel.
If you don't want to see the notification, change external content settings for Excel in the Trust Center:
In Excel, click the File tab > Click Options > Trust Center > Trust Center Settings, and then click External Content > choose the option "Enable all Data Connections (not recommended)" under Security settings for Data Connections:

For more detailed information, refer to the following article:
https://support.office.com/en-us/article/block-or-unblock-external-content-in-office-documents-10204ae0-0621-411f-b0d6-575b0847a795


text:
Q: django model instance value set to none after the loop Here, in the rename_dfs function, I am getting the Documents_details model instance and setting its corresponding fields inside the loop. Inside the for loop, some instance field values are getting set, but after the for loop, the instance field value automatically set to None.
def rename_dfs(documentId, request):
    doc_details = Documents_details.objects.get(id=documentId)

    for key, value in request.items():
        if request[key] and key != 'csrfmiddlewaretoken':
            if re.search("_a$", key):
                doc_details.key = int(value)
                print(key, doc_details.key)

            if re.search("_b$", key):
                doc_details.key = int(value)
                print(key, doc_details.key)

    print(doc_details.document_date_a)

    doc_details.save()

Output:
document_date_a 7
invoice_no_a 5
invoice_type_a 3
narration_a 2
debit_credit_a 1

document_date_b 5
invoice_no_b 4
invoice_type_b 3
narration_b 2
debit_credit_b 1

None # last print statement after the loop

Model:
class Documents_details(models.Model):
    company_name_a = models.CharField(max_length=50)
    document_date_a = models.IntegerField(null=True, blank=True)
    posting_date_a = models.IntegerField(null=True, blank=True)
    invoice_no_a = models.IntegerField(null=True, blank=True)
    invoice_type_a = models.IntegerField(null=True, blank=True)
    narration_a = models.IntegerField(null=True, blank=True)
    debit_a = models.IntegerField(null=True, blank=True)
    credit_a = models.IntegerField(null=True, blank=True)
    debit_credit_a = models.IntegerField(null=True, blank=True)

    company_name_b = models.CharField(max_length=50)
    document_date_b = models.IntegerField(null=True, blank=True)
    posting_date_b = models.IntegerField(null=True, blank=True)
    invoice_no_b = models.IntegerField(null=True, blank=True)
    invoice_type_b = models.IntegerField(null=True, blank=True)
    narration_b = models.IntegerField(null=True, blank=True)
    debit_b = models.IntegerField(null=True, blank=True)
    credit_b = models.IntegerField(null=True, blank=True)
    debit_credit_b = models.IntegerField(null=True, blank=True)

    documents = models.ForeignKey(Documents, on_delete=models.CASCADE)

Thanks in advance

A: This isn't the right way to set attribute value dynamically, add the value is assigned to attribute key
It shall be
setattr(doc_details,key, int(value))


text:
Q: Locate Objects in Collection with multiple keys Have a class with attributes attr1, attr2, attr3 and attr4.
I am looking for a way to load a bunch of objects of that class in an array (or ArrayList or Map or whatever) and then being able to retrieve (search) these objects based on attr1 or attr2.
It looks like the way to go is HashMap but I will have to:

*

*if I want only one HashMap, I will have two entries for each object, one with key attr1 and one with key attr2

*have two HashMap objects, one with key attr1 and the other with key attr2 and based on what I am searching for, use the appropriate Map.
Is there any other elegant way of doing this? Is there a Map or Collection object that will allow me to provide multiple keys for an object?

A: I find the second solution with two Map objects quite elegant, each Map being a sort of index of your data. If you really want one single structure, then you can use Guava's Table, who is mapping values to a pair of keys.


text:
Q: Setting textbox value in modal window using onclick button using Bootstrap I ma trying to display username in modal text box using onclick button
I have a button from there on onclick i am calling onclick="getUserName(this.id)"
this.id

gives me name which i want to set in
modal textbox userName

Here is my function
function getUserName(username) {
      $('#editUserPopUp').bind('show',function(){
          alert(username);
          $("#userName").val(username);
      });
 }

I am getting username in alert(username)
but how do i set thsi value to my modal, username text field
Here is my Modal

Update Password

        <form class="EditUserBody" role="form" id="usermanagement_editUser="novalidate" method="POST">

           User Name
             <input class="form-control" id="userName" type="text" class="input-medium" disabled />

        </form>

A: This should work.
But you should also take a look at the Bootstrap documentation about modal windows. There is a section explaining how to vary modal content.
Varying modal content based on trigger button

Use event.relatedTarget and HTML data-* attributes (possibly via jQuery) to vary the contents of the modal depending on which button was clicked.

function getUserName(username) {
  var $modal = $('#editUserPopUp'),
      $userName = $modal.find('#userName');
  $userName.val(username);
  $modal.modal("show");
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>

<button onclick="getUserName(this.id)" id="Foo Bar">Open Modal</button>

Update Password

        <form class="EditUserBody" role="form" id="usermanagement_editUser="novalidate" method="POST">

           User Name
             <input class="form-control" id="userName" type="text" class="input-medium" disabled />

        </form>

A: I think the problem is you are using show event,instead try call shown event after all, like so :
function getUserName(username) {
  $('#editUserPopUp').modal('show');

  $('#editUserPopUp').on('shown', function () {
    alert(username);
    $("#userName").val(username);
  })

}

p/s : did't test it. Hope this help. Comment if did't work.


text:
Q: How to check the space complexity of this program? I have written my version of strstr function in c. I am using a temporary array of size 26. Then is the space complexity O(1) or O(n)?
This is my code :
void strcheck(char t[], int n, char p[], int m)
{
    int i, j, k;
    int temp[26];

    for (i = 0; i < 25; ++i)
        temp[i] = 0;
    for (i = 0; i < n; ++i)
    {
        k = t[i] - 'a';
        temp[k]++;
    }
    for (j = 0; j < m; j++)
    {
        k = p[j] - 'a';
        if (temp[k] > 0)
            temp[k]--;
        else
            break;
    }
    if (j == m)
        printf("string occured\n");
    else
        printf("not occured\n");
}

The program is working correctly just wanna know about space complexity. Thanks

A: This is using O(1) (also Big-Theta(1), as the best-case and worst-case use are the same figure) space-complexity as the the amount of space needed to perform the operation does not increase with n.


text:
Q: Load Async reducers and sagas in react-boilerplate with React router v4 I am looking at migrating a project to the latest react-boilerplate version and many modules have changed. I am having trouble with React router v4 to play with my reducers and sagas. I looked at Dynamically load redux reducers with react router 4
and I am getting the following error now:
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.

Check the render method of withReducer(Component).
      in withReducer(Component) (created by Route)
      in Route (created by App)
      in Switch (created by App)
      in div (created by App)
      in App (created by Connect(App))
      in Connect(App) (created by Route)
      in Route (created by withRouter(Connect(App)))
      in withRouter(Connect(App))
      in Router (created by BrowserRouter)
      in BrowserRouter
      in IntlProvider (created by LanguageProvider)
      in LanguageProvider (created by Connect(LanguageProvider))
      in Connect(LanguageProvider)
      in Provider

My code is slightly different to the example I followed because I am adding withRouter:
const withConnect = withRouter(connect(mapStateToProps, mapDispatchToProps));

const addHelpReducer = injectReducer({ key: 'help', reducer: helpReducer });

export default compose(
    addHelpReducer,
    withConnect
  )(Help);

injectReducer comes from the react-boilerplate utils file, I have not modified that file or the configureStore file.

A: I figured out how to do this:
export default compose(
    withRouter,
    withReducer,
    withSaga,
    withConnect
  )(Help);

Although I now moved into a different issue. Closing this one.


text:
Q: PowerShell output contents of hash to file I have code to output a sorted hashtable to the screen:
$h.getenumerator() | sort value -descending

It looks like this:
Name                           Value
----                           -----
10.10.10.10 69566308           151
10.10.10.11 69566308           143
10.10.10.12 69566308           112
10.10.10.13 69566308            99
10.10.10.14 69566308            71
10.10.10.15 69566308            70

But I would like to output this to a file instead.
When I try to output to a file with
$h.getenumerator() | sort value -descending | out-string | Add-Content D:\Script\iis_stats.log

or
$h.getenumerator() | sort value -descending | Add-Content D:\Script\iis_stats.log

All I get is "System.Collections.DictionaryEntry" in D:\Script\iis_stats.log.
How do I fix it?

A: If you want it in the same format it displays on the screen (folded at the pipes for readability):
$h.getenumerator() |
  Sort-Object value -descending |
  Format-Table |
  Out-String |
  Add-Content D:\Script\iis_stats.log

A: You would get similar output on your screen if you did something like this as well:
$h.GetEnumerator() | sort value -Descending | ForEach-Object{
    $_.GetType().FullName
}

For every entry you would see System.Collections.DictionaryEntry since it does not have a proper string equivalent.
Then you should just do what mjolinor suggests. PowerShell automatically appends the | Out-Default command to the console so that it displays in a way that is visually pleasing. When you send the output to Add-Content that prettification cannot occur.


text:
Q: Run command-line SQLite query and exit We can use the -cmd option with sqlite3 to run a query, but then sqlite3 opens the database and waits in there for interactive input. How can we run a query on sqlite3 from the command line and exit?

A: If you are stuck in a situation where you absolutely "have to" use the -cmd flag when you are running SQLite 3 from the command line, you can use successive blank command to exit.
For example:
sqlite3 test.db "select * from urls;" "" > test.txt

In this example, the "" will cause the SQLite 3 process to exit. (At least it does for me on OS X.)

A: You can use the .exit command (1), to exit gracefully:
sqlite3 test.db "select * from abc;" ".exit"

Documentation: Command Line Shell For SQLite.

A: Just include the command in quotes after the database file argument.
For example, the following creates a table called abc:
sqlite3 test.db 'create table abc (col0 int)'

A: Also it might be useful to have multiline queries:
sqlite3 ./database.db <<EOF
    SELECT *
    FROM something
    LIMIT 5
EOF

A: As it is mentioned in the question, we can also make use of the '-cmd' option and... apply some shell 'magic' at the end (to imitate user manual 'exit'). Let's evaluate a sql expression:
#!/bin/sh
sqlite3 -cmd "select 5.0/2;" < `echo ".exit"`

2.5

This approach is effective, when we have to submit '.xxx' sqlite meta-commands (i.e. .show or .stat) as well:
sqlite3 -cmd ".stat" < `echo ".exit"`

Memory Used:                         0 (max 56) bytes
Number of Outstanding Allocations:   0 (max 2)
Number of Pcache Overflow Bytes:     0 (max 0) bytes
Largest Allocation:                  40 bytes
Largest Pcache Allocation:           0 bytes
Bytes received by read():            10992
Bytes sent to write():               253
Read() system calls:                 19
Write() system calls:                6
Bytes read from storage:             0
Bytes written to storage:            0
Cancelled write bytes:               0

Note: Tested in dash & bash. Should also play in zsh, fish, etc.

A: There are queries and there are dot-commands.
What can we pass to sqlite3? Let us check.
% sqlite3 --help
Usage: sqlite3 [OPTIONS] FILENAME [SQL]

We can also use dot-commands in place of [SQL]. However, there might be some exceptions which i am not aware about.
To list all dot-commands,run:
sqlite3 test.sqlite .help

Here, test.sqlite is the FILENAME.
To view the schema of the database, run:
sqlite3 test.sqlite .schema

To list all tables of the database, run:
sqlite3 test.sqlite .tables

If you must use -cmd then the command will look like:
sqlite3 -cmd .tables test.sqlite .quit

Now you can run query on the databases using:
sqlite3 test.sqlite "select * from DATABASE_NAME"

If you must use -cmd then the command will look like:
sqlite3 -cmd "select * from object_store" test.sqlite .quit

You might have already noticed, when using -cmd we are using more than one commands. Yes, we can do something like:
sqlite3 test.sqlite ".print The Tables Are:\n" ".tables" ".print \nThe Schema is:\n" ".schema" ".print \nList Of All Customers:\n" "select * from customers"

If you must use -cmd then the command will look like:
sqlite3 -cmd ".print The Tables Are:\n" -cmd ".tables" -cmd ".print \nThe Schema is:\n" -cmd ".schema" -cmd ".print \nList Of All Customers:\n" -cmd "select * from object_store" test.sqlite .quit

NOTE: From previous examples, we can see that, we only need to use .quit or .exit, if you use -cmd. Otherwise, it is not needed.

A: This command below inserts a row to person table, then reads person table in db.sqlite3 database then exits at once. *".exit" command is not needed to exit because after all queries complete, sqlite automatically exits:
sqlite3 db.sqlite3 "INSERT INTO person VALUES ('John');" "SELECT * FROM person;"


text:
Q: Не стартует Apache на CantOS8 Не стартует Apache на CentOS 8...
#systemctl status httpd
 httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
  Drop-In: /usr/lib/systemd/system/httpd.service.d
           └─php-fpm.conf
   Active: failed (Result: exit-code) since Wed 2020-10-21 11:28:45 EDT; 1min 0s ago
     Docs: man:httpd.service(8)
  Process: 27606 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited, status=1/FAILURE)
 Main PID: 27606 (code=exited, status=1/FAILURE)
   Status: "Reading configuration..."

Oct 21 11:28:45 web.chipman.local systemd[1]: Starting The Apache HTTP Server...
Oct 21 11:28:45 web.chipman.local httpd[27606]: no listening sockets available, shutting down
Oct 21 11:28:45 web.chipman.local httpd[27606]: AH00015: Unable to open logs
Oct 21 11:28:45 web.chipman.local systemd[1]: httpd.service: Main process exited, code=exited, status=1/FAILURE
Oct 21 11:28:45 web.chipman.local systemd[1]: httpd.service: Failed with result 'exit-code'.
Oct 21 11:28:45 web.chipman.local systemd[1]: Failed to start The Apache HTTP Server.

/etc/httpd/conf.d/web.conf
<VirtualHost *:80>

    ServerName web.chipman.local
    ServerAlias www.web.chipman.local
    DocumentRoot /srv/www/site1

    ErrorLog /srv/www/logs/errors.log
    CustomLog /srv/www/logs/access.log common

    <Directory /srv/www/site1>
        Options FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

</VirtualHost>

Подскажите в чём проблема и как решить?

A: Апач не слушает никакой порт. Добавим строчку Listen 80
Listen 80
<VirtualHost *:80>

    ServerName web.chipman.local
    ServerAlias www.web.chipman.local
    DocumentRoot /srv/www/site1

    ErrorLog /srv/www/logs/errors.log
    CustomLog /srv/www/logs/access.log common

    <Directory /srv/www/site1>
        Options FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

</VirtualHost>

Перегружаем апач, в случае если сработало, эту строчку переносим в файл ports.conf (Если он есть и подгружается, не обязательно, просто для структуризации) потом опять перегружаем апач


text:
Q: jQuery multiple parent() calls I have this for loop that gets the id and text of parents elements:
for (var i = 1; i < parents_num; i++)
{
  var prev_parent_text = jQuery(id).parent().parent().find('> .myclass').text();
  var prev_parent_id = jQuery(id).parent('ul').parent('li').attr('id');
}

What I am trying to do is to increase the number of parent() by 2 in each loop:
For example,
for i = 1:
var prev_parent_text = jQuery(id).parent().parent().find('> .myclass').text();
var prev_parent_id = jQuery(id).parent('ul').parent('li').attr('id');

for i = 2:
var prev_parent_text = jQuery(id).parent().parent().parent().parent().find('> .myclass').text();
var prev_parent_id = jQuery(id).parent('ul').parent('li').parent('ul').parent('li').attr('id');

for i = 3:
var prev_parent_text = jQuery(id).parent().parent().parent().parent().parent().parent().find('> .myclass').text();
var prev_parent_id = jQuery(id).parent('ul').parent('li').parent('ul').parent('li').parent('ul').parent('li').attr('id');

and so on..
I have used the eq() function unsuccesfully:
var num = (i*2) - 2
var prev_parent_text = jQuery(id).parent().eq(num).find('> .myclass').text();
var prev_parent_id = jQuery(id).parent('ul').parent('li').eq(num).attr('id');

Thank you for any help

A: Keep a reference for each, and update the reference for each step:
var $id = jQuery(id);
var $li = jQuery(id);

for (var i = 1; i < parents_num; i++) {
  $id = $id.parent().parent();
  $li = $li.parent('ul').parent('li');
  var prev_parent_text = $id.find('> .myclass').text();
  var prev_parent_id = $li.attr('id');
}

A: You could add a custom jquery function for that, like this:
$.fn.nparent = function(n) {
    var elem = $(this);
    for (var i=0;i<n;i++) {
       elem = elem.parent();
    }
    return elem;
}

And use it like:
var id = $('#element').nparents(4).attr('id');


text:
Q: Android URL wont connect after service is running for a longer period I'm not sure how to even put a good title to this question.
I have the following class in my Android app:
class Translator {
    public Translator() {
    }

    public String bingTranslate(String text) throws IOException {

        String response;
        String textEncoded= URLEncoder.encode(text, "utf-8");

        String url = "https://www.bing.com/tdetect";
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        con.setRequestMethod("POST");
        //con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "UTF-8");

        con.setDoOutput(true);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(con.getOutputStream());
        outputStreamWriter.write("text="+textEncoded);
        outputStreamWriter.flush();

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        response=in.readLine();
        in.close();
        con.disconnect();

        return response;

    }
}

And I'm calling it like this:
detected = new Translator().bingTranslate(text.substring(0, Math.min(text.length(), 100)));

This works absolutely fine, however after my service runs for a long time (like a day or so), the URL fails to connect throwing me errors failed to connect. Force-stopping the service and restarting it makes the whole think work again.
My service is extending NotificationListenerService so it's always running, and it tries to use Bing to detect the language of some notifications.
The detect string is a local variable and the Translator class is not referenced anywhere else. First I thought it might somehow remain referenced because I was using the Translator class as a field.  But even after moving the Translator to a local call the problem still resurface.
What I noticed when the connection fails, the URL throws and error that it failed to connect to: https://www.bing.com/204.79.197.200:443 which isn't really the URL string I used to make the call.
Am I'm missing the obvious or is this potentially a bug in Android?
As a footnote question any suggestion for an alternative to make the http call? I looked at Volley but that works with callbacks and I'm not too keen to make changes to my whole app to accommodate that.
UPDATE
I have now changed the code and switched over to Volley which seems to work fine even after 3 days, so far so good, but the question remains why the simple Https connection fails after some time? I was just not able to figure it out...

A: Looking at your question, I assume that you want the service to run infinitely, but it is only running for a day and throwing the exception.
What I believe is the Android OS is restricting your service to run for longer time due to some restriction Android team have introduced. Your service can't run for longer period of time because this long running services will drain a lot of battery and Android CPU resources.
If you are using the background service than this is not a proper solution for implementing the long running services, what I suggest is you use the Foreground service and let the application show one notification, this will not let the Android OS destroy your service.
Hope this helps.


text:
Q: Why do we have to manually flush() the EntityManager in a extended PersistenceContext? In our J2EE application, we use a EJB-3 stateful bean to allow the front code to create, modify and save persistent entities (managed through JPA-2).
It looks something like this:
@LocalBean
@Stateful
@TransactionAttribute(TransactionAttributeType.NEVER)
public class MyEntityController implements Serializable
{
    @PersistenceContext(type = PersistenceContextType.EXTENDED)
    private EntityManager em;

    private MyEntity current;

    public void create()
    {
        this.current = new MyEntity();
        em.persist(this.current);
    }

    public void load(Long id)
    {
        this.current = em.find(MyEntity.class, id);
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void save()
    {
        em.flush();
    }
}

Very important, to avoid too early commits, only the save() method is within a transaction, so if we call create(), we insert nothing in the database.
Curiously, in the save() method, we have to call em.flush() in order to really hit the database. In fact, I tried and found that we can also call em.isOpen() or em.getFlushMode(), well anything that is "em-related".
I don't understand this point. As save() is in a transaction, I thought that at the end of the method, the transaction will be committed, and so the persistent entity manager automatically flushed. Why do I have to manually flush it?
Thanks,
Xavier

A: To be direct and to the metal, there will be no javax.transaction.Synchronization objects registered for the EntityManager in question until you actually use it in a transaction.
We in app-server-land will create one of these objects to do the flush() and register it with the javax.transaction.TransactionSynchronizationRegistry or javax.transaction.Transaction.  This can't be done unless there is an active transaction.
That's the long and short of it.
Yes, an app server could very well keep a list of resources it gave the stateful bean and auto-enroll them in every transaction that stateful bean might start or participate in.  The downside of that is you completely lose the ability to decide which things go in which transactions.  Maybe you have a 2 or 3 different transactions to run on different persistence units and are aggregating the work up in your Extended persistence context for a very specific transaction.  It's really a design issue and the app server should leave such decisions to the app itself.
You use it in a transaction and we'll enroll it in the transaction.  That's the basic contract.
Side note, depending on how the underlying EntityManager is handled, any persistent call to the EntityManager may be enough to cause a complete flush at the end of the transaction.  Certainly, flush() is the most direct and clear but a persist() or even a find() might do it.

A: If you use extended persistence context all operations on managed entities done inside non-transactional methods are queued to be written to the database. Once you call flush() on entity manager within a transaction context all queued changes are written to the database. So in other words, the fact that you have a transactional method doesn't commit the changes itself when method exits (as in CMT), but flushing entity manager actually does. You can find full explanation of this process here

A: Because there is no way to know "when" the client is done with the session (extended scope).


text:
Q: Can AWS Lambdas receive inbound TCP connections? Is there any way to make an AWS lambda receive an inbound TCP connection (for instance from another lambda)?
EDIT: I'm not asking whether it's possible to call a lambda from another.

A: No not directly. You can only make a connection to Lambda by going through API gateway via HTTP/HTTPS. Your lambda function will be given an HTTP endpoint but the IP address this resolves to is still API gateway and not your lambda function. Invoke a AWS Lambda function by a http request
Why?
I suspect its because each lambda function shares its IP address with lots of other lambda functions located on the VM. They run on containers on top of EC2 instances so you would have several customers running on the same IP address. I've seen no documentation detailing what AWS is really doing but I would guess each container runs on a different port so for you to connect directly to your container you'd need to know the "current" port and not just the IP address. Ontop of that, theres no reason to give the containers public IP addresses. They all probably live in a private subnet.
If you want more confirmation you can explore the AWS lambda console and find no lambda properties other than the HTTP endpoint for API gateway. And if you google the SDK docs you won't come across any IP address retrieval functions.

A: No.
I am sure AWS pretty much locked it down for obvious reasons.
Besides each container only lives for as long as something keeps on invoking it and dies after around five minutes of non-usage.


text:
Q: Cyclic numbering of graph in Python How do I assign cyclic numbers to graph vertices and generate adjacency matrix corresponding to it? The current and desired output is attached.
import networkx as nx
n = 5
p = 0.8
G = nx.generators.random_graphs.gnp_random_graph(n, p)
nx.draw(G)

A = nx.adjacency_matrix(G)
T=A.toarray()
print(T)

Current output

Desired output

A: Your have to activate labels with the keyword with_labels=True. The function nx.draw() accepts all keywords of the function draw_networkx, but has different default values.
Example
import networkx as nx
n = 5
p = 0.8
G = nx.generators.random_graphs.gnp_random_graph(n, p)
nx.draw(G, with_labels=True)

A = nx.adjacency_matrix(G)
T=A.toarray()
print(T)

Example Output


text:
Q: Is there a standard way to preserve const correctness of underlying objects in smart pointers members? Say you have the following classes:
class Bar {
public:
    int nonConstFunc();
};

class Foo {
public:
    int someConstFunction() const
private:
    std::shared_ptr<Bar> m_bar;
};

Is there any way to enforce that we cannot call non-const functions of Bar inside the Foo's const functions? If we did not use a smart pointer here, this would not be a problem.
This is mostly theoretical, but can be the source of mistakes that go unnoticed.
I came up with this solution:
template<class T>
class smart_ptr
{
public:
    smart_ptr() = default;
    smart_ptr(typename T::element_type *u)
        : m_ptr(u)
    {
    }

    typename T::element_type *operator->() { return m_ptr.get(); }
    const typename T::element_type *operator->() const { return static_cast<const typename T::element_type *>(m_ptr.get()); }

private:
    T m_ptr;
};

And then use smart_ptr<std::shared_ptr< Bar >> m_bar; instead, but I'm wondering if there's a standard solution to this problem.