text:
Q: Nulls not returning in Query I have the following query that I want to exclude 'No' values for. I want to include N/A, Yes, and null. 'No', 'Yes', 'N/A', and 'null' are the only values in this column. When I run my query it does not return the null values but, it does return 'N/A' and 'Yes'.

select s.schoolid as "School Code",
       sch.name as "School Name",
       s.student_number as "Student Id",
       s.lastfirst as "Name",
       s.gender as "Gender",
       s.grade_level as "Grade",
       s.street as "Street",
       s.city as "City",
       s.state as "State",
       s.zip as "Zip",
       s.home_phone as "Home Phone"
from u_students u
  left join students s on u.studentsdcid = s.dcid
  left join schools sch on s.schoolid = sch.school_number
where s.grade_level in ('11','12')
  and s.enroll_status = '0'
  and U.Scs_Perm_Share_Military Not like 'No'
order by sch.name asc ;

A: If a SELECT statement is to test for null values in addition to others, it must include an IS NULL clause.  Also as others have stated you should use left joined conditions instead of putting filter in the where clause:
select s.schoolid as "School Code",
       sch.name as "School Name",
       s.student_number as "Student Id",
       s.lastfirst as "Name",
       s.gender as "Gender",
       s.grade_level as "Grade",
       s.street as "Street",
       s.city as "City",
       s.state as "State",
       s.zip as "Zip",
       s.home_phone as "Home Phone"
from u_students u
  left join students s on u.studentsdcid = s.dcid
                      and s.grade_level in ('11','12')
                      and s.enroll_status = '0'
  left join schools sch on s.schoolid = sch.school_number
where (U.Scs_Perm_Share_Military IS NULL
       OR
       U.Scs_Perm_Share_Military <> 'No'
      )
order by sch.name asc ;


text:
Q: Write csv file column by column I want to write a csv file column by column using python.
I read my data from a first csv file and, if the header is 'ok', then I want to copy the column.
I tried the following:
         for column in zip(*data):
            l= []
            if column[0] == 'ok' :
                for k in column:
                    l.append(k)

            my_writer.writerow(zip(*l))

But it raises the error:
    wrt.writerow(zip(*l))
_csv.Error: sequence expected

I then tried with writerows instead of writerow, but the result is clearly not what I expect: The first column contains parts of the names of the headers...
Any idea?

A: First of all, you have a syntax error: if column[0] = 'ok' :, it should be if column[0] == 'ok':
Then you will need to create an object that will create a row, with one element per row on the first iteration (for the first column), and then you keep appending your result to it, until you reach the end.
At this point you can write into the csv file.
Also, have a look at the CSV module.

redpajama_set_name: RedPajamaStackExchange


text:
Q: QlikView Dynamic Date Comparisons I'm relatively new to Qlikview and have a dataset that shows metrics by date.
This data spans two years and the requirement is to have a comparison/variance that is dynamic and can handle the date filters on the report.
For example if the user selects 2018 this field should show the current date compared to the previous year date. Similar for Quarters, months, weeks and weekdays.
Ideally it should always show for the previous period. They've had this created in Excel but it can't handle the amount of records and I suggested QlikView as I had created some other Dashboards in it.
I have tried set analysis though I struggle to see how that would fit into one expression.
Any thoughts would be appreciated!

A: I would say you would need two expressions, one without a set analysis (that would be filtered by your current selection) and one with a set analysis to guarantee that you only get today's value. This would be something like :
Sum($<[Date Field] = {"$(=Date(Today(), 'DD/MM/YYYY'))}>} [Value Field])

Check the date format conversion to see if it matches the date format of your field.


text:
Q: can we use Empty XSD ComplexType(Base) in Extension under Complex content in Child ComplexType? In Below XSD Format, is it the best way to use ObjectType in the Extension?? Do We really required in any aspect..any one help on this. shall i remove this objectType extension inside message..??
***<complexType name="ObjectType"/>***
<complexType name="Message">
        <complexContent>
            ***<extension base="ObjectType">***
                <sequence>
                <element name="element1" type="string" minOccurs="1" maxOccurs="1">
                </element>
                </sequence>
                </extension>
        </complexContent>
</complexType>

A: This XSD is correct (semantically and syntactically). I validate also by XMLSpear
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema elementFormDefault="qualified" targetNamespace="http://yourNamespace"
    xmlns="http://yourNamespace" xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xs:complexType name="ObjectType"/>

    <xs:complexType name="Message">
        <xs:complexContent>
            <xs:extension base="ObjectType">
                <xs:sequence>
                    <xs:element name="element1" type="xs:string" minOccurs="1" maxOccurs="1">
                </xs:element>
                </xs:sequence>
            </xs:extension>
        </xs:complexContent>
    </xs:complexType>
</xs:schema>

Here there are examples of extensions. http://www.w3schools.com/

Solution without extension
<?xml version="1.0" encoding="UTF-8"?>
    <xs:schema elementFormDefault="qualified" targetNamespace="http://yourNamespace"
        xmlns="http://yourNamespace" xmlns:xs="http://www.w3.org/2001/XMLSchema">

        <xs:complexType name="Message">
            <xs:sequence>
                <xs:element name="element1" type="xs:string" minOccurs="1" maxOccurs="1"/>
            </xs:sequence>
        </xs:complexType>
    </xs:schema>


text:
Q: Running Python script with C# acts strange This question have been asked and answered before (for example here: How do I run a Python script from C#?), but in my specific code the answers doesn't seem to work for me.
Github issue: https://github.com/nopara73/JoinMarketTest/issues/2
In cmd it seamlessly works:

"python wallet-tool.py generate"

This command generates a new wallet.
It asks for password, password confirmation and wallet name from the user.
However I doesn't seem to get it right with C# code.
At first glance it seems like an easy one, but something unusual is happening here.
The simpified code:
internal string Generate()
{
    ProcessStartInfo start = new ProcessStartInfo
            {
                FileName = PythonPath,
                Arguments = "wallet-tool.py generate",
                UseShellExecute = false,
                CreateNoWindow = true,
                RedirectStandardOutput = true,
                RedirectStandardInput = true
            };
    using (var process = Process.Start(start))
            {
                if (process == null) return String.Empty;
                using (var output = process.StandardOutput)
                {
                    using (var input = process.StandardInput)
                    {
                        // Asks for password.
                        var result = output.ReadToEnd();
                        input.WriteLine("password");
                        // Asks for password confirmation.
                        result += output.ReadToEnd();
                        input.WriteLine("password");
                        // Asks for wallet file name.
                        result += output.ReadToEnd();
                        input.WriteLine("wallet.json");
                        result += output.ReadToEnd();
                        return result;
                    }
                }
            }
}

A: As an alternative I've changed to IronPython.


text:
Q: Accessing a view that has a shared ID within shared layouts when only one layout is visible In my Android app I have a layout for an activity that presents a choice.
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/wrapper"
    android:orientation="vertical">

    <include layout="@layout/choices" />

    <include layout="@layout/choice_one" />
    <include layout="@layout/choice_two" />
</LinearLayout>

In layout/choices the user sees two buttons. One button shows layout/choice_one and the other shows layout/choice_two. (The parent in layout/choice_one and layout/choice_two is initially set to android:visibility=gone.)
So when a user chooses either choice_one or choice_two, essentially I'm setting the visibility to VISIBLE. That works great.
The issue is that inside of both choice_one and choice_two I have shared elements with the same ID. For example I have a TextView with ID header. (I did this because I figured only one of those layouts would be visible and they use the same things.)
The issue is that I use Butterknife, and it seems like if I Bind header, when I set the visibility on choice_one or choice_two, I have a 50/50 chance of correctly calling header.setText("Blah") on the appropriate header element.
I'm sure I can get around this by giving unique IDs to all elements in the layouts or ditching Butterknife and using findViewById instead. But is there another way I can target a shared ID inside of a layout without ditching Butterknife or my shared layouts?

A: I figured this out. (Writing it out helped, so I'll keep it here in case someone else stumbles upon it.) Instead of using include in xml and inflating layouts there, I just subclassed ViewGroup for my two layouts and added them to wrapper:
ChoiceOne choiceOne = new ChoiceOne();
wrapper.addView(choiceOne);


text:
Q: jQuery plugin for Processing.js not works in chrome when uploaded content in webpage i'm new on jquery, and i have a doubt about use of jquery use with Processing.js
I have some of links on sidebar; each of them is a lesson, and in one of these lessons i have a

blablablablabla

()
Then, when user click in the lesson (the content above), the webpage update the content, and call a jquery Plugin, if found the id #processing, calling
$.Processing('#processing', 'afile.pde')

(the plugin)
(function(){

var src = './processing-1.3.6.js'

$.Processing = function(parent, file){
    var appendScript = function(){
        $('head').append(function(){
            return $('').attr('src', src).html('added processing script');
        })
    }

    var appendProcessing = function(){
        $(parent).append(function(){
            var $c = $('<canvas></canvas>');
            var p = Processing.loadSketchFromSources($c, [file])
            return  $c;
        });
    }

    appendScript();
    appendProcessing();
}
}())

the problem is that the function ´$('head')append has not been called. tested on Chrome
Thanks

A: 1) Processing.loadSketchFromSources needs a plain createElement object, not a jQuery object. So you need to change this line:
Wrong: var $c = $('<canvas></canvas>');
Correct: var $c = document.createElement('canvas');
If you really need the jQuery object, then you would need to get the pure createElement from the jQuery object using $c[0] instead of $c, so this would also work:
var p = Processing.loadSketchFromSources($c[0], [file]);
2) Don't use </script> string inside a script tag because it will end your script:
Wrong: return $('')
Correct: return $('


text:
Q: Java - Parsing a JLabel to java.util.Date I'm simply trying to parse a string in  JLabel to a date using a simpleDateFormatter().  Based On everything I've searched online, this code should work. However, I'm receiving the "cannot find symbol - method parse(java.lang.String)" error during compiliation.  Any advice on how to resolve the issue would be greatly appreciated.
The JLabel in question was populated with a date from a database query using JDBC.
Additionally, I'm aware that that java.util.Date has been deprecated, but would still like to use it for this.
Code Snippet:
private Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
private JLabel dateDataLabel = new JLabel("");

private void setAndParseLabel()
{
    dateDataLabel.setText(formatter.format(validatePass.eventDate));

    java.util.Date aDate = formatter.parse(dateDataLabel.getText());
}

A: tl;dr

*

*You are ignoring crucial issue of time zone. You are unwittingly parsing the input as a value in UTC.

*You are using terrible old date-time classes that were supplanted years ago. Use java.time instead.

Example code:
LocalDateTime
.parse(
    "2018-01-23 13:45".replace( " " , "T" )  // Comply with standard ISO 8601 format by replacing SPACE with `T`. Standard formats are used by default in java.time when parsing/generating strings.
)                                            // Returns a `LocalDateTime` object. This is *not* a moment, is *not* a point on the timeline.
.atZone(                                     // Apply a time zone to determine a moment, an actual point on the timeline.
    ZoneId.of( "America/Montreal" )
)                                            // Returns a `ZonedDateTime` object.
.toInstant()                                 // Adjust from a time zone to UTC, if need be.

java.time
The modern approach uses the java.time classes.
Your input string is almost in standard ISO 8601 format. To fully comply, replace that SPACE in the middle with a T.
String input = "2018-01-23 13:45".replace( " " , "T" ) ;

Parse as a LocalDateTime because your input has no indicator of time zone or offset-from-UTC.
LocalDateTime ldt = LocalDateTime.parse( input ) ;

A LocalDateTime by definition does not represent a moment, is not a point on the timeline. It represents potential moments along a range of about 26-27 hours (the range of time zones around the globe).
To determine a moment, assign a time zone (ZoneId) to get a ZonedDateTime object.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;

If you wish to see that same moment through the wall-clock time of UTC, extract an Instant.
Instant instant = zdt.toInstant() ;  // Adjust from some time zone to UTC.

Avoid java.util.Date where feasible. But if you must interoperate with old code not yet updated to java.time, you can convert back-and-forth. Call new conversion methods added to the old classes.
java.util.Date d = java.util.Date.from( instant ) ;  // Going the other direction: `myJavaUtilDate.toInstant()`

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?

*

*Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later  - Part of the standard Java API with a bundled implementation.

*

*Java 9 adds some minor features and fixes.

*Java SE 6 and Java SE 7

*

*Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

*Android

*

*Later versions of Android bundle implementations of the java.time classes.

*For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

A: java.text.Format does not have method parse, so the code does not compile.
You can refer it by java.text.DateFormat:
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");

A: There is no method parse in java.text.Format. Use java.text.DateFormat instead:
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");


text:
Q: Laravel 5.4 update method I am trying to update the record in the database. This is a specific element that is an element of another. Here is my code, it doesnt work :/
web.php :
 Route::patch('/projects/{projectID}/{id}', 'ProjectsController@update');

Controller:
public function update($projectId, $id, CreateProjectRequest $request)
    {
        $page = Page::findOrFail($id);
        $page->update([
           'name' => $request->name,
       ]);

       return redirect('/projects/' . $projectId);
    }

HTML:
{!! Form::model($page, ['method'=>'PATCH', 'action' => ['ProjectsController@update', $project->id, $page->id]]) !!}
  {!! Form::text('name',null,['class'=>'blue-inp']) !!}

 {!! Form::submit('Save changes',['class'=>'btn btn-save-blue']) !!}

 {!! Form::close() !!}

A: You need to switch the class type-hint CreateProjectRequest for just Request in your controllers update method.
The variables passed from the form input fields can then be accessed like this:
$name = $request->input('name');

More on the topic: https://laravel.com/docs/5.0/requests

A: You can simplify the controller method, assuming the CreateProjectRequest handled all the necessary validation and it's inputs match the inputs you want to update
Edit: I prefer to validate everything with formrequests with rules and by the time it reaches the controller, it just calls services or does stuff.
As far as naming conventions, you may not need to send the $id in the url parameter and send it within the body, in order to avoid using Request in the formrequest to validate if it exists in the database
public function update($projectId, $id, CreateProjectRequest $request)
{
    $data = $request->validated();
    Page::findOrFail($id)->update($data);

    return redirect('/projects/' . $projectId);
}


text:
Q: How do i log the user's name to console? I'm making a Discord bot for a server and I am having trouble with this. I want it to log the user's name to console. So far it looks like:
INFO: <#777176816950575114> started typing in a channel
I tried changing it to user.tag instead of user.name but that changed the numerical id to undefined. Any ideas?
client.on('typingStart', user => {
    console.log(`${chalk.bold.blue("INFO")}${chalk.blue(`: ${user.name} started typing in a channel`)}`);
})

EDIT: I have had the suggestions user.user.tag and user.username. These aren't working: user.user.tag returns an error and user.username returns undefined.

A: Looking at this example. Channel is the first parameter and user is the second parameter.
client.on('typingStart', (channel, user) => {
    console.log(`${chalk.bold.blue("INFO")}${chalk.blue(`: ${user.username} started typing in a channel`)}`);
})

A: Just use user.username to get the username of a person.
console.log(user.username);


text:
Q: Column wise mean with condition pandas I have a sample dataframe as follow:
data = pd.DataFrame({'Date':[20210101,20210102,20210103,20210104,20210105],'coef1':[1,2,5,4,3],'coef2':[1,1,2,6,3],'coef3':[1,1,1,1,1]})

I would like to have mean over 'coef1' ,'coef2' and 'coef3' if these values does not equal to 1.
My desired dataframe should be like bellow:

I wrote a function and apply it on my datframe and got my desired output,however I want a pythonic way to achieve this.
def final_coef(x):
coef_list = []
if x['coef1'] == 1:
    pass
else:
    coef_list.append(x['coef1'])
if x['coef2'] == 1:
    pass
else:
    coef_list.append(x['coef2'])
if x['coef3'] == 1:
    pass
else:
     coef_list.append(x['coef3'])
return np.mean(coef_list)

data['Final_coef'] = data.apply(lambda row: final_coef(row),axis = 1)

A: This can be done in one line but there are three steps to do:

*

*apply np.nan everywhere a value is equal to 1 using df.where(df.ne(1), np.nan)

*calculate the mean of each row (NaNs arn't included) using df[['coef1', 'coef2', 'coef3']].mean(axis=1))

*assign the results of this calcualtion to a new colum using df.assign()
code example
df  = df.assign(final_coef=df.where(df.ne(1), np.nan)[['coef1', 'coef2', 'coef3']].mean(axis=1))

>>>df
       Date  coef1  coef2  coef3  final_coef
0  20210101      1      1      1         NaN
1  20210102      2      1      1         2.0
2  20210103      5      2      1         3.5
3  20210104      4      6      1         5.0
4  20210105      3      3      1         3.0

A: data['final_coef'] = (
    data[['coef1', 'coef2', 'coef3']][data[['coef1', 'coef2', 'coef3']] != 1]
    .mean(axis=1)
)
data
     Date   coef1 coef2 coef3 final_coef
0   20210101    1   1    1    NaN
1   20210102    2   1    1    2.0
2   20210103    5   2    1    3.5
3   20210104    4   6    1    5.0
4   20210105    3   3    1    3.0

Explanation:
This will generate the required mask. Note that Date field is no where required to be considered
data[['coef1', 'coef2', 'coef3']] != 1

    coef1   coef2   coef3
0   False   False   False
1   True    False   False
2   True    True    False
3   True    True    False
4   True    True    False

Then you can get the required corresponding data points in following way:
data[['coef1', 'coef2', 'coef3']][data[['coef1', 'coef2', 'coef3']] != 1]

   coef1 coef2  coef3
0   NaN   NaN   NaN
1   2.0   NaN   NaN
2   5.0   2.0   NaN
3   4.0   6.0   NaN
4   3.0   3.0   NaN


text:
Q: Python: Merge two list of diferent objects by attribute I'm trying to find an efficient way to merge two list of python objects (classes) with diferent structures and merge them into a new list of new object. The code:
from datetime import datetime

class StructureOne(object):
    def __init__(self, date_time: datetime, name: str):
        self.date_time: datetime = date_time
        self.name: str = name
        self.value = None

    def set_value(self,value:float):
        self.value = value

class StructureTwo(object):
    def __init__(self, date_time: datetime, value: float):
        self.date_time = date_time
        self.value: float = value

def merge_lists(list_one: list[StructureOne], list_two: list[StructureTwo]) -> list[StructureOne]:
    for element_one in list_one:
        i = 0
        while i < len(list_two) and element_one.value is None:
            if element_one.date_time == list_two[i].date_time:
                element_one.set_value(value=list_two[i].value)
            i += 1
    return list_one

list_one: list[StructureOne] = [
    StructureOne(date_time=datetime(2022, 1, 1, 0), name='zero'),
    StructureOne(date_time=datetime(2022, 1, 1, 1), name='one'),
    StructureOne(date_time=datetime(2022, 1, 1, 2), name='two'),
    StructureOne(date_time=datetime(2022, 1, 1, 3), name='three'),
]

list_two: list[StructureTwo] = [
    StructureTwo(date_time=datetime(2022, 1, 1, 0), value=0),
    StructureTwo(date_time=datetime(2022, 1, 1, 1), value=1),
    StructureTwo(date_time=datetime(2022, 1, 1, 2), value=2),
    StructureTwo(date_time=datetime(2022, 1, 1, 3), value=3),
]

merged_list: list[StructureOne] = merge_lists(list_one=list_one, list_two=list_two)

The desired result is

list_one: list[StructureOne] = [
    StructureOne(date_time=datetime(2022, 1, 1, 0), name='zero', value=0),
    StructureOne(date_time=datetime(2022, 1, 1, 1), name='one', value=1),
    StructureOne(date_time=datetime(2022, 1, 1, 2), name='two', value=2),
    StructureOne(date_time=datetime(2022, 1, 1, 3), name='three', value=3),
]

We are trying to not use external libraries like py-linq.

A: Assumptions:

*

*The lists might not be sorted.

*The date_time field is unique within each list.

*It is okey if the output is sorted.

*You want to populate the value of the objects in list_one with the value from the objects in list_two on matching date_time.

*You only want to populate the value of an object in list_one if it is None.

*In your code, you only populate the value if it is not None; I assume that you want to do the opposite.

def merge_lists(list_one: list[StructureOne], list_two: list[StructureTwo]) -> list[StructureOne]:

    # sort lists by date_time
    list_1 = sorted(list_one, key=lambda x: x.date_time)
    list_2 = sorted(list_two, key=lambda x: x.date_time)

    # merge sort
    i, j = 0, 0
    while i < len(list_1) and j < len(list_2):
        if list_1[i].date_time < list_2[j].date_time:
            i += 1
        elif list_1[i].date_time > list_2[j].date_time:
            j += 1
        else:
            # date_time matches
            # populate value from list_two into list_one if value is None
            if list_1[i].value is None:
                list_1[i].value = list_2[j].value
            i += 1
            j += 1

    return list_1

A: If all you want is to change the value attribute of StructureOne to the value of StructureTwo in the order of each list then you can do this to modify the elements in list_one:
for elem_one, elem_two in zip(list_one,list_two):
    elem_one.value = elem_two.value

You don't even need to have the value attribute in StructureOne, it will work the same:
class StructureOne(object):
    def __init__(self, date_time: datetime, name: str):
        self.date_time: datetime = date_time
        self.name: str = name

If by merging you mean to get rid of list_two you can delete the variable so it will get discarded.
del list_two

Printing the elements after the merge will have your value members updated:
for e in list_one:
    print(e.date_time,e.name,e.value)

# Output:

2022-01-01 00:00:00 zero 0
2022-01-01 01:00:00 one 1
2022-01-01 02:00:00 two 2
2022-01-01 03:00:00 three 3

Your __init__ function has a lot of duplication in names, that's why it can be a good idea to use dataclasses, it will work the same, but it's easier to read and maintain:
from dataclasses import dataclass

@dataclass
class StructureOne:
    date_time : datetime.datetime
    name : str

@dataclass
class StructureTwo:
    date_time : datetime.datetime
    value : float


text:
Q: Ingress resource vs NGINX ingress controller on Kubernetes I am setting up NGINX ingress controller on  AWS EKS.
I went through k8s Ingress resource and it is very helpful to understand we map LB ports to k8s service ports with e.g file def. I installed nginx controller till pre-requisite step. Then the tutorial directs me to create an ingress resource.
https://kubernetes.io/docs/tasks/access-application-cluster/ingress-minikube/#create-an-ingress-resource
But below it is telling me to apply a service config. I am confused with this provider-specific step. Which is different in terms of kind, version, spec definition  (Service vs Ingress).
https://raw.githubusercontent.com/kubernetes/ingress-nginx/master/deploy/provider/aws/service-l7.yaml
I am missing something here?

A: the NGINX ingress controller is the actual process that shapes your traffic to your services. basically like the nginx or loadbalancer installation on a traditional vm.
the ingress resource (kind: Ingress) is more like the nginx-config on your old VM, where you would define host mappings, paths and proxies.

A: This is a concept that is at first a little tricky to wrap your head around. The Nginx ingress controller is nothing but a service of type LoadBalancer. What is does is be the public-facing endpoint for your services. The IP address assigned to this service can route traffic to multiple services. So you can go ahead and define your services as ClusterIP and have them exposed through the Nginx ingress controller.
Here's a diagram to portray the concept a little better:

image source
On that note, if you have acquired a static IP for your service, you need to assign it to your Nginx ingress-controller. So what is an ingress? Ingress is basically a way for you to communicate to your Nginx ingress-controller how to direct traffic incoming to your LB public IP. So as it is clear now, you have one loadbalancer service, and multiple ingress resources. Each ingress corresponds to a single service that can change based on how you define your services, but you get the idea.
Let's get into some yaml code. As mentioned, you will need the ingress controller service regardless of how many ingress resources you have. So go ahead and apply this code on your EKS cluster.
Now let's see how you would expose your pod to the world through Nginx-ingress. Say you have a wordpress deployment. You can define a simple ClusterIP service for this app:
apiVersion: v1
kind: Service
metadata:
  labels:
    app: ${WORDPRESS_APP}
  namespace: ${NAMESPACE}
  name: ${WORDPRESS_APP}
spec:
  type: ClusterIP
  ports:
  - port: 9000
    targetPort: 9000
    name: ${WORDPRESS_APP}
  - port: 80
    targetPort: 80
    protocol: TCP
    name: http
  - port: 443
    targetPort: 443
    protocol: TCP
    name: https
  selector:
    app: ${WORDPRESS_APP}

This creates a service for your wordpress app which is not accessible outside of the cluster. Now you can create an ingress resource to expose this service:
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  namespace: ${NAMESPACE}
  name: ${INGRESS_NAME}
  annotations:
    kubernetes.io/ingress.class: nginx
    kubernetes.io/tls-acme: "true"
spec:
  tls:
  - hosts:
    - ${URL}
    secretName: ${TLS_SECRET}
  rules:
  - host: ${URL}
    http:
      paths:
      - path: /
        backend:
          serviceName: ${WORDPRESS_APP}
          servicePort: 80

Now if you run kubectl get svc you can see the following:
NAME                      TYPE          CLUSTER-IP      EXTERNAL-IP    PORT(S)                   AGE
wordpress                 ClusterIP     10.23.XXX.XX   <none>         9000/TCP,80/TCP,443/TCP   1m
nginx-ingress-controller  LoadBalancer  10.23.XXX.XX    XX.XX.XXX.XXX  80:X/TCP,443:X/TCP   1m

Now you can access your wordpress service through the URL defined, which maps to the public IP of your ingress controller LB service.


text:
Q: Calling assembly routine in objective C I have written a function nabs in assembly file math.nasm
as follows
%ifdef USE_x86_ASM
SECTION .text

    cglobal nABS
;*------------------------*
;* int nABS(int a)        *
;* return value in eax    *
;*------------------------*
ALIGN 16
    nABS:
        push ebx
        ......
                ......
                 pop ebx
        ret
%endif

I am calling this function from c function func1 in file myfunc.c
I am using nasm assembler for assembly file I am using X-code 3.1 version and gcc 4.0   compiler I have defined USE_x86_ASM
in Xcode settings Project Settings/Build/NASM BUILD OPTIONs/OTHER FLAGS AS -DUSE_X86_ASM
Also I have defined this pre-processor in header file myfunc.h also
I have declared nABS in myfunc.h as
#define USE_x86_ASM
int nABS(int a);

and included myfunc.h in myfunc.c
Both myfunc.c and math.nasm are compiled sussessfuly and generate math.o and myfunc.o, but I get a linking error
Undefined symbols:
  "_nABS", referenced from:
      _func1 in myFunc.o

can anyone tell me why am I getting link error?

I did the modification suggested in addition I removed %ifdef condition the modified code is as follows
.text
.align 2
.globl _nABS
.private_extern _nABS

_nABS:
        push ebx
        ......
        ......
        pop ebx
        ret
still I am getting same linking error the the file is compiled but I get same linking error.
I checked that the .o generated is included app.LinkFileList.

A: Some C compilers add a preceding underscore to C symbols. Just add the underscore to your label in the assembly file (and globl directive, of course).

A: Mehrad is right
This should work
%ifdef USE_x86_ASM
SECTION .text

;*------------------------*
;* int nABS(int a)        *
;* return value in eax    *
;*------------------------*
ALIGN 16
global _nABS
    nABS:
        push ebx
        ......
                ......
                 pop ebx
        ret
%endif


text:
Q: Good/better way to solve $y'' + 2y'/x + y^5 = 0$? DE: $y'' + 2y'/x + y^5 = 0$, $y(\infty) = 0$
Proof: Notice the DE is scale-invariant under $ x \leftrightarrow ax$ and $y \leftrightarrow a^{-1/3}y$. Therefore, if We make the substitution $y = x^{-1/3}u(x)$, then the DE reduces to:
$x^{-1/3}u'' + \frac{4}{3}x^{-4/3}u' - \frac{2}{9}x^{-7/3}u + x^{-5/3}u^5 = 0$ .... $(I)$
Is this approach correct? Notice $(I)$ can be solved by letting $u = x^m$.
Is there a better way to approach this problem?
Thanks.

A: Notice that if you assign dimension $m$ to $y$, $dy$, $d^2y$ and dimension 1 to $x$, $dx$, then the first two terms have dimension $m-2$ and the last one $5m$. Setting $m=-\frac{1}{2}$ makes the expression homogeneous in a generalised sense.
If we now let
$$x=e^{\xi}\qquad y=ue^{m\xi}$$
we arrive at an equation which is invariant with respect to shift in $\xi$, hence does not depend on $\xi$ explicitly.
$$\frac{dy}{dx}=e^{(m-1)\xi}\left(\frac{du}{d\xi}+mu\right)=e^{-\frac{3}{2}\xi}\left(u'_{\xi}-\frac{1}{2}u\right)$$
$$\frac{d^2y}{dx^2}=e^{(m-2)\xi}\left(u''_{\xi}+(2m-1)u'_{\xi}+m(m-1)u\right)\\=e^{-\frac{5}{2}\xi}\left(u''_{\xi}-2u'_{\xi}+\frac{3}{4}u\right)$$
EDIT: I was not careful enough in the previous version when inserting the above results in the original equation
$$e^{-\frac{5}{2}\xi}\left(u''_{\xi}-2u'_{\xi}+\frac{3}{4}u\right)+e^{-\frac{5}{2}\xi}\left(2u'_{\xi}-u\right)+e^{-\frac{5}{2}\xi}u^5=0$$
Hence
$$u''_{\xi}-\frac{1}{4}u+u^5=0$$


text:
Q: Implementing a Canvas in PyQt5 I have been trying to learn to using PyQt5.
I want to implement a canvas below the "Menu Bar"
class gui(QDialog):
    def __init__(self, parent=None):
        super(gui, self).__init__(parent)
        self.createTopLayout()
        self.painter = canvas(self)
        mainLayout = QGridLayout()
        mainLayout.addLayout(self.topLayout, 0, 0, 1, 2)
        mainLayout.addWidget(self.painter, 1, 0, 6, 2)
        self.setLayout(mainLayout)

    def createTopLayout(self):
        self.topLayout = QHBoxLayout()
        button1 = QPushButton("b1")
        button2 = QPushButton("b2")
        button3 = QPushButton("b3")
        styleComboBox = QComboBox()
        styleComboBox.addItems(QStyleFactory.keys())
        styleLabel = QLabel("&Style:")
        styleLabel.setBuddy(styleComboBox)
        self.topLayout.addWidget(styleLabel)
        self.topLayout.addWidget(styleComboBox)
        self.topLayout.addStretch(1)
        self.topLayout.addWidget(button1)
        self.topLayout.addWidget(button2)
        self.topLayout.addWidget(button3)

Where my canvas is defined as
class canvas(QMainWindow):
    def __init__(self, parent=None):
        super(canvas, self).__init__(parent)
        self.setGeometry(100, 100, 1000, 700)

    def paintEvent(self, e):
        cir = circle() #circle class creates a circle with random center and radius both between 0 to 100
        painter = QPainter(self)
        painter.setPen(QPen(Qt.red, 1, Qt.SolidLine))
        painter.drawEllipse(self, cir.center.x, cir.center.y, cir.radius, cir.radius)

but for me canvas doesnt render at all let alone the ellipse.

A: You should not use QMainWindow as a canvas, instead use a QWidget. On the other hand setGeometry will not work if you use layout since the latter handles the geometry, instead it establishes a fixed size and adequate margins. On the other hand it is recommended that the name of the classes begin with capital letters, considering the above the solution is:
class Canvas(QWidget):
    def __init__(self, parent=None):
        super(Canvas, self).__init__(parent)
        self.setFixedSize(1000, 700)
        self.setContentsMargins(100, 100, 100, 100)

    def paintEvent(self, e):
        # ...


text:
Q: Polygons on a grid I've tried multiple variations of polygons but can't find any that work. Do they exist?
Is it possible to draw a polygon on a grid paper and divide it into two equal parts by a cut of the shape shown on the Figure (a)?
Solve the same problem for a cut shown on Figure (b).
Solve the same problem for a cut shown on Figure (c).

(In every problem a cut is inside the polygon, with the ends lying on the boundary. The sides of the polygons and the cuts must lie on the grid lines. The small links of the cuts are twice as short as the large ones)

A: Here are (a) and (b). The key thing is to repeat the shape of the cut twice in the outline of the polygon.

EDIT: to add a solution for (c) constructed in a similar fashion.

A:
So your polygon can be a rectangle?
You need $a^2=(a+b)(a+c)-a^2$
$a^2=a^2+ac+ab+bc-a^2$
$a^2=ac+ab+bc$

A: Here is something for (a) and (b)


text:
Q: Is there a way to create a for loop to give the sum of values in a range of cells in a column based on the values from another column
I want to regroup cells from V1 based on a condition: if values in V1 are between 0 and 3 calculate the sum of the same rows in V3. form the picture I uploaded. values from V1 are between 0 and 3 and therefore we can calculate the 3 first cells in V3 (sum=12).
Next, I want to do the same for the interval [3,6] then [6,9] ... [i,i+3].
I tried to make a for loop but I couldn't figure out how to specify my arguments.

A: We could use dyplr:
library(dplyr)

df %>%
  mutate(interval = rep(row_number(), each=3, length.out = n())) %>%
  group_by(interval) %>%
  summarise(sum = sum(V3))

  interval   sum
     <int> <int>
1        1    12
2        2    21
3        3    30
4        4    12

data:
V1 <- 1:10
V2 <- 2:11
V3 <- 3:12

df <- tibble(V1,V2,V3)

A: Or another option is gl to create grouping column
library(dplyr)
df %>%
   group_by(interval = as.integer(gl(n(), 3, n()))) %>%
   summarise(V3 = sum(V3))

NOTE: data from @TarJae


text:
Q: Defining function arguments as local variables Sometimes I see two different ways to define default value for function arguments.
The first one is to redefine argument value like that:
var callName1 = function( name ) {
 name = name || 'John';
 console.log( 'Hello, ' + name );
};

The second one is to define local variable with the same name:
var callName2 = function( name ) {
 var name = name || 'John';
 console.log( 'Hello, ' + name );
}

Both of this methods are working the same.
So, I have two questions:
1) What's the point to define local variable with same name in the second way?
2) Which of these ways is more correct?

A: There is no difference between them. var statements for variables which are already local to the function have no effect.


text:
Q: Providing row data from a table in a notification I have an SNMP MIB that provides tabular data. If possible, I'd like to add an SNMP notification that provides the same data as one row of the table.
As an example, I'll use the following table from the NET-SNMP-EXAMPLES-MIB:
netSnmpHostsTable OBJECT-TYPE
    SYNTAX      SEQUENCE OF NetSnmpHostsEntry
    MAX-ACCESS  not-accessible
    STATUS      current
    DESCRIPTION
        "An example table that implements a wrapper around the
        /etc/hosts file on a machine using the iterator helper API."
    ::= { netSnmpExampleTables 2 }

netSnmpHostsEntry OBJECT-TYPE
    SYNTAX      NetSnmpHostsEntry
    MAX-ACCESS  not-accessible
    STATUS      current
    DESCRIPTION
        "A host name mapped to an ip address"
    INDEX   { netSnmpHostName }
    ::= { netSnmpHostsTable 1 }

NetSnmpHostsEntry ::= SEQUENCE {
    netSnmpHostName         OCTET STRING,
    netSnmpHostAddressType  InetAddressType,
    netSnmpHostAddress      InetAddress,
    netSnmpHostStorage      StorageType,
    netSnmpHostRowStatus    RowStatus
}

--- Definitions of objects in the sequence omitted

Ideally, I'd like to add a new notification which provides the data associated with a single NetSnmpHostsEntry.
My initial attempt was this:
netSnmpHostsEntryNotification NOTIFICATION-TYPE
    OBJECTS     { netSnmpHostsEntry }
    STATUS      current
    DESCRIPTION
        "First crack at the notification."
    ::= { netSnmpExampleNotificationPrefix 2 }

However, smilint reports these errors:
object `netSnmpHostsEntry' of notification `netSnmpHostsEntryNotification' must be a scalar or column
object `netSnmpHostsEntry' of notification `netSnmpHostsEntryNotification' must not be `not-accessible'

I roughly understand these errors. There are restrictions on what objects you can bind to a notification, and an object representing a row of a table is neither a scalar or a column and isn't valid.
I then tried changing that notification to this:
netSnmpHostWithEvent OBJECT-TYPE
    SYNTAX      NetSnmpHostsEntry
    MAX-ACCESS  read-only
    STATUS      current
    DESCRIPTION
        "Host associated with the notification"
    ::= { netSnmpExampleNotificationPrefix 3 }

netSnmpHostsEntryNotification NOTIFICATION-TYPE
    OBJECTS     { netSnmpHostWithEvent }
    STATUS      current
    DESCRIPTION
        "Second crack at the notification."
    ::= { netSnmpExampleNotificationPrefix 2 }

The linter gives a different error for this:
type `NetSnmpHostsEntry' of node `netSnmpHostWithEvent' does not resolve to a known base type

Again, I think this error makes sense. NetSnmpHostsEntry is declared as a SEQUENCE, not as a normal object. The items in that sequence are all defined as their own objects that link up to the netSnmpHostsEntry object, which itself links up to the netSnmpHostsTable object. In this example, the NetSnmpHostsEntry sequence is explicitly linked to the netSnmpHostsTable table, so the sequence isn't "usable" outside the context of the table.
This is mostly intuitive, and if I redefine the sequence in the notification, this gets through the linter without any errors1:
netSnmpHostsEntryNotification NOTIFICATION-TYPE
    OBJECTS {
        netSnmpHostName, netSnmpHostAddressType, netSnmpHostAddress,
        netSnmpHostStorage, netSnmpHostRowStatus
    }
    STATUS      current
    DESCRIPTION
        "Third crack at the notification."
    ::= { netSnmpExampleNotificationPrefix 2 }

I think this would work fine for the MIB I'm creating, but it does leave me with a few questions:

*

*Is there any way to reuse a SEQUENCE in a notification?

*Are there any issues with the final implementation of the notification that weren't caught by the linter?

1. I did need to change MAX-ACCESS of netSnmpHostName from not-accessible to read-create to make this work, but I don't think that's relevant to the general form of this question


text:
Q: Не удаётся заполнить и вывести массив Если ввести для второго массива (setB) число 9 для размерности массива, слово Set не выводится, только "B: ".
Если ввести число >= 10, выводится мусорное значение в конце массива и cout << "Set B: { "; не выводится.
Подскажите, пожалуйста, решение проблемы.
#include <iostream>
using namespace std;

void printSet(int setA[], int sizeA) {
    for (int i = 0; i < sizeA; i++)
        cout << setA[i] << " ";
    cout << "}";
}

void fillSet(int setA[], int sizeA) {
    for (int i = 0; i < sizeA; i++)
        setA[i] = rand() % 31;
}

int main() {
    srand(time(0));
    //creating sets
    int sizeA = 0, sizeB = 0;
    int* setA = new int[sizeA];
    int* setB = new int[sizeB];

    //inputting sizes and values of sets
    cout << "Enter the size of set A: ";
    cin >> sizeA;
    cout << "Set A: { ";
    fillSet(setA, sizeA);
    printSet(setA, sizeA);
    cout << endl << "Enter the size of set B: ";
    cin >> sizeB;
    cout << "Set B: { ";
    fillSet(setB, sizeB);
    printSet(setB, sizeB);

    delete[] setA;
    delete[] setB;
}

A: Как вы думаете, сколько памяти вы выделили для массивов здесь?
int sizeA = 0, sizeB = 0;
int* setA = new int[sizeA];
int* setB = new int[sizeB];

При выделении памяти вы запрашиваете нулевое ее количество.
Как минимум, память надо выделять после того, как становится известно, сколько ее вам требуется...


text:
Q: Show that $\int_{\tau}^{\infty}\frac{\exp(u)}{[1+\exp(u)]^2}du=\frac{\exp(-\tau)}{1+\exp(-\tau)}$ How $$\int_{\tau}^{\infty}\frac{\exp(u)}{[1+\exp(u)]^2}du=\frac{\exp(-\tau)}{1+\exp(-\tau)}$$?
My Attempt :
let $z=1+\exp(u)$
$\frac{dz}{du}=\exp(u)$
$$
\begin{array}{c|c|c|}
u&\tau&\infty\\
\hline
z&1+\exp(\tau)&\infty
\end{array}
$$
So,
$$\int_{\tau}^{\infty}\frac{\exp(u)}{[1+\exp(u)]^2}du$$
$$=\int_{1+\exp(\tau)}^{\infty}\frac{dz}{z^2}$$
$$=[\frac{-1}{z}]_{1+\exp(\tau)}^{\infty}$$
$$=\frac{1}{1+\exp(\tau)}.$$
But I have to show $\int_{\tau}^{\infty}\frac{\exp(u)}{[1+\exp(u)]^2}du=\frac{\exp(-\tau)}{1+\exp(-\tau)}$. How can I do that ?

A: $$
\int_{\tau}^{\infty}\tfrac{\exp(u)}{[1+\exp(u)]^2}du=\left.-\tfrac{1}{1+\exp(u)}\right|_\tau^\infty=\frac{1}{1+\exp(\tau)}=\tfrac{\exp(-\tau)}{\exp(-\tau)}\cdot\frac{1}{1+\exp(\tau)}=\frac{\exp(-\tau)}{1+\exp(-\tau)}
$$


text:
Q: Application Wait time issue I am stuck on this bit and not sure how to get past it. I need to be able to pause and the resume my code. I went with this idea to place a value into a cell, which the Application Wait time will use.
This bit is fine and works
Dim i As Integer
Dim Response As Integer
Sheets("Sheet3").Range("Z1").Value = "01:00:00" 'will place 1hr wait time in Sheet3 Z1
t = CStr(Range("Z1"))
Application.Wait (Now + TimeValue(t))

I then have a CommandButton2 on my userform, which will reset the wait time from 1hr wait to 2 seconds. In theory this should then resume the code from where it left off. The wait time is between the IE opening and loading and the FOR EACH loop running, so once it has resumed it would action the FOR EACH loop of the code.
Sheets("Sheet3").Range("Z1").Value = "00:00:02" `Reset time to 2 sec from 1hr

MY PROBLEM
I can not click on button2 when the wait time is running. Is there a way I could do this so that when the wait time code is running, button2 is still enabled to use?
BACKGROUND
User click commandbutton1 and code runs, IE opens and navigates to the correct page. NOW the code waits. As it gives the user time to  select from several options (Too many to put in a code). Once done the user click the second command button which resets the code to 2sec and they can extract their information. In theory it should continue, however I can not click on the second button while the wait code is running. Is there a work around?
I have tried to split the code into subs, but I was having several error messages and I gave up on that method. I did look at a doEvent loop, but I am limitted in coding and was not sure how it would work and if it would continue the code OR start from the begining. As starting from the begining is not how I want to do it.
Thanks in advance.
POST EDITED
This is the code now, not 100% sure if it is correct, it now allows me to change the value of Z1 via button2 but the FOR LOOP does not run
Before

After button2 is clicked

'#################### APPLICATION WAIT ################
Dim i As Integer
Dim Response As Integer
Sheets("Sheet3").Range("Z1").Value = "01:00:00" 'will place the 1hr wait time in Sheet3 Z1
t = CStr(Range("Z1"))
'Application.Wait (Now + TimeValue(t)) 'commented out or it freezes excel
WaitUntil = Now + TimeValue(t)
Do While Now <= WaitUntil
    DoEvents
Loop
'#################### APPLICATION WAIT ################

    'FOR LOOP
    For Each element In elements
      DoEvents
    ```

A: Application.Wait() pauses the entire application, not just your code. You should be able to achieve the intended result using a loop with DoEvents:
...
WaitUntil = Now + TimeValue(t)
Do While Now <= WaitUntil
    DoEvents
Loop
...

EDIT:
The DoEvents loop doesn't work because you set the value of t only once, so when your button2 changes value of Z1 to 00:00:02, the value of t is still 01:00:00. To fix this, you can reset value of t inside the loop:
...
WaitUntil = Now + TimeValue(t)
Do While Now <= WaitUntil
    DoEvents
    If t <> CStr(Range("Z1")) Then 'If value of Z1 changed, update t
        t = CStr(Range("Z1"))
        WaitUntil = Now + TimeValue(t)
    End If
Loop
...

A: I have managed to fix the problem, should anyone ever need this in the future here is the work around. Also a very big Thankyou to Kirill Tkachenko for putting me on the right path
I done it with a DoWhile Loop. This part of the code went in between browser (IE) is fully loaded and before the FOR EACH LOOP, then this code is triggered.
THE CODE

*

*It places a 1hr wait time in Z1, then THE DoWhile loop runs.

*When Button2 is clicked The time changes to under 3sec and the sheet recalclates
column Z.

*Then the if statement kicks in and as the DoWhile states the time should be more
than 3sec and Z1 now is 2sec the GOto runs next and goes to the lable I
created to tell the code to start here. That is just before the FOR
EACH loop
'#################### APPLICATION WAIT ################
Dim i As Integer
Dim Response As Integer
Sheets("Sheet3").Range("Z1").Value = "01:00:00" 'will place the 1hr wait time in Sheet3 Z1
t = CStr(Range("Z1"))
    WaitUntil = Now + TimeValue(t)

Do While Now > "00:00:03"
Sheets("Sheet3").Columns("Z").Calculate

If Sheets("Sheet3").Range("Z1").Value = "00:00:02" Then
        GoTo StartForLoop_Restart ' use GOTo command and label to reinitiate the sub
End If
DoEvents
Loop
'#################### APPLICATION WAIT ################

'Restart the code HERE, this is the key part
StartForLoop_Restart:

    'FOR LOOP
    For Each element In elements
      DoEvents

This is what I put in Button2
 Sheets("Sheet3").Range("Z1").Value = "00:00:02"
 Sheets("Sheet3").Columns("Z").Calculate

I know its not the best code in the world and could be written better, but the workaround works and hopefully someone can do a much better job in writing it in the future.


text:
Q: How to set up user to control Saved Search Criteria in NetSuite Suitelet SSv2 I am trying to set up a Suitelet to give the user the option of adjusting the criteria of a saved search. I have set up search with ID customsearch_ca_export_detail_search__38 and I would like to be able to control the criteria of this search within the Suitelet. I would prefer to use SSv2 but I am not finding instructions for this in the documentation. How do I do this?

A: /**
*@NApiVersion 2.x
*/

require(['N/search'], function(search) {

    function loadSearchAndAddFilter() {

        var searchObj = search.load({
            id: 'customsearch_ca_export_detail_search__38'
        });

        var filters = searchObj.filters;

        var filter = search.createFilter({
            // create new filter here
        });

        filters.push(filter);
        searchObj.filters = filters;

        searchObj.run().each(function(result) {
            // access search results here
            return true;
        });
    }

    loadSearchAndAddFilter();
});


text:
Q: Abbreviation/shortcut in R Do we have something in RStudio like the SAS Enterprise Guide editor abbreviations (https://blogs.sas.com/content/sasdummy/2011/11/17/sas-program-editor-abbrevs/)?
For those who don't know, they are a "template" code snippet that can be auto-completed by typping the abbreviation/shortcut. It's really useful when some block of code is often used or when it's hard to remember the syntax.
For example, I could define the shortcut "pp" to:
ggplot(df,aes(x=x, y=y)) +
  geom_point() +
  theme(plot.title = element_text(size = 16),
        axis.text.x = element_text(angle=90, hjust=1)) +
  theme_light() +
  labs(x = "X",
       y = "Y") +
  ggtitle("TITLE")

And insert it automatically by just typing "pp" + TAB.


text:
Q: does Tera Term handle software flow control internally? The title may be a little confusing but i'll explain the situation:
We have the following situation:
ARM MCU -> UART -> FTDI chip -> USB -> PC -> Tera Term terminal
The FTDI chip has built-in hard- and software to handle software flow control (XON/XOFF) internally. So i expect that when you select software flow control in Tera Term that it will send commands to the FTDI chip to enable flow control.
This means that Tera Term will not handle flow control itself but only enables/disables it on the FTDI chip by sending commands at initialization?
If so, is there a terminal program which do handle flow control on PC?
edit:
if you downvote, tell at least why.

A: There is no standard "command" one side can send to enable or disable flow control on the remote side. Hence, your terminal will not send anything when you enable or disable handling of (software) flow control.
What you do enable is the handling of the XON and XOFF bytes by the terminal. This means that the terminal program will be aware that XON (0x11) and XOFF (0x13) when received are not to be shown in the terminal window but mean to resume or pause, respectively, transmitting data to the other side.
Or, in other words, XON/XOFF is only sent by either side when that side is currently receiving data.
Edit: The misunderstanding may be in that "XON" does not "turn on" flow control, but is itself a flow control command signalling to the other side to turn "transmission on", i.e. go on sending data; "XOFF" is sent to the other side to tell it to turn "transmission off", i.e. to pause sending.


text:
Q: How do we understand the relationship between independent probabilities and real-world independence? From what I have come to understand, the events A and B are considered independent for purposes of probability theory when
$$
p(A \cap B) = p(A) \cdot p(B)
$$
Now, supposing I flip two coins. I write down the probabilities for the joint outcomes as $\left(\frac{1}{4}, \frac{1}{4}, \frac{1}{4}, \frac{1}{4}\right)$ and see that the individual coins are independent. But how do we know those probabilities? Well, the first coin could come up either heads or tails with probability $\frac{1}{2}$, then in the case of heads we know that the probabilities for the second coin are still $\frac{1}{2}$… but this seems to be assuming $p(A|B) = p(A)$, which is mathematically just a rearrangement of the above formula, so this feels like circular reasoning.
So, what's the explanation? Why does theoretical independence correspond to practical independence, in a not-apparently-circular way?

A: I think if you approach it the other way around it is more intuitively understandable. What does it mean that two variables $A$ and $B$ are independent? It means that knowing the probability distribution/function of one tells us absolutely nothing about the other one. The fact that $B$ may or may not have occurred is irrelevant, extraneous, and pretty much distracting when we are thinking of $A$. What does this mean in probabilistic terms? It means that the probability of $A$ occurring, given that $B$ occurred is the same as the probability of $A$ ignoring $B$ completely. We translate this English (or whatever language you wish) concept into symbolic mathematical form as $P(A|B) = P(A)$. This is the root expression, not the product rule, as this is the translation into mathematical symbols of the meaning of the word "independent".
Now that we have defined/translated "independence" to mean $P(A|B) = P(A)$, we can make the following observation:
$$
P(A|B) = P(A)\\
\frac{P(A \cap B)}{P(B)} = P(A)\\
P(A \cap B) = P(A)P(B)
$$
The "product rule" is an outgrowth (via algebraic manipulation) of the definition, not the other way around.

A: I think there's a problem where you say you "observe the two coins are independent."  You never observe probabilistic independence, per se; it is always a property of the events / random variables under consideration, which are constructed by the modeller to represent some (physical or otherwise) phenomenon.
So, the physical phenomenon here is: there are two fair coins, and tossing either one of them does not affect the outcome of the other.  They're 'independent' in a nontechnical sense, if you want to use that word.
A probabilistic model that we can build to represent this physical phenomenon mathematically is: define two independent, Bernoulli(1/2)-distributed random variables $X_{0}$ and $X_{1}$.  I.e.,
$$
X_{0}, X_{1} \overset{iid}\sim \text{bernoulli}(1/2) \\
$$
Here I mean 'independent' in the technical, probabilistic sense.  That gives us stuff like
$$
P(\{X_{0} = 1\}\cap\{X_{1} = 1\} = P(X_{0} = 1)P(X_{1}=1)
$$
and we can get the joint distribution by enumerating all the combinations of $X_{0}$ and $X_{1}$, as you've done.  Nothing circular to be found.


text:
Q: how to perform inverse pyramid for given interger array list values? in android  4  5  7  6 3
  9  3  4  9
   3  7  4
    1   2
      3

4+5=9
5+7=12 -->1+2=3
Likewise, how to get final result 3 like n number?
public static void main(String[] args) {
    int rows = 5;

    for(int i = rows; i >= 1; --i) {
        for(int space = 1; space <= rows - i; ++space) {
            System.out.print("  ");
        }

        for(int j=i; j <= 2 * i - 1; ++j) {
           System.out.print("* ");
            //System.out.print(a[j]);
        }

        for(int j = 0; j < i - 1; ++j) {
            System.out.print("* ");
        }
    }
}

A: Code, provided that the numbers are in an array, as I cannot find a pattern in the numbers you have provided.
public static void main(String[] args) {

        int numList[] = {4, 5, 7, 6, 3, 9, 3, 4, 9, 3, 7, 4, 1, 2, 3};
        int i,j=0,k=1; //k is for the spaces.

        for (int line = 4; line >= 0; line--) {

            // To display spaces
                for(int space=0; space<k; space++) {
                    System.out.print(" ");

                }
             // To display the numbers.
                for (i = j; i <= (j + line); i++) {
            // The below if statement is for symmetry, you may ignore it.
                    if(k>=1){
                        System.out.print(" ");
                    }
                    System.out.print(" "+numList[i]+" ");
                }
                j = i;
                //The below code is just to make the pyramid symmetrical you
                //may ignore it.
                if(k==0){
                    k++;
                }
                else{
                    k+=2;
                }

                System.out.println();
            }
       }

Output


text:
Q: Is there any way to calculate the roots of this polynom? I need to calculate the roots of the real function $f$:
$$
f(x)=\frac{-{x}^{3}+2{x}^{2}+4}{{x}^{2}}
$$
But I am not able to decompose the numerator. There should be only one real solution and two complex, and I tryed to aproximate it using the Bolzano's Theorem, so I know that the root must be between 2.6 and 2.605, but that's all I got...

A: You can use Newton's method to find a zero of $f$. Choose any $x_0$ and define the sequence: $x_{n+1}= x_n-\frac{f(x_n)}{f'(x_n)}$. It converges to a root of the function (under some assumptions that you don't really care  about when the function is a polynomial)

A: First we know that the domain of $f$ is $(-\infty,0)\cup(0,\infty)$. Since $f$ is defined as a quotient of polynomials, we know that $f=0$ when the numerator is $0$. Thus we solve
$$-x^3+x^2+4=0.$$
We can find the roots to this polynomial using WolframAlpha or Mathematica.

A: We need: $-x^3+2x^2+4 = 0$, but as you noted, you can't further reduce this polynomial in order to find it's roots. In this case you find away to approximate the roots.


text:
Q: how to properly style image in react native I've just started learning React Native.. this is what my current app looks like

this is my code so far:
import { StatusBar } from 'expo-status-bar';
import { SafeAreaView, StyleSheet, Text, Image, View, Button, TextInput } from 'react-native';

export default function App() {
  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.mainContainer}>
        <View style={styles.logoContainer}>
          <Image style={styles.logoImage} source={require("./assets/logo03t.png")} />
        </View>
        <Text style={styles.logoText}>App untuk Edy Kiatmadja ver 1.0</Text>
        <TextInput style={styles.input} placeholder="Username" />
        <TextInput style={styles.input} placeholder="Password" />
      </View>
      <StatusBar style="auto" />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'dodgerblue',
    alignItems: 'center',
    justifyContent: 'center',
  },
  logoContainer: {
    padding: 20,
  },
  logoImage: {
    resizeMode: 'contain',
    height: 200,
    backgroundColor: "#fff",
  },
  logoText: {
    marginTop: 8,
    fontSize: 12,
    fontStyle: 'italic',
  },
  mainContainer: {
    flex: 1,
    justifyContent: 'center', // horizontal axis
    alignItems: 'center', // vertical axis
  },
  input: {
    height: 40,
    margin: 10,
    borderWidth: 1,
    padding: 10,
    width: 200,
  }
});

what do I have to do to make the Image not cut-off?

A: Set a maximum width of current screen width in logoContainer style. You can use react-native's Dimension API to find current device width & height.
To get the device width:
import { Dimensions } from 'react-native';
const windowWidth = Dimensions.get('window').width;

Then use this as width of the container.
...
  logoContainer: {
    padding: 20,
    maxWidth: windowWidth,
  },
...


text:
Q: In fluid dynamics does $u_x-v_y$ have a name? I have come across the quantity:
$$\frac{\partial u}{\partial x}-\frac{\partial v}{\partial y}$$
of the two dimensional velocity field $(u,v)$. Does this quantity have a name or is it related to any quantity with a name?

A: This quantity is called the Stretching deformation.  The reference (1) given below says the following about it:

Stretching deformation, $D^{(1)}$, is a measure of the deformation of a fluid element due to compression in one direction and simultaneous dilation in a direction orthogonal (90 degrees) to it.

Here by deformation it seems to be referring directly to a change in shape rather then also including changes in areas. This is because the quantity above is zero when the shape is kept the same but the area varied.
Reference
(1) Mak, M. 2011. Atmospheric Dynamics. Cambridge: Cambridge University Press (page 50 Link to Google Books)


text: Q: Jekyll - Create Multiple Landing Pages from One Markdown File I am trying to create two web pages from the same markdown file, is this possible? I have two layouts test1.html and test2.html. I want to generate two pages from the layouts above based on one markdown file data.md in order for ab testing... is this doable in jekyll?


text:
Q: Ruby Azure Blob Storage: "RequestBodyTooLarge" If I try to upload a large file - 388.7 MB in this case - to azure blob storage using the demo code, it fails like so:
begin
  content = File.open("big_file.dat", "rb") { |file| file.read }
  blob = azure_blob_service.create_block_blob(container.name,"image-blob", content)
  puts blob.name
rescue StandardError => e
  $stderr.puts e.message
end

# RequestBodyTooLarge (413): The request body is too large and exceeds the maximum permissible limit.

I've read in the blob storage documentation that blobs can be up to 200 GB in size, so it looks as though the Ruby API doesn't correctly chunk its file uploads. Am I missing something?

A: The current Ruby Azure SDK does indeed have methods for doing chunked uploads, but there are no usage examples anywhere and everything in the specs is a mock, which doesn't really help.
Getting chunked uploads to work is so fiddly that this is absolutely something that should be included in the library. It took me a number of hours to get this right and I hope this code snippet helps.
Here is a very basic usage example:
class ::File
  def each_chunk(chunk_size=2**20)
    yield read(chunk_size) until eof?
  end
end

container  = 'your container name'
blob       = 'your blob name'
block_list = []
service    = Azure::BlobService.new
counter    = 1

open('path/to/file', 'rb') do |f|
  f.each_chunk {|chunk|
    block_id = counter.to_s.rjust(5, '0')
    block_list << [block_id, :uncommitted]

    # You will likely want to get the MD5 for retries
    options = {
      content_md5: Base64.strict_encode64(Digest::MD5.digest(chunk)),
      timeout:     300 # 5 minutes
    }

    md5 = service.create_blob_block(container, blob, block_id, chunk, options)
    counter += 1
  }
end

service.commit_blob_blocks(container, blob, block_list)

Give me a couple of days and I should have something more reasonably encapsulated committed to https://github.com/dmichael/azure-contrib

A: Even though block blobs can be of 200 GB in size, you can upload a block blob without splitting it in chunks if the blob size is less than 64 MB. Any blob which is greater than this size must be uploaded by splitting it into chunks where each chunk can be of a maximum 4 MB in size.
Looking at the source code for this function, this function uploads the file in one go without splitting it into chunks. Since your file size is more than 64 MB, you are getting this error. The solution would be to split your file in chunks and then upload the file using create_blob_block function.


text:
Q: external directory list and download I am trying to make a script that will let me download files outside my web root directory and list the files...It is listing the files of the directory but it does not allow me to download them as when they are clicked it just goes to website.com/clickedlink.jpg but it needs to some how change that to go to the location I would like...
I think I am explaining this a little odd so please tell me if it needs clarification.
I need to download files from /home/files/I/need but the website is stored in /var/website/
so if someone could please help out I'd be 100% thankful!
<title>Root page</title>

<?
// open this directory
$myDirectory = opendir("/home/files/I/need");

// get each entry
while($entryName = readdir($myDirectory)) {
    $dirArray[] = $entryName;
}

// close directory
closedir($myDirectory);

//  count elements in array
$indexCount = count($dirArray);
Print ("$indexCount files
\n");

// sort 'em
sort($dirArray);

// print 'em
print("
\n");
print("
Filename	Filetype	Filesize
\n");
// loop through the array of files and print them all
for($index=0; $index < $indexCount; $index++) {
        if (substr("$dirArray[$index]", 0, 1) != "."){ // don't list hidden files
        print("
$dirArray[$index]	");
        print("");
        print(filetype($dirArray[$index]));
        print("	");
        print("");
        print(filesize($dirArray[$index]));
        print("	");
        print("
\n");
    }
}
print("
\n");
?>

A: The best solution is to let your web server take care of this by creating a location alias; having the web server perform the downloading for you is much more scalable than doing this in PHP.
However, since you asked for a PHP solution, add this to this top of your script:
$basePath = "/home/files/I/need";
if (isset($_SERVER['PATH_INFO']) && $file = basename($_SERVER['PATH_INFO'])) {
    if (file_exists("$basePath/$file")) {
        // add file size
        header('Content-Length: ' . filesize("$basePath/$file"));
        // write file to output
        readfile("$basePath/$file");
        return;
    }
}

To construct the URL to make the download:
/path/to/your/script.php/clickedlink.jpg

The /path/to/your/script.php is the same URL that generates the page; you append a slash, together with the intended filename.
I'm using basename() to prevent people from accessing ../../../etc/passwd or some other file they shouldn't be seeing, but that also means you can't use sub folders. If you need to support sub folders, you have to sanitize the PATH_INFO in a different manner.


text:
Q: JQuery DataTable Export Excel cannot apply Built in style to empty cell I am trying to apply style to excel by using attr('s', '20') from the button extension from jquery datatable. https://datatables.net/reference/button/excelHtml5
Below code is how I apply style to the 3rd child of a row:
$('#DataTable').DataTable({
    dom: 'Bfrtip',
    buttons: [
        {
            extend: 'excelHtml5',
            customize: function (xlsx) {
                var sheet = xlsx.xl.worksheets['sheet1.xml'];
                $('row[r!=1]', sheet).each(function () {
                    $(this).children().eq(2).attr('s', '20');//apply style to 3rd child of the row.
                });
            }
        }]...............

The problem is : When the cell is empty, the style wont be applied.
When the 3rd cell is an empty string or null on the datatable, the style won't be apply on excel file. I debugged the code and find out  $(this).children().eq(2) does not exist when the cell is an empty string. If the 3rd cell has some text in it, the style will be applied.
Does anyone know how to work around this? Or is there a way to apply style to the entire row.
Thanks.

A: Use "createEmptyCells" : true,
Example
        { extend: 'excelHtml5',
                                                                text: 'Export to Excel',
                                                                "createEmptyCells" : true,
                                                                exportOptions:
                                                                    {   title:null,
                                                                        orthogonal: 'export'
                                                                     }
                                                                },

A: To style the third cell for each row excluding the header, you need this selector:
$('row[r!=1] c:nth-child(3)', sheet).attr('s', '20');

The styling will apply even the cell is empty. Check this example I created.


text:
Q: Deploy a model on ml-engine, exporting with tf.train.Saver() I want to deploy a model on the new version of Google ML Engine.
Previously, with Google ML, I could export my trained model creating a tf.train.Saver(), saving the model with saver.save(session, output).
So far I've not been able to find out if the exported model obtained this way is still deployable on ml-engine, or else I must follow the training procedure described here and create a new trainer package and necessarily train my model with ml-engine.
Can I still use tf.train.Saver() to obtain the model I will deploy on ml-engine?

A: tf.train.Saver() only produces a checkpoint.
Cloud ML Engine uses a SavedModel, produced from these APIs: https://www.tensorflow.org/versions/master/api_docs/python/tf/saved_model?hl=bn
A saved model is a checkpoint + a serialized protobuf containing one or more graph definitions + a set of signatures declaring the inputs and outputs of the graph/model + additional asset files if applicable, so that all of these can be used at serving time.
I suggest looking at couple of examples:

*

*The census sample - https://github.com/GoogleCloudPlatform/cloudml-samples/blob/master/census/tensorflowcore/trainer/task.py#L334

*And my own sample/library code - https://github.com/TensorLab/tensorfx/blob/master/src/training/_hooks.py#L208 that calls into https://github.com/TensorLab/tensorfx/blob/master/src/prediction/_model.py#L66 to demonstrate how to use a checkpoint, load it into a session and then produce a savedmodel.
Hope these pointers help adapt your existing code to produce a model to now produce a SavedModel.
I think you also asked another similar question to convert a previously exported model, and I'll link to it here for completeness for anyone else: Deploy retrained inception SavedModel to google cloud ml engine


text:
Q: c++ Determine images in a polygon contour I am using GPC (General Polygon Clipper) to create sets of images. I am unable to determine if the images are from disjoint sets though.
I am using a gpc_polygon struct defined at the above link, reading the vertex list from an image data (lat/lon of corners)... And adding images sequentially to a polygon.
It is important to separate images that belong to separate regions. While I can't say for sure that the intersection area will be non-zero (that would have been a perfect test), I have noticed that the num_contours of the completed polygon coincides with the number of distinct regions.
I thought that I can use num_contours to determine if an image belongs to a set.
Yet, as I add images, I can see, on one image, num_contours=1, after the second, it increases to 2 (whether the image is in the same section or not, and that makes sense)... but it doesn't increase after that, until the pattern of disjointed images is really off - so I can't really use it to test, at least not on its own.
It is the same as I remove images from the polygon, using a DIFF operator.
If anyone else has used GPC, or some other method of polygon convolution, perhaps you can give me some advice on what I can use to identify which images belong to each contour, so I can either separate them before, or after, polygon creation ?

A: I used num_contours, with a limiting value of 2 instead of 1, and had to go back iteratively, and try to re-add contours, until I couldn't add them anymore. The solution is suboptimal, may be very slow, and there are situations when polygons that don't belong together end up in the same contour.


text:
Q: RunTime Error on online compilers when using string in c++ I am trying to run this code on online compilers and it shows Runtime errors while it runs perfectly locally. The parts of code that are not being used have been commented out.
#include <iostream>
#include <string>
#include <cmath>
using namespace std;

int main() {
    // your code goes here
    ios_base::sync_with_stdio(0);
    cin.tie(NULL);
    cout.tie(NULL);
    int t;
    cin>>t;
    while(t--)
    {
        string s;
        cin>>s;

        int x,y;
        cin>>x>>y;
        string ans;
        int noOfApple=0,noOfBanana=0;
        for(int i=0;i<s.size();i++)
        {
            if(s[i]=='a')
            {
                noOfApple++;
            }
            else
            {
                noOfBanana++;
            }
        }
        int noOfABlock=ceil(noOfApple/x);
        //int noOfBBlock=ceil(noOfBanana/y);
        int length=floor(noOfBanana/(noOfABlock-1));
        int remainderB=noOfBanana%(noOfABlock-1);
        int counter=0;
        //condition for '*'

        if(noOfBanana<(noOfABlock-1))
        {
            int q=noOfBanana;
            for(int i=0;i<(noOfABlock-1);i++)
            {
                for(int j=0;j<x;j++)
                {
                    ans[counter++]='a';
                }
                if(q>0)
                {
                    ans[counter++]='b';
                    q--;
                }
                else
                {
                    ans[counter++]='*';
                }
            }
            for(int i=0;i<x;i++)
        {
            ans[counter++]='a';
        }

        }
        else{
        for(int i =0;i<(noOfABlock-1);i++)
        {
            for(int j=0;j<x;j++)
            {
                ans[counter++]='a';
            }
            for(int j=0;j<length;j++)
            {
                ans[counter++]='b';
            }
            while(remainderB>0)
            {
                remainderB--;
                ans[counter++]='b';
            }
        }
        for(int i=0;i<x;i++)
        {
            ans[counter++]='a';
        }
        }

        cout<<ans<<endl;

    }
    return 0;
}

Input for this program:-
6
ab
1 1
aab
1 1
aabb
1 2
aaaaab
2 1
aaaa
1 3
aaaaa
2 2

When Arrays are used we  have to initialize the size of the arrays as they are static but as string are dynamic we do not need to initialize with a size.


text:
Q: Coupons collectors problem extended Given $n$ distinct coupons, each package contains exactly one of the $n$ coupons with the probability $\dfrac{1}{n}$. I'm interested in the expected number of packages one has to buy so that one has each coupon at least two times.
My approach was to to just imagine that there are $2n$ coupons to choose from and we're interested in computing the expected number of coupons we have to buy to get all of them ($2n$). I'm however very uncertain whether this approach is correct.


text:
Q: Unable to compile transcluded directives in unit test as of Angular 1.3.0 I have a directive with transclude: true.  It includes a template property that points to a simple HTML file with one element that contains an ng-transclude attribute on an anchor element.  The anchor element wraps the content of the directive.
My test looks like this:
describe('foobar directive', function() {
    var $compile, $rootScope, $modal;

    beforeEach(module('collective'));
    beforeEach(module('test.templates'));

    beforeEach(inject(function(_$rootScope_, _$compile_, _$modal_) {
        $rootScope = _$rootScope_;
        $compile = _$compile_;
        $modal = _$modal_;
    }));

    it('attempts to open the modal when the wrapped element is clicked', function() {
        spyOn($modal, 'open');

        var el = $compile('<foo-bar>

</foo-bar>')($rootScope);
        $rootScope.$digest();

        el.find('#foobar').click();
        expect($modal.open).toHaveBeenCalled();
    });
});

Note that I'm using ng-html2js-preprocessor to load my templates into the test.templates module. That seems to be working fine for all other non transcluded directives.
The test above fails as $modal.open() is never called.  It is never called as the anchor element in the template is never added to the element after it is compiled.  This is not an issue in my running app, nor was it an issue with Angular 1.2.9.  The issue starts with Angular 1.3.0, and remains in Angular 1.3.5.
After running $compile in my test, the element looks like this:
<foo-bar class="ng-scope">

</foo-bar>

When it should look like this:

<foo-bar class="ng-isolate-scope">

</foo-bar>

The latter is true of 1.2.9, but not 1.3.0.
Any idea what is going wrong here?

A: I just checked with Angular#1.3.0 and #1.3.5 and compiling directives with transcluded content works fine for me in both cases. To be specific I made the compilation in the karma test environment like you.

How are you sure that ng-transclude is the problem here?

A: Thanks to @artur, I noticed that the issue was caused by a small change in behavior first introduced into Angular 1.3.0.
Turns out one of the services I was injecting was preventing angular from compiling the directive in my test environment. The dependency in question was a small factory I created that simply makes a property on the window an injectable service. I never actually use this service in my tests, so I don't actually import the underlying library in my karma config, and therefore the property on window is undefined. Angular 1.2.x doesn't seem to care, but 1.3.x chokes and fails to compile!
For example, given this defined factory:
myModule.factory('bootbox', function() {
    return window.bootbox;
});

...and the following directive:
myModule.directive('myDirective', ['$scope', 'bootbox' function($scope, bootbox) {
   //...
}]);

The above directive WILL compile if window.bootbox is undefined in Angular 1.2.x, but it will NOT compile in 1.3.x.  A null value doesn't seem to cause this problem, strangely enough.


text:
Q: How to middle align in bash shell Let's say I want the screen output to look like this.
Ship to                            Bill to
John Smith                         John Smith
222 Address                        555 Address
Los Angeles, CA                    New York, CA

Without hard-coding the spaces, cause once the length of the entries in the first column changes, the second column won't be aligned anymore.

A: Example using printf:
#!/bin/bash

st_name="John Smith"
bt_name=$st_name
st_addr="222 Address"
bt_addr="555 Address"
printf "%-20s%s\n" "Ship to" "Bill to"
printf "%-20s%s\n" "$st_name" "$bt_name"
printf "%-20s%s\n" "$st_addr" "$bt_addr"


text:
Q: Confusion about naming: increase a directory / partition / filesystem / block device? I'm a new linux user (Fedora, LXDE). Now I have some troubles with increasing the size of... partition? Directory? Filesystem? .../usr. This is my question.
What exactly I want to do is to "increase the size of /usr" in order to install new packages. Increasing is a separate problem - maybe I would need to increase size of something different (maybe even delete partition with Windows) - here I'm asking about naming.
If I'm increasing the size of /usr, am I increasing the size of partition /usr, directory /usr, filesystem /usr, block device /usr (because gnome-disk-utility says /dev/fedora/usr is a block device), or something different? Or "increasing" is a misconception here, or I'm increasing something different?
Sorry for the title, I didn't know how to name my problem (thus my question could be too subjective and deleted, I understand that).
EDIT 1: I'm asking in the context of my output of df command:
/dev/mapper/fedora-usr                           2,9G  2,7G   42M  99% /usr

EDIT 2: Well, now I have thought it through and consider that the size of /dev/mapper/fedora-usr is the size to increase.

A: This is confusing. First, /usr is a directory. But any directory can also be a mount point, which is where a filesystem is anchored. The filesystem by itself is on a block device — this can be either a partition, a logical volume, or a file attached to a loopback device.
There are certain directories which by tradition are often separate mount points, and usr is one of them. I think the easiest way to find out the state of a given system is with the df command — give it the name of a directory, and it will tell you information about the filesystem that directory is under. For example, on my system:
$ df -h /usr
Filesystem           Size  Used Avail Use% Mounted on
/dev/mapper/fedora-root   79G   19G   57G  25% /

Which shows that for me, /usr is on the "root" filesystem, which is on the device /dev/mapper/fedora-root, which is mounted mounted at /. On your system, based on your update, /usr is separate.
For comparison:
$ df -h /home/mattdm/
Filesystem           Size  Used Avail Use% Mounted on
/dev/mapper/fedora-home   99G   74G   21G  79% /home

which tells me that my home directory is on a filesystem mounted at /home.
Whether or not a particular directory is a mount point, to make more space available under any directory, you need to increase the space on the filesystem on which that directory resides. In my case, since /usr is on the
/dev/mapper/fedora-root filesystem mounted at /, I would need to increase the size of that /dev/mapper/fedora-root. In your case, /usr is the mount point for the /dev/mapper/fedora-usr filesystem, so you need to increase the size of that filesystem.
To make more space on /usr in your situation, you will first need to have a logical volume with enough space — you can add physical volumes to that if there is no room free. Then, you will need to grow the filesystem inside that logical volume too. (This can be done in one step with the --resizefs flag to lvextend.)

A: I'm taking on from @mattdm's good answer to show you the practical steps to do what you need.
The output of df
/dev/mapper/fedora-usr                           2,9G  2,7G   42M  99% /usr

shows that you are using LVM (Logical Volume Manager), and that the /usr directory is mounted on a LV (Logical Volume) named usr on the VG (Volume Group) named fedora.
Therefore you need to do this:
1) Add a new (physical or virtual) disk to the machine to provide the extra disk space; let's call it /dev/sdc.
2) Create a new partition /dev/sdc1 (of type 0x8E = Linux
LVM) on the new disk:
fdisk /dev/sdc

(I'm assuming you know how to proceed on this so I'm leaving out the details: press n, p, 1, etc.)
This is not necessary but recommended, because if you have other
OSes accessing the disk they might not recognize LVM and see the whole
unpartitioned disk as empty.
3) Initialize the new partition as a Physical Volume:
pvcreate /dev/sdc1

4) Add the newly created PV to the existing Volume Group:
vgextend fedora /dev/sdc1

5) Extend the Logical Volume usr - and the underlying filesystem as well - so that it takes all free space:
lvresize -l+100%FREE --resizefs /dev/mapper/fedora-usr

Your /usr partition is now larger of whatever the size of /dev/sdc was.


text:
Q: how to get method parameter name of proxy class in Spring AOP I want to get method parameter name of proxy class in Spring AOP. My code is:
@Around("writeLog()")
    public Object doBefore(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        String[] paramNames = signature.getParameterNames();
    }

However, the variable paramNames always is null.
Version info:
- spring-boot: 2.0.7.RELEASE
- cglib: 3.2.9
So is there any method to solve the problem, thanks?


text:
Q: Glassfish: Fast hot deployment setup What is a good setup for really fast hot deployment of a Java EE application to Glassfish, so the changes are visible in less than e.g. 1 second?
Currently I'm using Eclipse Luna to develop a JSF2.1 application on Glassfish 3.1.2. When I change something in a jsf, a managed bean or an ejb, it takes ages to deploy the changes. I've already found some good advise,

*

*GlassFish (real) hot deployment of JSF pages and resources (CSS etc.) in Eclipse

*Glassfish taking 20s to do hot deployment, is that right?
but I don't think I can speed up my setting to get the deployment under e.g. < 1sec. Also I think "directory deployment" is not supported in GF3.
So what setup can you recommend? Should I switch to Netbeans? Or are there any hidden Eclipse settings to speed this up? Or do you reach fast hot deployments with Eclipse Luna and I'm just missing some properties?
Some more information: I have to use GF3.1.2 Furthermore I use maven, the backend jar and the front end war are bundle together in an ear file. I use EJBs and JPA to connect to a DB2 database. So except GF nothing special.

A: As far as I know, Glassfish does not support hot deployment. You would need something like JRebel to accomplish that. In case you're not bound to glassfish you might consider switching to wildfly or some other AS that supports this feature.


text:
Q: How come MooseX::Storage doesn't seem to follow attribute traits for some objects? I have put together a little test case to demonstrate my problem:
package P1;
use Moose;
use MooseX::Storage;
with Storage;

has 'blah' => (
    is => 'rw',
);

package P2;
use Moose;
use MooseX::Storage;
with Storage;

has 'lol' => (
    is => 'rw',
    traits => ['DoNotSerialize']
);

package P3;
use Moose;
extends 'P2';

has 'magic' => (
    is => 'rw',
);

package Test;
my $obj = P3->new(
    magic => 'This ok!',
    lol   => sub { 'weee' }
);

my $stored = P1->new(blah => $obj);

use Data::Dumper; print Dumper ($stored->pack);

I would expect this to print the object, but not the 'lol' attribute in the P2 package - however, I can still see this in the result of $stored->pack
$VAR1 = {
          '__CLASS__' => 'P1',
          'blah' => bless( {
                             'magic' => 'This ok!',
                             'lol' => sub { "DUMMY" }
                           }, 'P3' )
        };

Am I using MooseX::Storage wrong, or does this look like buggy behaviour?

A: Yup that looks like a bug. Can you turn this into a test that uses Test::More and submit it to the RT queue and someone (probably me) will fix that.
Note that if you Dump $obj->store you see that the trait is properly applied to the direct attribute but it seems that it's getting lost during the inheritance process.
You can report bugs against MooseX::Storage in RT

A: You can make 'blah' an isa of P3....
has 'blah' => (
    is  => 'rw',
    isa => 'P3',
);

and now Dumper( $stored->pack ) shows this....
$VAR1 = {
      '__CLASS__' => 'P1',
      'blah' => {
                  '__CLASS__' => 'P3',
                  'magic' => 'This ok!'
                }
};

which looks like the correct serialisation for this Moose object?


text:
Q: Image not fitting correctly I'm trying to fit the image <img class="img-drawer"... inside the div
, but for some reason the image gets 1 or 2 pixels top and bottom smaller than it should.
PS: I'm just starting out WebDev, so it's not very tidy. Sorry.
https://codepen.io/ualmeida/pen/jOWYaEm
Edit: the end result should look like this 1

A: I do agree that your margin of 23rem is quite excessive. Your ".img-drawer" has "2px" worth of padding and the height is set to "height: 313px;". Maybe try and add the "height" property to your ".site-container" and set it to something bigger, say "height: 320px;" and see if that helps.


text:
Q: Заполнить двумерный массив выборочно Создаю игру Bingo:
private final int BOARD_SIZE = 5;
private int[][] field = new int[BOARD_SIZE][BOARD_SIZE];

Нужно заполнить первую колонку числами в диапазоне 1-15, вторую 16-30, третью 31-45, четвертую 46-60, пятую 61-75.
public void initArray() {//метод Math.random
    field[0][0] = StartNums.makeNums(1, 15);
    field[0][1] = StartNums.makeNums(1, 15);
    field[0][2] = StartNums.makeNums(1, 15);
    field[0][3] = StartNums.makeNums(1, 15);
    field[0][4] = StartNums.makeNums(1, 15);
}

и т.д.
Был ещё вариант сделать 5 одномерных массивов, но подозреваю, что это плохой подход.
Как красиво заполнить каждый из пяти подмассивов? В дальнейшем ещё придется в каждом расставить по возрастанию и исключить повторы, но с этим, думаю, справлюсь.

A: Предлагаю самый очевидный вариант:
for (int i=0; i<BOARD_SIZE; i++) {
    field[0][i] = StartNums.makeNums(1, 15);
}

for (int i=0; i<BOARD_SIZE; i++) {
    field[1][i] = StartNums.makeNums(16, 30);
}

// и так далее

Либо такой:
for (int i=0; i<BOARD_SIZE; i++) {
    for (int j=0; j<BOARD_SIZE; j++) {
        switch (i) {
            case 0:
                field[i][j] = StartNums.makeNums(1, 15);
                break;
            case 1:
                field[i][j] = StartNums.makeNums(16, 30);
                break;
            // и так далее
        }
    }
}

Я бы выбрал первый способ, так как он хорошо читается.
PS. Только Вы определитесь, что Вы заполняете значениями из одного интервала: колонки или строки, а то Вы пишите, что колонки, однако заполняете строки.

A: Можно создавать массив со значениями от минимального до максимального, после чего его перемешивать и брать первые BOARD_SIZE значений. Затем эти значения сортировать и записывать в столбцы:
public class Bingo
{
    private static final int
            BOARD_SIZE = 5,
            OPTIONS_COUNT = 15;

    private static final Random rand = new Random();

    private int[][] field = new int[BOARD_SIZE][BOARD_SIZE];

    public void init()
    {
        for (int i = 0; i < BOARD_SIZE; i++)
        {
            int[] numbers = createAndShuffleArray(OPTIONS_COUNT * i + 1, OPTIONS_COUNT * (i + 1));
            int[] requiredNumbers = new int[BOARD_SIZE];
            System.arraycopy(numbers, 0, requiredNumbers, 0, BOARD_SIZE);
            Arrays.sort(requiredNumbers);
            for (int j = 0; j < BOARD_SIZE; j++)
            {
                field[j][i] = requiredNumbers[j];
            }
        }
        for (int i = 0; i < BOARD_SIZE; i++)
        {
            System.out.println(Arrays.toString(field[i]));
        }
    }

    private int[] createAndShuffleArray(int min, int max)
    {
        int[] array = new int[max - min + 1];
        for (int i = 0; i < array.length; i++)
        {
            int j = rand.nextInt(i + 1);
            array[i] = array[j];
            array[j] = min + i;
        }
        return array;
    }
}

И запуск этого кода:
public static void main(String[] args)
{
    Bingo bingo = new Bingo();
    bingo.init();
}

Числа получаются в рамках диапазона, без повторений и по возрастанию.
Если числа нужно записывать в строку, то цикл будет ощутимо короче:
for (int i = 0; i < BOARD_SIZE; i++)
{
    int[] numbers = createAndShuffleArray(OPTIONS_COUNT * i + 1, OPTIONS_COUNT * (i + 1));
    System.arraycopy(numbers, 0, field[i], 0, BOARD_SIZE);
    Arrays.sort(field[i]);
}

A: Можно вот так:
int magicNumber = 15;

for (int i = 0; i < field.length; i++)
    for (int j = 0; j < field[i].length; j++)
        field[i][j] = startNums.makeNums(i * magicNumber + 1, (i + 1) * magicNumber);


text:
Q: Why am I getting this message: Cannot convert type 'bool' to 'string' Below is the code snippet that I am using.
using System;
using System.Collections.Generic;
using System.Text;

namespace businessTMS
{
    public class SignIn
    {
        public string authenticate(String UserName, String password)
        {
            dataTMS.SignIn data = new dataTMS.SignIn();
          string authenticate=(string)data.authenticate(UserName, password);
            return authenticate;
        }

    }
}

A: Use the Boolean.ToString Method (documentation can be found here) like so:
using System;
using System.Collections.Generic;
using System.Text;

namespace businessTMS
{
    public class SignIn
    {
        public string authenticate(String UserName, String password)
        {
            dataTMS.SignIn data = new dataTMS.SignIn();

            return data.authenticate(UserName, password).ToString();
        }

    }
}

A: Your error is occurring due to this line:
string authenticate = (string)data.authenticate(UserName, password);

You are setting authenticate equal to a true/false calculation which is returning a Boolean value.  Try this instead.
string authenticate = data.authenticate(UserName, password).ToString();

You can also modify the code to still return a string by doing this:
bool authenticate = data.authenticate(UserName, password);
return authenticate.ToString();

PREFERRED OPTION:Furthermore, I'm not sure why you are returning a string representation of true/false (bool)...  If it were my function, I would probably return this:
return data.authenticate(UserName, password);

I would highly encourage you to simply return the Boolean value in the PREFERRED OPTION area.  There is no obvious reason to keep this in a string format.

A: I got the error message "Cannot convert type 'bool' to 'string'" but the line in my code where the error appeared was not cause of the message.
I had inadvertently chopped the last parameter off the previous lines function call, which should have been a bool, and not closed the bracket.


text:
Q: Create list of images from a PDF blob using react-pdf and pdfjs I am using react-pdf to generate a PDF on the client-side. It works great.
However, on mobile, the PDFViewer components doesn't work.
So, I have a 7-page PDF I need some way to "preview"/display on mobile.
My near-term solution is to convert the 7-page pdf to 7 individual jpegs or pngs.
I'm trying to do this with pdfjs but not having much luck... more info below:
I have the following component
    return (

        <PDFtoIMG
          pdfComponent={
            <ReactPDFExample />
          }
        >
          {({pages}) => {
            if (!pages.length) return 'Loading...';
            return pages.map((page, index) => );
          }}
        </PDFtoIMG>

    );

It looks like
import {Component} from 'react';
import * as PDFJS from 'pdfjs-dist';
import {pdf} from '@react-pdf/renderer';

PDFJS.GlobalWorkerOptions.workerSrc = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.5.207/pdf.worker.js`;

class PDFtoIMG extends Component {
  state = {
    pages: [],
  };

  async componentDidMount() {
    const blob = await pdf(this.props.pdfComponent).toBlob();
    const reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onloadend = () => {
      PDFJS.getDocument(reader.result).promise.then((pdf) => {
        const pages = [];
        this.pdf = pdf;
        for (let i = 0; i < this.pdf.numPages; i++) {
          pages.push(this.getPage(i + 1));
        }
        Promise.all(pages).then((pages) => {
          this.setState({pages});
        });
      });
    };
  }

  getPage = (num) => {
    return new Promise((resolve, reject) => {
      this.pdf.getPage(num).then((page) => {
        const scale = 1.5;
        const viewport = page.getViewport(scale);
        const canvas = document.createElement('canvas');
        const canvasContext = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;
        page
          .render({
            canvasContext,
            viewport,
          })
          .promise.then(() => {
            resolve(canvas.toDataURL('image/jpeg'));
          });
      });
    });
  };

  render() {
    return this.props.children({pages: this.state.pages});
  }
}

export default PDFtoIMG;

it returns an array like ["data:,", "data:,", "data:,", "data:,", "data:,", "data:,", "data:,"] which display some "url no found state" img stages

But I've confirmed the blob is correct (I can download and looks fine).
Some other research

*

*Turn pdf into array of png's using javascript (with pdf.js)


text:
Q: Load webview URL from other VC I'm trying to make it work but nothing.
I want to make (URL textfield) on (RightVC) as (webview)-url on (LeftVC).
I saved the textfield with this code:
@IBAction func save(sender: UIButton) {
    NSUserDefaults.standardUserDefaults().setObject(urltxtfield.text, forKey: "urltxtfield")
    NSUserDefaults.standardUserDefaults().synchronize()
}

override func viewDidLoad() {
    super.viewDidLoad()

    if NSUserDefaults.standardUserDefaults().objectForKey("urltxtfield") != nil {
        urltxtfield.text = NSUserDefaults.standardUserDefaults().objectForKey("urltxtfield") as? String
    } else {
        urltxtfield.placeholder = "urltxtfield"
    }
}

And it's ok with save. But how to make URL work with LeftVC webview?
This pic to make you understand me:

A: here: some sample of code to call load request to UIWebview when user enter url that urlstring it pass here as parameter Instead of google.com:
UIWebView.loadRequest(webviewInstance)(NSURLRequest(URL: NSURL(string: "google.cam")!))

OR
let url = NSURL (string: "http://www.google.com");
let requestObj = NSURLRequest(URL: url!);
myWebView.loadRequest(requestObj);

A: In your LeftVC (webView), you first need to get the NSUserDefaults and then make a request with your webView.
let prefs = NSUserDefaults.standardUserDefaults()
if let url = prefs.stringForKey("urltxtfield"){
    // You have an URL and can make the request
    let requestURL = NSURL(string: url)
    let request = NSURLRequest(URL: requestURL!)
    webView.loadRequest(request)
}else{
   // Nothing stored in NSUserDefaults
}

Update
After I got the project I updated the reference to the webView from strong to weak and I added the temporary code
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

In info.plist to allow you to browse on websites (you have to check if you want this and I can recommend you to read more about it).