text:
Q: Adding Greek letters in existing columns in ArcPy? Example table:
colA    colB  colC
173743    01  8974
173443    02  8934
173943    05  8924
173243    01  8994
173343    03  8964

I want to pass to the third column:
The 3 first numbers from the first column, then add '\delta\sigma', then the rest of the numbers from that column then add the second column.
I tried:
with arcpy.da.UpdateCursor('G82.shp', ['colA','colB','colC']) as cursor:
    for row in cursor:
       row[2] = row[0].str[:2].add('δσ').add(row[0].str[2:]).add(row[1])
       cursor.updateRow(row)

But it doesn't do anything.
It gives:

AttributeError: 'unicode' object has no attribute 'str'

A: first of all, you need to update the rows in your loop, otherwise the changes will not be written in the database.
second, your line of code will return some errors. There are different ways to write it but I suggest the use of format().
row[2] = "{0}ds{1}{2}".format(str(row[0])[:3], str(row[0])[3:], row[1])
cursor.updateRow(row)

EDIT (because of comment mentionning greek letters): not so familiar with greek letter, but you could try unicode characters
"{0}ds{1}{2}" replaced with u"{0}\u0394\u03C3{1}{2}"


text:
Q: SQLAlchemy.create_all doesn't work in integration test I'm new to Python and to Flask but I did manage to create an API that uses SQLAlchemy to interact with the DB.
Now, I'm trying to use integration tests to test my API but the db doesn't create before the API starts so an exception is thrown when I try to access one of it's tables...
As I was saying, everything works fine when I manually run the API.
Here is my integration test:
@pytest.fixture()
def app():
    db = SQLAlchemy()
    app = create_app(
        db,
        "sqlite:///:memory:",
        5,
        "secret"
    )
    app.config.update({
        "TESTING": True,
    })

    with app.app_context():
        db.create_all()

    yield app.test_client()

    # clean up / reset resources here

def test_valid_create_profile_request_returns_200(app):
    response = app.post("/profiles/",data=json.dumps(dict(name="my_profile")), content_type="application/json")
    assert response.status_code == 200

This is the error message that is thrown when I try to write to the DB:
E       sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: profile_model
E       [SQL: INSERT INTO profile_model (id, name) VALUES (?, ?)]
E       [parameters: ('da134852-db67-11ec-9bcd-d27906eb9227', 'my_profile')]
E       (Background on this error at: https://sqlalche.me/e/14/e3q8)

What am I doing wrong?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Issue with Kendo Graph in Printing We have a page where we are printing Kendo pie charts which is working perfectly fine. We have a facility to print these charts using default windows Print option using Windows.Print(). Issue that we have seen is that the charts which are Center aligned shifts to right while we are printing. On investingating further we understood that this is happening because the page is resizing itself while Printing but Kendo Charts are not resizing and aligning themselves in center. We explicitely refreshed the Kendo charts by adding followed by explicit refresh of Kendo Chart
$("#Chart").data("kendoChart").refresh();

However still we are facing challenge while getting it center aligned while printing. Has anyone faced similar challenge? Is there a workaround?

A: You can resize kendo chart by redraw method
$("#myChart").data("kendoChart").redraw();


text:
Q: Add HTML Snippet to Wordpress Blog Page? I have recently started working with Wordpress, and I use the HTML Snippets plug-in to fill in the contents of each page. This works well until I hit the blog page. My blog page does not take anything from the page editor, so I can neither paste code snippets nor write anything in the WP page editor field. It only responds to posts. As a result, I am unable to add anything static to my blog page. Also, editing the template post_list file also leads to damaging the template.
How do I go about adding static elements to my blog page?

A: Essentially it sounds like you're wanting to add a page template to your theme, which you can then assign as your 'Posts' page through the Wordpress admin.
The question itself is rather too broad to answer without an attempt at coding it yourself, but you can read more about it on the codex: http://codex.wordpress.org/Page_Templates#Creating_a_Page_Template


text:
Q: How to use "return-path" in php mail function What is that return path for?
Can i Use in this way?
mail($to_address, $subject, $message, $headers, "-f".$return_path );

Where:
$return_path = "C:/www/project/handlebounceemail.php";

Additional:
How to direct the email to a php script? I want to read the email and check for errors.

A: The $return_path refers to the email address to which undeliverable messages will be sent. This does not refer to a file or URL. So you could use:
$return_path = "bounces@example.com";

The next step would be for you to write a script to read the mailbox of the bounces user and do something based on the contents. The exact operations required to do that are dependent on your email system.


text:
Q: ListView that imitates Windows Explorer How can I make a ListView imitate the ListView in Windows Explorer on the right side. Like how can I get icons in the ListView and get the arrows?

A: You can find the icons by using Google Image search.  To create the ListView, you could do something like this is XAML:
<Grid>
    <ListView ItemsSource="{Binding ListViewSource}">
        <ListView.View>
            <GridView>
                <GridViewColumn Width="25">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <Image Source="{Binding Icon}"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
                <GridViewColumn Header="Name" DisplayMemberBinding="{Binding FileName}" Width="250"/>
                <GridViewColumn Header="Date Modified" DisplayMemberBinding="{Binding DateModified}" Width="100"/>
                <GridViewColumn Header="Type" DisplayMemberBinding="{Binding FileType}" Width="100"/>
                <GridViewColumn Header="Size" DisplayMemberBinding="{Binding FileSize}" Width="100"/>
            </GridView>
        </ListView.View>
    </ListView>
</Grid>

The next step is to create an ObservableCollection to hold all of the items in your list and call it ListViewSource.  You can populate this collection with actual FileDirectory information, or your own kind of list.  You'll then want to create your logic as to what happens when you doubleclick on an item.  Since your question didn't specify to what detail you want the ListView to work, I'm going to stop there.  Let us know if you want it to behave just like Windows Explorer, and we'll try to help you out.


text:
Q: add a line in the "n" position of a csv file that is being read As I have searched, it does not seem to be so easy to read and edit at the same time in fact, I have not managed to achieve it. but what confuses me the most is how to add an element in a line "n" of my csv, for example I want to add a line in the line 2 of my csv.

mycsv.csv

name,last name
yeison, smith
lola, boa
elmo, spitia
anderson, exneider
juan, ortega

my code:
with open("mycsv.csv", "r") as rfh:
 r = csv.DictReader(rfh)
 for idx, row in enumerate(r): #nothing happens
     print(r)
 with open("mycsv.csv", "a") as wfh:
     if(idx==2):
        #append element "german,ezequiel"

A: Reading all lines then writing should work:
with open('mycsv.csv', 'r') as f:
    lines = f.readlines()

lines.insert(2, 'german, ezequiel')

with open('mycsv.csv', 'w') as f:
    f.write(''.join(lines))

A: You can use pandas.
import pandas as pd

df = pd.read_csv("mycsv.csv")

line = pd.DataFrame({"name": 'XYZ', "last name": 'ABC'}, index=[2])
df2 = pd.concat([df.ix[:1], line, df.ix[2:]]).reset_index(drop=True)

df2.to_csv("mycsv.csv", index=False)


text:
Q: Solid-state relay controlling LED lights keeps failing I have some outdoor lights controlled by two PIR sensors at the top and bottom of the driveway. They are 24 V lights and will pull up to 10 A in total.
I initially had some trouble with the PIR sensors failing and rectified this to some degree by adding in two solid state relays so that the PIR sensors trigger the relays to turn the lights on.
One of the SSRs keeps failing (no longer switching), usually after a couple of months of use. The DC to DC relays are rated up to 60 A and 60 V but I'm wondering if I'm getting some voltage spiking on switch-off which is overloading something. I've read a bit about flyback diodes, is this what I need?

A: With dry contact relay switching, HV flyback voltages must be suppressed with some snubber or diode clamp from switch output to the opposite rail for turn off.
As dry contacts switch towards 0 time, V=LdI/dt is a very high voltage even for small L lines.  The same is true to a lesser extend for fast SSR's are not as fast turning off.


text:
Q: What is this icon supposed to be and what does it mean? I can't find an explanation for this, I tried googling VS symbols, icons, locals window, a few combinations. I get lots of results about all manner of non-related subjects - but none that explain what I'm looking for:
The following icons relate to string fields (at least in my current run) in my Visual Studio 2015 Community Locals Window, which I have running a C# program.
The top one has a little rosette or something on it - what is this actually an image of (not a rosette I assume) and what does it mean regarding my string?!
Here's a screenshot, with the icon on the top string field -

The classes I've used to recreate this is:
namespace TEST_ENVIRONMENTS
{
    class locals_window_icon_test
    {
        protected string A = "";
        private string B;
    }

    class derived : locals_window_icon_test
    {
        public string C = "";
        public string D;

        public void method()
        {
            A = "Hey";
            C = "Guy";
            D = "Gop";
        }
    }
}

And this is run from an instance by:
namespace TEST_ENVIRONMENTS
{
    class _PROGRAM
    {
        static void Main(string[] args)
        {
            derived x = new derived();
            x.method();
        }
    }
}

I just put a debug stop marker at the end of method and look at the variables in the Locals window.


text:
Q: Vb.net rounding inconcistancy I am using vb.net to summarize some information in a datatable using the following code.
For some reason the rounding works on all value apart from 1.
Code:
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    If TextBox1.Text = "" Then
        'Do Nothing
    Else

        Dim conn As New SqlClient.SqlConnection
        With conn
            .ConnectionString = "server=inlt01\SQLEXPRESS; database=OrbisBilling; integrated security=yes"
            .Open()
        End With

        Dim cmd As New SqlClient.SqlCommand
        With cmd
            .CommandText = "SELECT [Account], [Customer Lookup],ROUND (SUM ([ChargedAmount]),2) as [Sum of Buy Price],ROUND (SUM ([Sell Price]),2) as [Sum of Sell Price],[Tariff Lookup] FROM [OrbisBilling].[dbo].[" + TextBox1.Text + "] GROUP BY [Account], [Customer Lookup],[Tariff Lookup] Order by [Customer Lookup]"
            .CommandType = CommandType.Text
            .CommandTimeout = 30
            .Connection = conn
        End With
        Dim dt As New DataTable
        dt.Load(cmd.ExecuteReader)

        With OrbisViewBillForm.DataGridView1
            .AutoGenerateColumns = True
            .DataSource = dt
        End With

        cmd.Dispose()
        cmd = Nothing
        conn.Dispose()
        conn = Nothing

        OrbisViewBillForm.Show()

    End If
End Sub

As you can see I ROUND the sum for 'Sell Price' by 2 decimal places.
Here is the result.
56.1
1.5899999999999999
133.64
12.67
14.93
0.76
0.57
4.25
2.24
0.06
7.75
4.31
7.96
0.78
0.01
33.55

If rounding to 2, why do I get 1.5899999999999999?
To help troubleshoot I changed the rounding to 3 and get the following inconstancies.
56.1
1.5899999999999999
133.643
12.671
14.928
0.764
0.568
4.253
2.2439999999999998
0.058
7.745
4.306
7.9559999999999995
0.779
0.005
33.554

Any help greatly appreciated.
Thanks,

A: The SQL Server FLOAT and REAL data types don't store decimal values exactly.
You should consider changing the database columns to DECIMAL or NUMERIC.


text:
Q: Split Flask view functions into two files I have a fairly large Flask application and I have encountered a need to create view functions in a separate python module. Right now I have all of my view functions in one module where I create my Flask app object, all my view functions, and run the Flask dev server. All of these views so far are urls that users will actually see when using the application so I am okay with keeping these in this existing module. However, I need to have an API where another application will be posting JSON to specific urls. I would like to keep these API handlers (views) separate from the other views.
I have already read the documentation here http://flask.pocoo.org/docs/0.10/patterns/packages/. The way I see it I have two options. I can put my application in a package and create the Flask app in the __init_.py, then import views from each file there as well, with a module to run the app next to the package like it is shown in the docs, or I can create a blueprint for my API handlers and register the blueprint in my existing module.
I am not sure what is the best way to go about this. I am leaning towards blueprints but I need feedback on what other people have done in this situation.

A: This question is not generally a good question for Stack Overflow, since it appears you're asking for an opinion and your question is vague. You should post code that you've already tried and have a more specific question.
Since you're new, I'll answer as best I can, with the very limited information you posted.
I highly recommend using Blueprints for your situation. It will make it a lot easier in the future to manage the application if it's broken up into modules that are glued together with blueprints. Then you would have a small __ init__.py script, that primarily registers the blueprints.


text:
Q: Flutter - Returning items from list that have a property set to true I have a list in flutter with elements. These elements have a property that can be true or false.
I want to map this list and return just the list where the elements are true. This property is a variable of the element object.
return StreamProvider<List<CustomElement>>.value(
      value: DatabaseService().customElements.map((item) => item.isValid),
      child: CustomElementList(),
);

The error I am getting is:

The getter isValid isn't defined for the class List < CustomElement >

So I am wondering how to write the correct syntax for this issue.

A: You return type of stream is List but you are returning isValid, so to return List of bool do following.
change following
StreamProvider<List<CustomElement>>

To
 StreamProvider<List<bool>>

Also convert map into list.
.map((item) => item.isValid).toList()


text:
Q: echo "." until command finishes executing I am currently trying to figure out how to make bash draw a series of dots across the screen (kind of like a progress indicator) until a command finishes executing. For example, say I want to draw dots for a wget download:
wget -s http://url.tar.gz
until "above command has finished executing"; do
    echo -n "."
    sleep 0.05s
done

Can I use "$!" or "$?" to help solve this?
Thank you for the help!

A: This will print dots until wget completes:
while sleep 0.1; do printf "."; done &
wget -q http://url.tar.gz
kill $!
echo "Finished"

wget has its own progress indicator.  The above uses -q to turn that off.
$! expands to the PID of the last process executed in the background which, in this case, is the while loop that prints the dots.  Thus, kill $! stops the loop, ending the printing of dots.

A: Thanks to Squirrel, I was able to solve this. He pointed me to a thread that I had duplicated shell - get exit code of background process. By adding the following to my script, I was able to get it working how I had hoped:
wget -q http://url.example.com.tar.bz2 &
wget_pid=$!

while [ -d /proc/$wget_pid ]; do
    echo -n "."
    sleep 0.01s
done


text:
Q: During test in XUnit EF Core retrieves all possible navigation properties The following code gives different results during testing in XUnit and working normally (here - controller method)
var actual = await _itemService.GetSingleBySpecAsync(
            new ItemWithRelatedFieldsSpecification(2));

I am unable to test my methods normally because test behaviour has nothing to do with real results.
The correct result in controller method - the fields I specified are in place and no more

but during testing I see all Categories being retrieved recursively till the very root - I do not need this

Edit 1
public class Item : BaseEntity
{
    public string Title { get; set; }
    public int CategoryId { get; set; }
    public int StoreId { get; set; }
    public int BrandId { get; set; }
    public int MeasurementUnitId { get; set; }
    public string Description { get; set; }

    public Category Category { get; set; }
    public Store Store { get; set; }
    public Brand Brand { get; set; }
    public MeasurementUnit MeasurementUnit { get; set; }
    public IEnumerable<FileDetails<Item>> Images { get; set; }
    public IEnumerable<ItemVariant> ItemVariants { get; set; }
}
public class Category : BaseEntity
{
    public string Title { get; set; }
    public int ParentCategoryId { get; set; }
    public bool CanHaveItems { get; set; }
    public string Description { get; set; }

    public Category ParentCategory { get; set; }
    public List<Category> Subcategories = new List<Category>();
}
public class BaseEntity
{
    public int Id { get; set; }
}
public async Task<Item> GetSingleBySpecAsync(ISpecification<Item> spec)
{
   return await _itemRepository.GetSingleBySpecAsync(spec);
}
public async Task<T> GetSingleBySpecAsync(ISpecification<T> spec)
{
    return (await ListAsync(spec)).FirstOrDefault();
}
public async Task<IEnumerable<T>> ListAsync(ISpecification<T> spec)
{
    // fetch a Queryable that includes all expression-based includes
    var queryableResultWithIncludes = spec.Includes
       .Aggregate(_dbContext.Set<T>().AsQueryable(),
           (current, include) => current.Include(include));
     // modify the IQueryable to include any string-based include statements
     var secondaryResult = spec.IncludeStrings
        .Aggregate(queryableResultWithIncludes,
            (current, include) => current.Include(include));

    // return the result of the query using the specification's criteria expression
    return await secondaryResult
                    .Where(spec.Criteria)
                        .ToListAsync();
}
public class ItemWithRelatedFieldsSpecification : BaseSpecification<Item>
{
    public ItemWithRelatedFieldsSpecification(int? id)
        : base(i => (!id.HasValue || i.Id == id))
    {
        AddInclude(i => i.MeasurementUnit);
        AddInclude(i => i.Store);
        AddInclude(i => i.Category);
        AddInclude(i => i.Brand);
        AddInclude(i => i.Images);
    }
}
public abstract class BaseSpecification<T> : ISpecification<T>
{
    public BaseSpecification(Expression<Func<T, bool>> criteria)
    {
        Criteria = criteria;
    }
    public Expression<Func<T, bool>> Criteria { get; }
    public List<Expression<Func<T, object>>> Includes { get; } = new List<Expression<Func<T, object>>>();
    public List<string> IncludeStrings { get; } = new List<string>();

    protected virtual void AddInclude(Expression<Func<T, object>> includeExpression)
    {
        Includes.Add(includeExpression);
    }
    protected virtual void AddInclude(string includeString)
    {
        IncludeStrings.Add(includeString);
    }
}


text:
Q: Выбор последней записи в которой сумма была >0 Подскажите пожалуйста как правильно сделать выборку.
Не могу выбрать последнего поставщика, выбираются все что были. Как это можно исправить? Условие max не подходит так как номер поставщика будет не по возрастанию, а по условию sum>0. Сумма больше 0 могла быть в промежутке с 1-9 месяц включительно.
select trader.name
from trader, monthly_accounting mm, daily_accounting dd
where mm.trader=trader.i and mm.sum>0 and mm.m<=dd.m and mm.y=dd.y and dd.y=2019 and dd.m=9 and dd.d=10 and dd.post=102358

A: select **first 1** trader.name
from
     trader,
     monthly_accounting mm,
     daily_accounting dd
where
     mm.trader=trader.i
     and mm.sum>0
     and mm.m<=dd.m
     and mm.y=dd.y
     and dd.y=2019
     and dd.m=9
     and dd.d=10
     and dd.post=102358
**order by trader.name desc**


text:
Q: How to enable domain select on Vista logon screen? I recently set up the first Vista laptop for our domain, and discovered that there is no longer a domain dropdown box.  Main application is switching between domain and local computer accounts.  Since the syntax of a full domain logon name is minor trivia to a user, is there a way put back the domain select, or at least have multiple users shown on the "Switch User" screen?

A: Nope, I tried for ages and even went through a support request at Microsoft.
The feature no longer exists and you have to type Domain\username.
By default, Windows will try and go to the default domain it is joined to - unless the user exists locally.

A: Using the UPN format might be more logical for the end-users, ie instead of domain\user or domain.com\user - use user@domain.com.
May one ask why local user accounts are used at all?

A: There's no way (that I'm aware of...) to show a list of available domains; howewer, Vista will by default logon to the domain the computer is joined to, if the user name you type is not the name of a local user account; so in most cases you don't need to type the domain name.
The most notable exception is, of course, the Administrator account, which always exists both int the local system and in the domain; if you only type "Administrator", Vista will do a local logon, so you need to explicitly type "DOMAIN\Administrator" if you want to log on as the domain Administrator. But if you type "username" and there's no local user called "username", Vista will logon to the domain.
Of ourse, if you have multiple domains, things tend to get a little tricky... I personally hate Vista's logon screen; but Microsoft seems to like it a lot :(


text:
Q: Dominated convergence theorem for log-integrable rational functions Let $\{f_n\}_{n\ge 0}$ be a sequence of rational functions $f_n\colon \mathbb{C}\to\mathbb{R}_+$ which are non-negative and analytic on the unit circle and assume that $\lim_{n\to\infty} f_n =  f$ pointwise, where $f$ is again a rational function non-negative and analytic on the unit circle. Notice that $f_n$ can possess zeros on the unit circle. It is well known however that the latter zeros represent log-integrable singularities. Indeed it holds that $\log\,f_n$ is integrable on the unit circle, i.e.
$$
\left|\int_{-\pi}^{\pi} \log\, f_n(e^{j\theta})\, \mathrm{d}\theta\right|<\infty.
$$
My question concerns the limit of the integral of the sequence $\{\log\,f_n\}_{n\ge 0}$, namely
$$
\lim_{n\to \infty}\int_{-\pi}^{\pi}\, \log\, f_n(e^{j\theta}) \,\mathrm{d}\theta \overset{?}{=} \int_{-\pi}^{\pi} \log\, f(e^{j\theta})\, \mathrm{d}\theta.
$$
My attempt was to apply Lebesgue's dominated convergence theorem. However in this case the dominating function $g$ such that $|\log\, f_n|\le \log\,g$ can have (at most) a countable number of zeros on the unit circle (corresponding to all the possible zeros on the unit circle of $f_n$'s) and I'm not completely sure whether the logarithm of such a function is integrable.
Any help is really appreciated.

A: There are many counterexamples.
If $p$ is a polynomial, then on the circle $|p|^2$ equals a rational function of the kind under discussion. But such $|p|^2$ are dense in the continuous nonnegative functions on the circle. (This follows from Stone-Weierstrass.) This allows for bending these $|p|^2$ around quite a bit.
For $n=1,2,\dots $ define $f_n$ on the circle by visualizing it on $[0,2\pi].$ There it is the piecewise linear function whose graph is connects the points $(0,1),(1/n,1),(2/n,e^n),(3/n,e^n),(4/n,1),(2\pi,1).$ (Good to draw a picture.) So $f_n$ is a gliding hump that equals $1$ except on the interval $[1/n,4/n],$ where it spikes up to the value $e^n$ on the interval $[2/n,3/n].$ Note that $f_n \to 1$ pointwise everywhere on $[0,2\pi].$
We can find polynomials $p_n$ such that $||p_n|^2-f_n|<1/n$ on the circle. Thus $|p_n|^2\to 1$ pointwise everywhere on the cirlce. However,
$$\int_0^{2\pi}\log |p_n|^2 \ge \int_{2/n}^{3/n}\log |p_n|^2 \ge \int_{2/n}^{3/n}\log (f_n -1/n) =  \int_{2/n}^{3/n}\log (e^n -1/n).$$
The last expression $\to 1$ as $n\to \infty,$ so certainly we don't have convergence to $\int_0^{2\pi} \log 1 = 0.$


text:
Q: zsh autocomplete without completing prompt Tried to find this answer, but could not.
I am new to zsh, and I like it a lot on my Mac.  I am looking for an option to set it to autocomplete, but without putting the completion in the prompt until I hit enter.
For example, if I type:
cd Documents/
and then press tab, it will highlight the options but ALSO add them to the prompt, so I have to either tab a ton to get to the one I want, or delete back. Here is what I mean:
cd Documents/ (press tab)

it shows:
$ cd Documents/Apple

Apple         Banana       Durian
Orange        Starfruit    Tamarine

But I am going through the list to get to Tamarine--I want to see the options and be able to continue to tab through them, but not have them added to my current prompt until I hit Enter.
Is this possible?
unsetopt automenu

Gets me close, but then I cannot tab through the options.
Does that make sense?
Thanks!

A: Make sure that the option MENU_COMPLETE is disabled:
setopt nomenucomplete

MENU_COMPLETE (-Y)
On an ambiguous completion, instead of listing possibilities or beeping, insert the first match immediately.  Then when completion is requested again,  remove the first  match  and insert the second match, etc.  When there are no more matches, go back to the first one again. reverse-menu-complete may be used to loop through the list in the other direction. This option overrides AUTO_MENU.

A: One way to do this is to use a zsh framework. I recommend oh-my-zsh, as I am using it myself.  With it, hitting tab once will show all the possibilities, and hitting it once more will enter select mode, where the possibilities will show in your prompt and you can switch between them not only with tab, but also with arrow keys.


text:
Q: How can I shift list elements "down" to corresponding elements of another list recursively in Python? I have a list of 6-element lists.  If two particular "columns" of the nested list don't match, I want to recursively "shift" the first 3 elements to the next list for the length of the top list... So:
list1 = [
    ['4', 'and', '3', '4', 'EOS', '15'],
    ['4', 'what', '3', '0', 'and', '2'],
    ['4', 'is', '2', '1', 'what', '3'],
    ['4', 'the', '2', '1', 'is', '5']
]

becomes
list2 =  [
    ['0', 'EOS', '0', '4', 'EOS', '15'],
    ['4', 'and', '3', '0', 'and', '2'],
    ['4', 'what', '3', '1', 'what', '3'],
    ['4', 'is', '2', '1', 'is', '5']
]

where the last 3 elements of the last list don't add a new list.
I'm sure there's some built-in way to do this, but I can't find it.  Thanks!

A: I don't know about built-in, and certainly not terribly pythonic, but this works (modifies in place):
list1 = [
    ['4', 'and', '3', '4', 'EOS', '15'],
    ['4', 'what', '3', '0', 'and', '2'],
    ['4', 'is', '2', '1', 'what', '3'],
    ['4', 'the', '2', '1', 'is', '5']
]
prev = ['0','EOS','0']
for i in list1:
    tmp = i[0:3]
    i[0:3] = prev
    prev = tmp

print list1

A little better but ugly still (creates a new list):
list1 = [
    ['4', 'and', '3', '4', 'EOS', '15'],
    ['4', 'what', '3', '0', 'and', '2'],
    ['4', 'is', '2', '1', 'what', '3'],
    ['4', 'the', '2', '1', 'is', '5']
]

prev = ['0','EOS','0']
y = [prev + [0,0,0]] + list1
list2 = [y[i][0:3] + list1[i][3:] for i in range(0, len(list1))]

Modifies the old list by prepending the new data, still creates a new list:
list1 = [
    ['4', 'and', '3', '4', 'EOS', '15'],
    ['4', 'what', '3', '0', 'and', '2'],
    ['4', 'is', '2', '1', 'what', '3'],
    ['4', 'the', '2', '1', 'is', '5']
]

list1 = [['0','EOS','0']] + list1
print [list1[i-1][0:3] + list1[i][3:] for i in range(1, len(list1))]

This might be the best. Takes advantage of the behavior of sequence[-1], creates a new list:
list1 = [
    ['4', 'and', '3', '4', 'EOS', '15'],
    ['4', 'what', '3', '0', 'and', '2'],
    ['4', 'is', '2', '1', 'what', '3'],
    ['4', 'the', '2', '1', 'is', '5']
]

# Put the new data on the end of the list
list1[-1][0:3] = ['0','EOS','0']
# note how i=0 -1 references the *last* element of the list
print [list1[i-1][0:3] + list1[i][3:] for i in range(0, len(list1))]


text:
Q: Laravel: How to get Models out of query results? Suppose I have a query that, among other things, returns user id's, this query was built using DB::table()... rather than using the models, so, as a result, I got a collection with arrays for each retrieved row, something like this:
user_id | calculated_data
--------+----------------
      1 |     123
      2 |     111
      3 |     222
    ... |     ...

Supose I store this collection on a $data variable, of course if I do a foreach ($data as $d) { $d->user_id ... } will work.
But I want this query to return something more like what the ORM does, so instead user_ids, return User models so I can do, for example, a $data->user->name
Can this be even done? if so, how?

A: You can use the hydrate() function, it accepts an array of stdClass objects (or even associative arrays AFAIR) as input and returns a collection of Eloquent Models, so you can do things like this:
$result = DB::table('users')->take(10)->get();
$users = App\User::hydrate($result->all());

You can even get a collection of Eloquent Models directly from a RAW query with the fromQuery() function, i.e.:
$users = App\User::fromQuery('SELECT * FROM users WHERE id > ?', [2])

Update: If in your collection you don't have all the fields to hydrate a model, you can preload all the users you need with one query and modify your collection, i.e.:
$users = App\User::find($data->pluck('user_id'));
$data->transform(function($item) use($users) {
            $item->user = $users->where('id', $item->user_id)->first()
            return $item;
        });

A: You need to use Eloquent to call value the "ORM way" I did not find anything related to the query builder in relation to ORM.
You could do something like this:
$flights = App\Flight::all();

foreach ($flights as $flight) {
    echo $flight->name;
}

And in the ORM way you would get the user like this:
foreach ($flights as $flight) {
    echo $flight->user->name;
}

Of course you would need to setup the correct relations.

A: // initial query will return collection of objects
$query = DB::table('user_something')
   ->join('users', 'users.id', 'user_something.user_id');

// You could cast it to the model query, by using fromSub.
// Make sure to alias a subquery same as the model's name,
// otherwise it would not be able to parse models data
User::fromSub($query, 'users');

// The most robust way is to get table name from the model
User::fromSub($query, User::make()->getTable());


text:
Q: Adding methods to class and use them in other groovy code I'm very new to Groovy. I have a class where I'm adding methods using metaClass. Here is the code I have for Parser.groovy:
PrivateClass.metaClass.convertDDTToMap { obj,fileLocation ->

}

where PrivateClass is a class coming from a jar. Now in other file named Hack.groovy I have the following code:
class Hack extends PrivateClass
{
//.. code
convertDDTToMap(param,param)
}

when I run Hack.groovy, I get the exception that the method convertDDTToMap is not there.
However Parser.groovy is in the same classpath and it gets compiled. But its not adding the method.
Where I'm making the mistake?

A: Parser.groovy being compiled only is doing nothing, the code there needs to be called. For example using new Parser().run()


text:
Q: How did they feed people at the end of "Endgame"? With half of all people gone, the infrastructure and food must have been greatly reduced. In five years, how would they have fed a population that suddenly doubled?

A: At the end of Endgame, the un-snappening results in the return of all of the humans and other forms of life that Thanos destroyed in the Snap.

Scott Lang (Ant Man) looks at a bird nesting in a tree which is now miraculously two birds.
This presumably includes a significant number of animals (and plants?) that are now available for harvesting. The governments of the world, now back up to fighting strength in terms of manpower, presumably had contingency plans in place in case the population returned as fast as it had disappeared. This would presumably include the stockpiling of rationable items like MREs.

A: Far From Home shows that a number of issues have been caused by the Blip, Aunt May is hosting a benefit to raise money for all those made homeless by the blip (she says she reappeared in her old apartment to find other people living there). I imagine other charities have been set up and governments have had to scramble to deal with the sudden influx of people. There are also the added issues, people who claimed to have been snapped when they where not, pay out of life insurance now needing to be paid back, children and babies blipping back with no idea where there parents are living now. Parents blipping back and having to hunt down and find there children who have had 5 years dealing with the loss of there families. I imagine as well that a number of people committed suicide, died of natural causes etc, they won't have returned and people who where snapped out will have to deal with emotional fallout of finding out they have returned, but there mother/father/husband/wife/son/daughter is dead. I imagine the impact will reverberate around the MCU for a few more films yet.


text:
Q: On WordPress.org Plugin repository, Last Updated Date doesn't match with Plugin Version Update Date I have been going through the Plugin lists on all my client sites, looking for Plugins that haven't been updated by Plugin Authors. Every time we update a Plugin on a website, we note the date in our documentation. In the process, I have noticed a strange disagreement: on WordPress.org Plugin repository, Last Updated Date doesn't match with the Plugin's Version Update Date.
For example, in our documentation, a plugin named Category Post shows that the last update to version 4.9.13 was done on 9/29/2021. The date here would cause this to be marked as a plugin that might need to be replaced, because it looks like it's a plugin that isn't being maintained.
But, when I went to WordPress.org (on February 2023) to check on the plugin, it says Last Updated: 1 month ago, to that same version number (4.9.13)!
Any clue as to what is happening?

A: Please check the Category Posts Plugin's Changelog on WordPress.org (on the Development tab). I'm providing the screenshot below:

You'll notice that version 4.9.13 was indeed updated on JULY 22 2021.

4.9.13 – JULY 22 2021
Fixed Line number with WordPress 5.8

However, on the right side it shows: Last updated: 1 month ago.
This last update doesn't refer to updates to the plugin version itself, rather updated information on wordpress.org that it was Tested up to: 6.1.1.
I've dug further down the source code to the last commit of the plugin files, and you can see that the change was only made on the readme.txt file and it's just the Tested up to: 6.1 part:

WordPress.org's plugin listing page is generated from this readme.txt file. So what WordPress.org is referring to when it says: Last updated: 1 month ago, is only this much.
So you see, there's no significant update and there's no actual disagreement about the update date.


text:
Q: Should memory leak always results high memory consumption? My client is using RHEL and they are having an issue which to me seems like a memory leak.
But my client showed me there are tons of memory available and consumption is reasonable.
So my question is, in case of a memory leak is it inevitable to face memory consumption issue? Or there could be scenarios where memory leak could result in many other more issues without memory consumtion?

A: Memory leaking is something we as developers definitely don't want and should fix when then appear.
However, memory leaks are not necessarily a problem in practice. Unless there is a bug or a memory leak in the OS kernel itself, all leaked memory happening in some buggy software will automatically be freed at the program termination. So the severity of memory leak really depends on actual numbers:

*

*What is the average memory leaking rate, in bytes per second?

*What is the expected program life time, in seconds?

*How much memory is available on the system?

As an example, a small utility leaking 1 kilobyte per second running only during 1 second on a computer with 32 GB will go totally unnoticed unless you profile it. But if this same utility is a permanent daemon on a production server, it becomes a problem: the amount of allocated memory would increase 86 MB per day, and after a year of uptime the daemon would have leaked 31.5 GB, the same amount as the system memory.
But even in the latter case, the system will probably continue to run smoothly because all the leaked memory would likely be swapped to disk as stay there forever, since the leaked memory cannot be accessed anymore when pointer to it is lost.
A well written software without any memory leak could well allocate gigabytes of memory for its need. This is a much higher memory consumption than a completely naive program written by a beginner, leaking the totally of its few kilobytes.
So my conclusion is that it depends. Most of the time memory leaks in user programs are not a problem, though they should be avoided of course. In an OS kernel and in daemon software, they are usually critical.


text:
Q: Efficiently get array of all previous dates per id per date limited to past 6 months in BigQuery I have a very big table 'DATES_EVENTS' (20 T) that looks like this:
ID      DATE
1   '2022-04-01'
1   '2022-03-02'
1   '2022-03-01'
2   '2022-05-01'
3   '2021-12-01'
3   '2021-11-11'
3   '2020-11-11'
3   '2020-10-01'

I want per each row to get all past dates (per user) limited to up to 6 months.
My desired table:
ID      DATE                   DATE_list
1   '2022-04-01'   ['2022-04-01','2022-03-02','2022-03-01']
1   '2022-03-02'   ['2022-03-02','2022-03-01']
1   '2022-03-01'   ['2022-03-01']
2   '2022-05-01'   ['2022-05-01']
3   '2021-12-01'   ['2021-12-01','2021-11-11']
3   '2021-11-11'   ['2021-11-11']
3   '2020-11-11'   ['2020-11-11','2020-10-01']
3   '2020-10-01'   ['2020-10-01']

I have a solution for all dates not limited:
SELECT
  ID, DATE, ARRAY_AGG(DATE) OVER (PARTITION BY ID ORDER BY DATE) as DATE_list
FROM
  DATES_EVENTS

But for a limited up to 6 months I don't have an efficient solution:
SELECT
  distinct A.ID, A.DATE, ARRAY_AGG(B.DATE) OVER (PARTITION BY B.ID ORDER BY B.DATE) as DATE_list
FROM
  DATES_EVENTS A
INNER JOIN
  DATES_EVENTS B
ON
 A.ID=B.ID
 AND B.DATE BETWEEN DATE_SUB(A.DATE, INTERVAL 180 DAY) AND A.DATE

** ruffly a solution

Anyone know of a good and efficient way to do what I need?

A: Consider below approach
select id, date, array(
  select day
  from t.date_list day
  where day <= date
  order by day desc
) as date_list
from (
  select *, array_agg(date) over win as date_list
  from dates_events
  window win as (
    partition by id
    order by extract(year from date) * 12 + extract(month from date)
    range between 5 preceding and current row
  )
) t

if applied to sample data in your question - output is

In case if (as I noticed in your question) 180 days is appropriate substitution for 6 months for you  - you can use below simpler version
select *, array_agg(date) over win as date_list
from dates_events
window win as (
  partition by id
  order by unix_date(date)
  range between current row and 179 following
)


text:
Q: How to design HBase schema for Twitter data? I have following Twitter data and I want to design a schema for the same .The queries which I would need to perform would be following:
get tweets volume for time interval,tweets with corresponding user info,tweets with corresponding topic info etc... Based on the below data ,anyone tell where designing of schema is correct.. (make rowkey as id+timestamp, column family as user ,others grouped into primary column . Any Suggestions ?
{
   "created_at":"Tue Feb 19 11:16:34 +0000 2013",
   "id":303825398179979265,
   "id_str":"303825398179979265",
   "text":"Unleashing Innovation Conference Kicks Off - Wall Street Journal (India)              http:\/\/t.co\/3bkXJBz1",
   "source":"\u003ca href=\"http:\/\/dlvr.it\" rel=\"nofollow\"\u003edlvr.it\u003c\/a\u003e",
   "truncated":false,
   "in_reply_to_status_id":null,
   "in_reply_to_status_id_str":null,
   "in_reply_to_user_id":null,
   "in_reply_to_user_id_str":null,
   "in_reply_to_screen_name":null,
   "user":{
      "id":948385189,
      "id_str":"948385189",
      "name":"Innovation Plaza",
      "screen_name":"InnovationPlaza",
      "location":"",
      "url":"http:\/\/tinyurl.com\/ee4jiralp",
      "description":"All the latest breaking news about Innovation",
      "protected":false,
      "followers_count":136,
      "friends_count":1489,
      "listed_count":1,
      "created_at":"Wed Nov 14 19:49:18 +0000 2012",
      "favourites_count":0,
      "utc_offset":28800,
      "time_zone":"Beijing",
      "geo_enabled":false,
      "verified":false,
      "statuses_count":149,
      "lang":"en",
      "contributors_enabled":false,
      "is_translator":false,
      "profile_background_color":"131516",
      "profile_background_image_url":"http:\/\/a0.twimg.com\/profile_background_images\/781710342\/17a75bf22d9fdad38eebc1c0cd441527.jpeg",
      "profile_background_image_url_https":"https:\/\/si0.twimg.com\/profile_background_images\/781710342\/17a75bf22d9fdad38eebc1c0cd441527.jpeg",
      "profile_background_tile":true,
      "profile_image_url":"http:\/\/a0.twimg.com\/profile_images\/3205718892\/8126617ac6b7a0e80fe219327c573852_normal.jpeg",
      "profile_image_url_https":"https:\/\/si0.twimg.com\/profile_images\/3205718892\/8126617ac6b7a0e80fe219327c573852_normal.jpeg",
      "profile_link_color":"009999",
      "profile_sidebar_border_color":"FFFFFF",
      "profile_sidebar_fill_color":"EFEFEF",
      "profile_text_color":"333333",
      "profile_use_background_image":true,
      "default_profile":false,
      "default_profile_image":false,
      "following":null,
      "follow_request_sent":null,
      "notifications":null
   },
   "geo":null,
   "coordinates":null,
   "place":null,
   "contributors":null,
   "retweet_count":0,
   "entities":{
      "hashtags":[

      ],
      "urls":[
         {
            "url":"http:\/\/t.co\/3bkXJBz1",
            "expanded_url":"http:\/\/dlvr.it\/2yyG5C",
            "display_url":"dlvr.it\/2yyG5C",
            "indices":[
               73,
               93
            ]
         }
      ],
      "user_mentions":[

      ]
   },
   "favorited":false,
   "retweeted":false,
   "possibly_sensitive":false
}

A: If you are 100% sure that the ID is unique, you could this one as your row key to store the bulk of the data:
303825398179979265 -> data_CF
You column family data_CF would be defined in these lines:

"created_at":"Tue Feb 19 11:16:34 +0000 2013"
"id_str":"303825398179979265"
...
"user_id":948385189 { take note here I'm denormalizing your dictionary }
"user_name":"Innovation Plaza"

It gets a little trickier for the lists. The solution is to put something that will make it unique prefixed by the category:

"entities_hashtags_":"\x00" { Here \x00 is a dummy value }

For the URL, if the ordering is not important, you may prefix it with a UUID. It will guarantee that it is unique.
The advantage with this approach is if you need to update a field in this data, it will be done atomically since HBase guarantees row atomicity.
For the second question, if you need instantaneous aggregated information, you will have to precompute it and store it as you said in another table. If you want this data to be generated through M/R, you may put the timestamp + row id if it is to be time based. By topic would be something like topic + row id. This allows you to write Prefix scans with start stop row that will include only the time range or the topic you are interested.
Have fun !


text:
Q: Run Safari from command line with URL parameter I'm trying to open Safari (on OS X 10.8) from the terminal by executing the following:
open -a /Applications/Safari --args "http://www.example.com"

Safari opens and tries to navigate to the url:
file:///http:/www.example.com

Is there a way to get Safari to open up the browser at the specified url?
Note: I can't do open http://www.example.com because I can't be guaranteed that the Safari is the default browser. (And before I'm asked why I'm not using the default browser - I'm doing browser specific test automation.)

A: It would seem the answer is:
open -a safari http://www.example.com

According to the man page for open(1),  open -a <applicationName file> opens a given file with a given application. Therefore, this seems like the most appropriate syntax.
This forum thread explain more.


text:
Q: Intuitive way to connect gamma and chi-squared distributions I understand that a chi-squared distribution is a special case of the gamma distribution. However, I find claims of "the math just works out" to be an unhelpful in remembering or understanding the relationship.
Is there a satisfying way to relate these two distributions? For example, is there a way to connect the Poisson process interpretation of the gamma to the "sum of squares of iid normals" interpretation of the chi-squared? Why does the gamma have anything to do with Gaussian r.v.s that has been squared?
For possible reference, some intuition I currently have:

*

*I intuit the gamma distribution as the waiting time for the $k$-th arrival in a Poisson process. This supports the idea that independent gamma r.v.s (with same rate parameter) can be summed to another gamma distribution.

*A gamma distribution with a large shape parameter can be thought of as the sum of many independent gamma r.v.s with smaller shape parameters. By CLT, the gamma converges to a normal distribution as the shape parameter grows. (Same deal with the chi-squared distribution.)

A: Intuition has to be trained through arduous application to become other than misleading. There are too many implied questions here for a single post. However, addressing those here does provide a series of links summarizing some of the properties of the gamma distribution, so the implied questions posited may have some value to the potential reader.
Q1 Chi-squared and gamma distribution
A1 See end of answer here, and even more explicitly here. In particular in that latter answer, note the following statement: "Unique properties are scattered around all over Mathematics, and most of the time, they don't reflect some "deeper intuition" or "structure" - they just exist (thankfully)."
Q2 "is there a way to connect the Poisson process interpretation of the gamma"
A2 See answer No, there is no Poisson process interpretation. Poisson is a subset of gamma for positive integers only. Thus, there is a gamma simplification that leads to Poisson not the obverse.
Q3 An implied question: "I intuit the gamma distribution as the waiting time for the -th arrival in a Poisson process. This supports the idea that independent gamma r.v.s (with same rate parameter) can be summed to another gamma distribution."
A3 Backwards again. Although the special case of same rate parameter has closure under convolution (sum of rv's), this is not the case without having the same rate parameter, where the sum (convolution) of two gamma distributions is not closed by a gamma distribution. For what it actually is see this link for the sum of two gammas, and for more than two see this other link. Second, as a Poisson distribution is a gamma distribution subset one can at most "suspect" that a gamma distribution might have something to do with wait times. What is lacking is any such determination for anything beyond that special case simplification.
Statement "A gamma distribution with a large shape parameter can be thought of as the sum of many independent gamma r.v.s with smaller (Sic, iff identical) shape parameters." It can, but to what end?
Q4 "By CLT, the gamma converges to a normal distribution as the shape parameter grows."
A4 The shape does but the mean would grow without bound to do so. To maintain stationarity, a lot more has to be done. See this answer.


text:
Q: How to draw a shape right at the position of the QPushButton clicked on? //oneLed.h
#pragma once

#include<QPushButton>

class oneLed :public QPushButton
{
    Q_OBJECT

public:
    oneLed(QWidget* parent = 0);
protected:
    void doPainting();
};

#include"oneLed.h"
#include<QPainter>
oneLed::oneLed(QWidget* parent)
    :QPushButton(parent)
{
    connect(this, &QPushButton::clicked, this, &oneLed::doPainting);
}

void oneLed::doPainting()
{
        QPainter painter(this);
        //painter.setRenderHint(QPainter::Antialiasing);
        painter.setPen(QPen(QBrush("#888"), 1));
        painter.setBrush(QBrush(QColor("#888")));
        painter.drawEllipse(0, 0, this->width(), this->height());
        //painter.drawEllipse(0, 0, 30, 30);

}

//main.cpp
#include"oneLed.h"
#include <QtWidgets/QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    oneLed w;
    w.resize(100, 500);
    w.show();
    return a.exec();
}

I want to achieve the following effect:
When I clicked on the oneLed object, A circle appears at the position of the oneled object. When I click on the oneLed object again, the circle disappears.
But in fact when I click on the oneLed object, the circle doesn't appear.

A: I guess you got it wrong. What happens in your code is:

*

*the button is clicked and your doPainting slot is called

*you do your custom painting

*the actual button paint event is triggered by Qt main event loop and overwrites your painting

You need to override the paintEvent method.
In your custom slot, raise a boolean flag that indicates the button has been pressed.
void oneLed::slotClicked()
{
    m_clicked = !m_clicked;
}

Then do something like this:
void oneLed::paintEvent(QPaintEvent *event)
{
    // first render the Qt button
    QPushButton::paintEvent(event);
    // afterward, do custom painting over it
    if (m_clicked)
    {
        QPainter painter(this);
        painter.setPen(QPen(QBrush("#888"), 1));
        painter.setBrush(QBrush(QColor("#888")));
        painter.drawEllipse(0, 0, this->width(), this->height());
    }
}

A: The method that you implement is paintEvent, in the slot that doPainting you must change a flag and call the update() method.
Important: The update method calls paintEvent.
oneLed.h
#ifndef ONELED_H
#define ONELED_H

#include <QPushButton>

class oneLed : public QPushButton
{
    Q_OBJECT
public:
    oneLed(QWidget* parent = 0);

protected:
    void paintEvent(QPaintEvent * event);

private slots:
    void doPainting();

private:
     bool state;
};

#endif // ONELED_H

oneLed.cpp
#include "oneled.h"
#include <QPainter>

oneLed::oneLed(QWidget *parent):QPushButton(parent)
{
    state = false;
    connect(this, &QPushButton::clicked, this, &oneLed::doPainting);
}

void oneLed::paintEvent(QPaintEvent *event)
{
    QPushButton::paintEvent(event);
    if(state){
        QPainter painter(this);
        //painter.setRenderHint(QPainter::Antialiasing);
        painter.setPen(QPen(QBrush("#888"), 1));
        painter.setBrush(QBrush(QColor("#888")));
        painter.drawEllipse(0, 0, width(), height());
    }

}

void oneLed::doPainting()
{
    state = !state;
    update();
}


text:
Q: django create a form from list Lets say I have a list
mylist = ['name', 'username']

And I want to create a form from this list:
class MyForm(forms.Form):
    for field in mylist:
        field = forms.CharField(max_length=100)

Its not giving me the form for name and username.
How can I create a form from list ?

A: All fields are kept in self.fields dictionary:
class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        for field in mylist:
            self.fields[field] = forms.CharField(max_length=100)


text:
Q: Can't run parallel jobs with SLURM on Ubuntu 18.04 on same machine Seems i can't run parallel jobs on the same node.
I've set up SLURM on a single machine (Ubuntu 18.04 CPUs=8 Boards=1 SocketsPerBoard=1 CoresPerSocket=4 ThreadsPerCore=2 RealMemory=15976) to use with Kaldi.
To test if i can execute jobs in parallel i've used a short python snippet:
#!/usr/bin/env python
# demo.py:
# usage: python demo.py [job-number]

import sys
import socket
from time import sleep

def work(jobnum):
  print("Starting job {} on {}.".format(jobnum, socket.gethostname()))
  sleep(5)
  print("Finished job {}...\n".format(jobnum))

if __name__ == "__main__":
  jobnum = sys.argv[1]
  work(jobnum)

And then basically i tried to execute three jobs in parallel as:
#!/bin/bash

#SBATCH --nodes=1
#SBATCH --ntasks=3
#SBATCH --cpus-per-task=1

# Execute jobs in parallel
srun -c 1 --exclusive python demo.py 0 &
srun -c 1 --exclusive python demo.py 1 &
srun -c 1 --exclusive python demo.py 2 &
wait

I've tried pretty much all sort of things with #SBATCH arguments to no avail. They are always executed sequentially.
Using squeue -o "%all" i found that basically the first job has 8 cpus while the second and third 1 cpus and thus are queued as the first job is taking all resources.
So it must be something related to the installation or configuration.
Here is my configuration file:
# slurm.conf file generated by configurator.html.
# Put this file on all nodes of your cluster.
# See the slurm.conf man page for more information.
#
ControlMachine=sam-red
#ControlAddr=
#BackupController=
#BackupAddr=
#
AuthType=auth/munge
#CheckpointType=checkpoint/none
CryptoType=crypto/munge
#DisableRootJobs=NO
#EnforcePartLimits=NO
#Epilog=
#EpilogSlurmctld=
#FirstJobId=1
#MaxJobId=999999
#GresTypes=
#GroupUpdateForce=0
#GroupUpdateTime=600
#JobCheckpointDir=/var/lib/slurm-llnl/checkpoint
#JobCredentialPrivateKey=
#JobCredentialPublicCertificate=
#JobFileAppend=0
#JobRequeue=1
#JobSubmitPlugins=1
#KillOnBadExit=0
#LaunchType=launch/slurm
#Licenses=foo*4,bar
#MailProg=/usr/bin/mail
#MaxJobCount=5000
#MaxStepCount=40000
#MaxTasksPerNode=128
MpiDefault=none
#MpiParams=ports=#-#
#PluginDir=
#PlugStackConfig=
#PrivateData=jobs
ProctrackType=proctrack/pgid
#Prolog=
#PrologFlags=
#PrologSlurmctld=
#PropagatePrioProcess=0
#PropagateResourceLimits=
#PropagateResourceLimitsExcept=
#RebootProgram=
ReturnToService=1
#SallocDefaultCommand=
SlurmctldPidFile=/var/run/slurm-llnl/slurmctld.pid
SlurmctldPort=6817
SlurmdPidFile=/var/run/slurm-llnl/slurmd.pid
SlurmdPort=6818
SlurmdSpoolDir=/var/lib/slurm-llnl/slurmd
SlurmUser=sam
#SlurmdUser=root
#SrunEpilog=
#SrunProlog=
StateSaveLocation=/var/lib/slurm-llnl/slurmctld
SwitchType=switch/none
#TaskEpilog=
TaskPlugin=task/none
#TaskPluginParam=
#TaskProlog=
#TopologyPlugin=topology/tree
#TmpFS=/tmp
#TrackWCKey=no
#TreeWidth=
#UnkillableStepProgram=
#UsePAM=0
#
#
# TIMERS
#BatchStartTimeout=10
#CompleteWait=0
#EpilogMsgTime=2000
#GetEnvTimeout=2
#HealthCheckInterval=0
#HealthCheckProgram=
InactiveLimit=0
KillWait=30
#MessageTimeout=10
#ResvOverRun=0
MinJobAge=300
#OverTimeLimit=0
SlurmctldTimeout=120
SlurmdTimeout=300
#UnkillableStepTimeout=60
#VSizeFactor=0
Waittime=0
#
#
# SCHEDULING
#DefMemPerCPU=0
FastSchedule=1
#MaxMemPerCPU=0
#SchedulerRootFilter=1
#SchedulerTimeSlice=30
SchedulerType=sched/backfill
SchedulerPort=7321
SelectType=select/cons_res
SelectTypeParameters=CR_Core
#
#
# JOB PRIORITY
#PriorityFlags=
#PriorityType=priority/basic
#PriorityDecayHalfLife=
#PriorityCalcPeriod=
#PriorityFavorSmall=
#PriorityMaxAge=
#PriorityUsageResetPeriod=
#PriorityWeightAge=
#PriorityWeightFairshare=
#PriorityWeightJobSize=
#PriorityWeightPartition=
#PriorityWeightQOS=
#
#
# LOGGING AND ACCOUNTING
#AccountingStorageEnforce=0
#AccountingStorageHost=
#AccountingStorageLoc=
#AccountingStoragePass=
#AccountingStoragePort=
AccountingStorageType=accounting_storage/none
#AccountingStorageUser=
AccountingStoreJobComment=YES
ClusterName=cluster
#DebugFlags=
#JobCompHost=
#JobCompLoc=
#JobCompPass=
#JobCompPort=
JobCompType=jobcomp/none
#JobCompUser=
#JobContainerType=job_container/none
JobAcctGatherFrequency=30
JobAcctGatherType=jobacct_gather/none
SlurmctldDebug=3
SlurmctldLogFile=/var/log/slurm-llnl/slurmctld.log
SlurmdDebug=3
SlurmdLogFile=/var/log/slurm-llnl/slurmd.log
#SlurmSchedLogFile=
#SlurmSchedLogLevel=
#
#
# POWER SAVE SUPPORT FOR IDLE NODES (optional)
#SuspendProgram=
#ResumeProgram=
#SuspendTimeout=
#ResumeTimeout=
#ResumeRate=
#SuspendExcNodes=
#SuspendExcParts=
#SuspendRate=
#SuspendTime=
#
#
# COMPUTE NODES
NodeName=sam-red CPUs=8 RealMemory=14000 Sockets=1 CoresPerSocket=4 ThreadsPerCore=2 State=UNKNOWN
PartitionName=shared Nodes=sam-red Default=YES MaxTime=INFINITE State=UP

I am pretty much a newbie regarding schedulers, maybe it could be a trivial issue for someone with more experience.
UPDATE:
submitting the job with:
#!/bin/bash

srun --nodes=1 --nodelist=sam-red --ntasks=1 --oversubscribe  python demo.py 0  &
srun --nodes=1 --nodelist=sam-red --ntasks=1 --oversubscribe  python demo.py 1  &
srun --nodes=1 --nodelist=sam-red --ntasks=1 --oversubscribe  python demo.py 2  &

wait

Now forces the first job to allocate only 2 CPUs. But the other are still queued even if i have quad-core CPU with hyperthreading.

A: I had to reboot my server for maintenance.
Not sure what happened but now I can run the jobs in a parallel fashion using:
#!/bin/bash

srun --nodes=1 --nodelist=sam-red --ntasks=1 --oversubscribe  python demo.py 0  &
srun --nodes=1 --nodelist=sam-red --ntasks=1 --oversubscribe  python demo.py 1  &
srun --nodes=1 --nodelist=sam-red --ntasks=1 --oversubscribe  python demo.py 2  &

wait

The key to enforce parallel jobs on same node is the --nodes=1 argument. That alone is sufficient on my system.
for quick reference more examples are available here:
https://slurm.schedmd.com/cpu_management.html#Example6


text:
Q: Displaying data in directive, using ng-repeat I am currently trying to understand Angular directives.
Right now i have made a directive, and i are using this directive in order to show a modal when a button is clicked. The modal to be shown is getting its data via an injection when it is instantiated.
The data to be used is found via an ng-repeat over an array of objects from my controller. I have tried to just plain out show the modal in each loop, and when i do this the data is just as expected. However when i try to open the modal via a button click, it shows the data from the first object regardless of what index in the ng-repeat the button is in.
My directive:
angular.module('myAppRename.directives', []).
directive('myModal', function () {
return {
  restrict: 'AE',
  scope: {
    inv: '='
  },

  template:

      '
' +
      '
' +
      '
' +
      '
Redigering af bilaget : {{inv.title}}
' +
  '<form role="form">' +
      '
' +
      'Title:' +
  '<input placeholder="{{inv.title}}" type="text" class="form-control" id="title">' +
      '
' +
      '
' +
      'Projekt:' +
  '<input placeholder="{{inv.project}}" type="text" class="form-control" id="projekt">' +
      '
' +
      '
' +
      'Ordre:' +
  '<input placeholder="{{inv.order}}" type="text" class="form-control" id="ordre">' +
      '
' +
      '
' +
      'Senders Noteringer:'+
  '<input placeholder="{{inv.notes}}" type="text" class="form-control" id="sendernote">' +
      '
' +
      '
' +
      'Dine Noteringer:' +
      '<input placeholder="{{inv.adminComment}}" type="text" class="form-control" id="dinenoter">' +
      '
' +
      '<button ng-click="editAnnex()>Send Redigering</button>' +
  '</form>'+
  '
'+
  '
'+
  '
'

 };
 }
 );

Using the directive in ng-repeat:

                <my-modal inv="inv"></my-modal>

                    <button class="btn btn-success btn-block"
                            ng-click="acceptAnnex(inv.id,inv.title)">Accepter
                    </button>
                    <button class="btn btn-danger btn-block" ng-click="denyAnnex(inv.id,inv.title)">Slet</button>
                    <button class="btn btn-primary btn-block" ng-click="addComment(inv.id)"> Tilføj kommentar
                    </button>
                    <button type="button" class="btn btn-default btn-block" data-toggle="modal"
                            data-target="#myModal"> Rediger</button>

 Title : {{inv.title}}

Sender : {{inv.sender}}

Projekt : {{inv.project}}

Ordre : {{inv.order}}

Senders Noteringer :

{{inv.notes}}

Din kommentar :

{{inv.adminComment}}

Cant really understand why this might be happening, so any suggestion, or hint in the right direction is greatly appreciated!

A: You're using #myModal as the ID for every single modal on the page.  When you reference a modal by #myModal you're not getting the one you want because ids are supposed to be unique.
You need to generate:
id=myModal1 , id=myModal2 , ... (one unique id for each modal on the page) inside your iterator and then your target should be
#myModal1 (or whatever the appropriate one is.)


text:
Q: Hide or minimise search facet component after making a selection We're building a Reactivesearch solution and have a requirement to hide or minimise a facet (SingleList in this case) after a selection has been made.
I've already tried the below approach using a custom render function where I can inspect the if a value has been selected and apply conditional rendering:
    render: ({
        loading,
        error,
        data,
        handleChange,
        value
    }) => {
        if (value !== "") {
            return (
                {value}
            )
        }
        else {
            return (

                    {
                        data.map(item => (

                                <input
                                    type="radio"
                                    value={item.key}
                                    onChange={handleChange}
                                />

                                    {item.key}
                                    {item.doc_count}

                        ))
                    }

            )
        }
    }

Whilst this works, I wonder if there is a cleaner way, which also avoids the need to have a custom render of the list. Basically, a solution that uses the default render in the case of no facet selection.

A: I think this is the best approach that I think would work. Here are other ways how I may have done:

*

*Using state variable

Create a state variable and update the state whenever the value is selected. You can do this using onValueChange. Whenever this state change you can set the display none for the singlelist.
handleUpdate = (value) => {
  this.setState({
    value,
  })
}

render(){
  const { value } = this.state;

  return (

      <SingleList onValueChange={this.handleUpdate} dataField={} style={value ? { display: 'none' } : { display: 'block'}} />
      {value ? {value} : null}

  );
}

This is the other way you can follow. But the custom render method is the best way to go about this issue.
Hope this helps!


text:
Q: What Does $_session['error'] means in php I have this php code
if (isset($_SESSION['error']))
{
echo "
" . $_SESSION['error'] . "
";
unset($_SESSION['error']);
}

What Does $_SESSION['error'] means
and unset one please explain

A: $_SESSION contains all session variables (user ID of logged in user for example). You can set a session variable like this:
$_SESSION['foo'] = 'bar';
And access it later (after multiple page loads still, that's why it's so useful) using:
$foo = $_SESSION['foo'];
echo $foo; //Displays 'bar'

Your code checks if there is a session variable set, and if so display an error and unset the session variable. So I would guess this is to show a one-time error when something went wrong. Using a session variable means you can execute this code on a different page then where the error happened.

A: $_SESSION['error'] means a an array key of $_SESSION which was generated by you.

A: It looks in the session, which is a temporary storage that is unique to the user and more often than not is mean to last for the time a user stays on a page in a single "visit session", for a variable (actually rather an array key) called error; it then injects whatever that contains (likely an error message) into a piece of HTML, and after that, it deletes the error from the session storage with unset().
Take a look on the documentation for $_SESSION.


text:
Q: Get Data From An Uploaded Excel File Without Saving to File System I have a requirement to allow a user of this ASP.NET web application to upload a specifically formatted Excel spreadsheet, fill arrays with data from the spreadsheet, and bind the arrays to a Oracle stored procedure for validation and insertion into the database.  I must be able to read the data from the Excel spreadsheet without being able to save it to the web server's hard disk.  This is the part I cannot figure out how to do.  Here's a simple code example.
<%--ASP.NET Declarative--%>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Send File" OnClick="Button1_Click" />

// C# Code-Behind
protected void Button1_Click(object sender, EventArgs e) {
    var postedFile = FileUpload1.PostedFile;

    // ... Read file in memory and put in format to send to stored procedure ...

}

Can anyone help me with this?  I appreciate anyone's consideration.
thx,
gabe

A: I found a great lightweight open source API on Codeplex for doing this called ExcelDataReader.
It can transform an input stream of an excel file into a System.Data.DataSet object (probably parsing using BIFF specs).
Here's the link:

http://www.codeplex.com/ExcelDataReader

Here's a code sample:
<%--ASP.NET Declarative--%>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Send File" OnClick="Button1_Click" />
<asp:GridView ID="GridView1" runat="server" />

// C# Code-Behind
protected void Button1_Click(object sender, EventArgs e) {
    // the ExcelDataReader takes a System.IO.Stream object
    var excelReader = new ExcelDataReader(FileUpload1.FileContent);
    FileUpload1.FileContent.Close();

    DataSet wb = excelReader.WorkbookData;
    // get the first worksheet of the workbook
    DataTable dt = excelReader.WorkbookData.Tables[0];

    GridView1.DataSource = dt.AsDataView();
    GridView1.DataBind();
}

A: Use the FileUpload1.FileContent Stream. I guess your Excel library can handle streams directly.

A: The COM libraries of Excel does not support loading file from another source than file.
But there exists a lot of third-party components, which allows you read/write excel files.
Othervise you can see a documentation for th XLS file format at [MS-XLS]: Excel Binary File Format (.xls) Structure Specification.
Or you can use a same way of office files processing like in Sharepoint Server. See Microsoft.Office.Excel.Server.WebServices Namespace.

A: maybe have look on csvreader, it reads csv, xls and xlsx:
http://www.csvreader.com

A: This is something I've been playing with recently.
Check this post: Write an excel workbook to a memory stream .NET
It points to a great library by Carlos Aguilar Mares, which lets you work with Excel workbooks as XML.
ExcelXMLWriter
You dont need Excel installed on the server (which is kinda breaking the MS licensing anyway as you are accessing this over the web).
You can load the Excel workbook as a stream using Workbook.Load(stream)

A: Could you have your users upload a CSV file instead? Dealing with a plain text file would be much easier. I had a similar issue before and I asked the users and they were OK, saved me tons of work.
Good luck.


text:
Q: Installing/Uninstalling via .run this question is more of the understanding of .run installation, when you download a file and use .run to install it, does it actually interact with Linux's package manager, or does it work just like a portable program, where once you delete the installation path, it's gone?
For example, if I download Qt Creator which has a .run file, and I install it in Documents/Qt, does that mean it's installed in that path and once I delete that folder it's gone from my system?

A: .run files are simply executable files that contain a program's installation instructions.
Package managers can't track where the program's files are installed, so it's not really possible to uninstall the program.
The only way you can uninstall a program that uses a .run installer is if it provides an uninstaller. This is why programs that use .run installers are not recommended...

A: It can interact with the package manager. It can do anything. They're just scripts. What they actually do depends on the people who write them. It is very possible that they build themselves a fake package to aid removal.
I have had some installers do this. I honestly can't remember which they were but they built themselves little meta-packages to aid removal.
These were system-installed though. I think it's very unlikely that a home-installed application is going to request to elevate to root permissions to do the same though.


text:
Q: prove that $n^{13}-n\equiv 0\mod(2730)$ by generalizing Fermat's little theorem. When I saw this problem, it came to me that Fermat's little theorem that says:$$a^p\equiv a\mod(p)$$can also been said in general:
$$a^{1+(p-1)k}\equiv a\mod(p)$$
Ad since $13$ can be written as:$$1+(2-1)12=13\\1+(3-1)6=13\\1+(5-1)3=13\\1+(7-1)2=13\\1+(13-1)1=13$$Therefor $$n^{13}\equiv n\mod(2\cdot3\cdot5\cdot7\cdot13=2730)$$
But I didn't find a way to prove this generalization $a^{1+(p-1)k}\equiv a\mod(p)$. Maybe someone can help me prove it?
Thanks.

A: If $a \equiv 0\mod p$: Done.
If $a$ is not divisible by $p$, Fermat's Little Theorem can be written as:
$a^{p-1} \equiv 1 \mod p$.
And so:
$$a^{1+(p-1)k} = a.(a^{p-1})^k \equiv a(1)^k \equiv a\mod p. $$


text:
Q: Shared preferences storing a string return only a part of it So, I've been saving some coordinates into a SharedPreferences, but when I try to get them back, the latitude returns fine like :44.374736436, but the longitude returns only 26, even though when I save it, I store it like: 26.24343343.
Where I save it:
 PunctSalvat_SP punct = new PunctSalvat_SP(
                            String.valueOf(latitudine_start),
                            String.valueOf(longitudine_start),
                            id_alerta
                    );
 SharedPrefManager.getInstance(getApplicationContext()).SalvarePunct(punct);

SharedPreferences.SalvarePunct():
public void SalvarePunct(PunctSalvat_SP punctSalvat) {
    SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_PUNCT, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(KEY_latitudine, punctSalvat.getLatitudine());
    editor.putString(KEY_longitudine, punctSalvat.getLongitudine());
    editor.putString(KEY_id_marker, punctSalvat.getid());
    editor.apply();
}

PunctSalvat_SP class:
public class PunctSalvat_SP {
private String latitudine, longitudine, id;

public PunctSalvat_SP(String latitudine, String longitudine, String id) {
    this.latitudine = latitudine;
    this.longitudine = longitudine;
    this.id = id;
}

public String getLatitudine() {
    return latitudine;
}
public String getLongitudine() {
    return longitudine;
}
public String getid() {
    return id;
}

}
Where I try to get it back:
 if (SharedPrefManager.getInstance(this).ExistaPunct()) {
            ArrayList<String> punct_ramas_in_memorie = new ArrayList<String>();
            PunctSalvat_SP punct = SharedPrefManager.getInstance(this).getPunct();
            punct_ramas_in_memorie.add(punct.getLatitudine());
            punct_ramas_in_memorie.add(punct.getLongitudine());
            ruta_pentru_o_problema_id.add(punct.getid());
            CrearePunctDinRuta(punct_ramas_in_memorie);
        }

SharedPreferences.ExistaPunct() and SharedPreferences.getPunct():
public boolean ExistaPunct() {
    SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_PUNCT, Context.MODE_PRIVATE);
    return (sharedPreferences.getString(KEY_latitudine, null) != null && sharedPreferences.getString(KEY_longitudine, null) != null);
}
public PunctSalvat_SP getPunct() {
    SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_PUNCT, Context.MODE_PRIVATE);
    return new PunctSalvat_SP(
            sharedPreferences.getString(KEY_latitudine, null),
            sharedPreferences.getString(KEY_longitudine, null),
            sharedPreferences.getString(KEY_id_marker, null)
    );
}

Debuggind the code, I observed the following:
When I save it, the punct has the right value (Ex: punct = (44.3432432423, 26.1323232, 26)), but when I try to get it back, the arraylist punct_ramas_in_memorie returns 2 elements, the 1st being the right latitude, but the 2nd one returns only 26, instead of 26.242423432.

A: Verify preference key values for KEY_longitudine and KEY_id_marker, if they are same.
If both key are same the value of id will overridden on longitude. and while retrieving value of longitude you will get value of id(what was written lastly on that key).


text:
Q: How do I call a function inside another controller file in PHP? I have one function I need to call from another file with Codeigniter and I'm not sure how to do this.
The one file is in controllers/Jobassignment.php, which contains a function called createassignments() that I need to call from controllers/Reporting.php. I am pretty new at Codeigniter, so how would I call the createassignments function from Reporting.php?
I tried
$this->load->library('controllers/jobassignment');
$this->jobassignment->createassignments();

But this isn't working.
It has been called in a form tag:
<form action="<?php echo base_url( 'jobassignment/createassignments' ); ?>

but I can't do that in the middle of a function.
They are both controller files. Any help would be appreciated.

A: It has nothing to do with Codeigniter. If the Jobassignment.php is a PHP class you can make an instance of it and then call that function:
user namespace/Jobassignment

$jobassignment = new Jobassignment();

$jobassignment->createassignments();

but if this method you create is going to call in other classes you must make a class under Helpers directory and then call the method the way that I explained.
Don't make instance of request class. you must make a helper class to handel this.

A: If the goal is to make the action of the form a method in a different controller then your code
<form action="<?php echo base_url( 'jobassignment/createassignments' ); ?>

is perfectly fine. You just have to understand that you are doing a redirect and code execution in the current controller is done. Understand that a <form action...> is always a redirect where the input element values of the form are sent to the server.
Because it is a redirect there is no reason to call $this->load->library('controllers/jobassignment');


text:
Q: Websocket is not closed upon missing pong when connection is interrupted Websockets should be closed with WebSocketStatus.GOING_AWAY if no pong message is received within pingInterval. Why doesn't this work when connectivity is lost, e.g. with an un-plugged cable? Is this expected behaviour? And if so, what's the point of the ping messages? (I know of the TCP timeout stuff.)
Reproduce:

*

*With a low pingInterval (e.g. 1ms), websocket is correctly closed with closeCode==1001

*With a high pingInterval (e.g. 1000ms), kill connectivity after a while, websocket will not close (closeCode is null)

Here is the code to reproduce:
import 'dart:async';

import 'package:web_socket_channel/io.dart';

void main() {
  final channel = IOWebSocketChannel.connect("ws://echo.websocket.org/",
      pingInterval: Duration(milliseconds: 1000));
  channel.stream.listen(print, onError: print, onDone: () => print('done'));
  Timer.periodic(Duration(seconds: 3), (t) {
    int time = DateTime.now().millisecondsSinceEpoch;
    channel.sink.add("message: hi, $time");
  });
  Timer.periodic(Duration(seconds: 10), (t) {
    print("closeCode: ${channel.closeCode}");
  });
}

And the console output:
message: hi, 1562579165221
message: hi, 1562579168221
message: hi, 1562579171221
closeCode: null
message: hi, 1562579174221
message: hi, 1562579177221
message: hi, 1562579180221
closeCode: null    <---- cable pulled
closeCode: null
closeCode: null


text:
Q: MySQL returning -0001 as year I'm trying to store a date that is converted and displayed as one format (d M, Y) to the user and stored in the default format in the mysql table (yyyy-mm-dd).
I'm storing the date using the following function on each date field:
private function formatDate($date)
    {
        if(!empty($date))
        {
            $changeFormat = DateTime::createFromFormat('d M, yy', $date);
            $newDate = $changeFormat->format('Y-m-d');
        } else {
            return "";
        }
        return $newDate;
    }

and reverting it back to d M, yy with the following function:
private function formatDateBack($date)
    {
        if(!empty($date))
        {
            $changedFormat = DateTime::createFromFormat('Y-m-d', $date);
            $newDate = $changedFormat->format('d M, Y');
        } else {
            return "";
        }
        return $newDate;
    }

When I use the above function to retrieve the date and show it to the user, and the date field is empty, I get the following date back:
30 Nov, -0001

I have a hunch that this is because of the two different year formats given to the format() function above in my two private functions, the first being 'd M, yy' and the second being 'd M, Y'. However, this is the way that I can properly change the date formats, because if I change the format to 'd M, yy' in formatDateBack(), I will get a date like '4 Jan, 1414'.
I don't understand why I'm getting the date 30 Nov, -0001 back, even when the date shown in the database table is 0000-00-00. I would even appreciate it if I got that back instead!
If someone can help me I would love to find a solution to this.
EDIT: my date fields data type is date

A: public function formatDateBack($dtm)
{
    if(is_null($dtm) || $dtm == '0000-00-00') return 'whatEverYouLike';
    $datum = new DateTime($dtm);
    return $datum->format('d.m.Y');
}

A: You are getting this result, probably, because of the time zone. If the date is null, it's being translated to 0, which is 1 of Jan of year 0, in GMT. In a different time zone, that time changes slightly.
I can only think that you're getting 30 of Nov instead of 31 Dec because this conversions, while converting the fields, lead to some problems when the month indexes change from 0-based to 1-based.


text:
Q: Mac android studio Show only grade building image of android studio
android studio showing only grade building from a long time, I am unable to create the project in android studio 2.3.3 on my Mac

A: I too had the same problem, First check your internet connectivity because gradle needs Internet while building, Second if your internet connection is working well then try this - goto File-> Invalidate and restart select first option from a dialog "Invalidate and restart", this option will restart your android studio and clear all caches.


text:
Q: Login form prepared statements not functioning I'm making a login form with prepared statements, I already have a register form where that data is in a database. Now my login form is not returning "Hello, you are logged in". I double checked all the variables matching my in my db and code, local host is correct, html is fine. Thanks
<?php
// Include config file
require_once 'config.php';
// Define variables and initialize with empty values
$Email = $Password = "";
$Email_err = $Password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){

    // Check if Email is empty
    if(empty(trim($_POST["Email"]))){
        $Email_err = 'Please enter Email.';
    } else{
        $Email = trim($_POST["Email"]);
    }

    // Check if Password is empty
    if(empty(trim($_POST['Password']))){
        $Password_err = 'Please enter your Password.';
    } else{
        $Password = trim($_POST['Password']);
    }

    // Validate credentials
    if(empty($Email_err) && empty($Password_err)){
        // Prepare a select statement
        $sql = "SELECT Email, Password FROM people WHERE Email = ?";

        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters

            $param_Email = $Email;
            // Set parameters
            mysqli_stmt_bind_param($stmt, "s", $param_Email);

            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                // Store result
                mysqli_stmt_store_result($stmt);

                // Check if Email exists, if yes then verify Password
                if(mysqli_stmt_num_rows($stmt) == 1){
                    // Bind result variables
                    mysqli_stmt_bind_result($stmt, $Email, $hashed_Password);
                    if(mysqli_stmt_fetch($stmt)){
                        if(Password_verify($Password, $hashed_Password)){
                            /* Password is correct, so start a new session and
                            save the Email to the session */
                            session_start();
                            $_SESSION['Email'] = $Email;
                            echo "Hello! You are signed in!";
                        } else{
                            // Display an error message if Password is not valid
                            $Password_err = 'The Password you entered was not valid.';
                        }
                    }
                } else{
                    // Display an error message if Email doesn't exist
                    $Email_err = 'No account found with that Email.';
                }
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }
        }
        // Close statement
        mysqli_stmt_close($stmt);
    }
    // Close connection
    mysqli_close($link);
}
?>


text:
Q: Automatically turn on VPN on computer unlock Ubuntu 18.04 When I wake the laptop from the sleep I need to get the VPN state as I left it (turned on). Can't find the setting of autoconnect in VPN settings... Need some easy way to ask the system to autoconnect the VPN when the internet is available.
Edit based on comments:
Ubuntu 18.04 has no option to Always connect to VPN when using using this connection.

A: An addition to @dobey answer.
I found that the icon on the password setting on the VPN connfig window
is actually clickable. It allows other system users to use vpn password,
which is required to automatically connect to vpn after suspend.

A: If you go into your WiFi connection settings for the AP you want to connect to the VPN on, there is an Always connect to VPN when using this connection: option, which you can enable, and select the VPN which you wish to automatically connect to.
Then when you connect to this connection (or when it reconnects on wake from suspend), the system will also attempt to connect to the VPN upon successfully reconnecting to the designated WiFi AP.
It seems the changes in newer GNOME have removed this option from the main UI, so you need to run nm-connection-editor to edit the connection, which should make the option available again.

A: It's not shown in the GUI, but you can still type
nm-connection-editor
in a terminal and select 'always connect to vpn...' under settings > general tab.

A: The "automatically connect to this VPN" checkbox has moved.  Ubuntu 18.04.  Run 'nm-connection-editor' and select the wifi network that you usually connect to.  Click the gear, go to General tab.  It's right there at the bottom - click the checkbox, then click the dropdown below and select the VPN you want to automatically connect to.

A: When OpenVPN is already installed on your computer and have the configurations for OpenVPN, then follow this steps:

*

*Unpack the configuration-zip: unzip openvpn.zip

*Move to the OpenVPN directory and rename it to "openvpn.conf.": sudo cp ~/Downloads/OpenVPN/'Northeast US.ovpn' /etc/openvpn/openvpn.conf

*To login automatically every time you connect do this: Open "/etc/openvpn/openvpn.conf" with sudo, then search for the line auth-user-pass and add auth.txt. ----> How does it looks like: auth-user-pass auth.txt! Crate the file in the following directory "/etc/openvpn"and type in there your username and password. More about that here.

*Make sure OpenVPN  starts up every time you turn-on your computer: sudo
systemctl enable openvpn

*Restart the computer and test your connection with services like whoer.net

A: for those who are looking for a command-line solution, here you go:
first of all, you can list the existing VPN connections you created under this path:
sudo \ls -l /etc/NetworkManager/system-connections/

after finding which VPN connection you want auto-connect, edit the corresponding file (my-VPN in my case)
sudo \vi /etc/NetworkManager/system-connections/my-VPN

... and change the autoconnect=true, save and exit;
note: Omit sudo from the command if you are under root user.

use the [sudo] nmcli connection edit for interactive command-line connection editor.

A: None of the solutions above worked for me.
I did some investigation on @αғsнιη solution with autoconnect and found out that you can use secondaries instead. See here https://manpages.debian.org/testing/network-manager/nm-settings.5.en.html. Also this page says that you can't use autoconnect with VPN profiles.
What I did:
List all existing connections:
sudo \ls -l /etc/NetworkManager/system-connections/

Open a file of the corresponding VPN connection (my-VPN in my case):
sudo gedit /etc/NetworkManager/system-connections/my-VPN

Then copy uuid. It should look like this 5a9bde6f-54ge-4h41-8754-f1a2977fa564.
Open your Wi-fi connection file:
sudo gedit /etc/NetworkManager/system-connections/My-Wi-Fi

And add secondaries property with copied uuid.
It should look like this:
[connection]
id=My-Wi-Fi
uuid=1ab56231-9401-48c7-82de-a9ffghtyeac4
type=wifi
interface-name=wlo1
permissions=
secondaries=5a9bde6f-54ge-4h41-8754-f1a2977fa564;
timestamp=1649182910

[wifi]
...

After that restart NetworkManager or your computer:
systemctl restart NetworkManager


text:
Q: css - @media does not work with firefox and IE I Have this simple media query to check resolution of browser and accordingly display or hide the image... But it works only on Chrome and does not work on firefox and IE. any idea whats wrong with my code? or any suggestions what can I do?
@media screen and (max-width: 1030px) {

#img{
display:none;
}
}

@media screen and (min-width: 1031px)
{

#img{
display:block;
}
}

Here is my HTML:

A: Without seeing your html I will assume that you are attempting to hide an image with and id of image? If so I would do the following.
Change the id of img to be a class, for example we will use .image-class this will mean the style can be re-used on other images on the page as IDs have to be unique.
So your html should look similar to this:

And then for your CSS:
/* Mobile first strategy (no media query required) - images will not display when under 1030px)*/
.image-class {
  display: none;
}

/* Images will display above 1030px */
@media screen and (min-width: 1030px) {
  .image-class {
    display: block;
  }
}

See this fiddle

A: try display:inline-block;
@media screen and (max-width: 1030px) {

#img{
display:none;
}
}

@media screen and (min-width: 1031px)
{

#img{
display:inline-block;
}


text:
Q: Get operations in domain driven design I have an an entity A which has a relation to entity B and C.
Entity B and C can only be created when I create entity A in a transaction.
Thus I only have an A-Repository.cs
When I do a read/get operation on entity B in the context of A or with C outside the context of A.
Where do I put those get operations?

A: On A, assuming A is the root entity of your aggregate, assuming you're applying the tactical patterns.

A: Your get operations for B and C belong in A. So, in A, you are looking at code like public B b{get;} and public C c{get;}.

A: According to the definition of aggregate, you need to retrieve aggregate from repository (A in your case) and then traverse the object graph to get local entities(B and C in your case).
A a = aRepository.findBy(id);
B b = a.getB();
C c = a.getC();

Some infrastructure issues have to be addressed. You may need an orm framework supporting lazy-loading if your domain models are also your persistent models and your store B and C in seperate tables from that of A.


text:
Q: CLR SQL Server UDF Question I am trying to create a CLR UDF that takes in a string value seperated like "Mike|John|Smith". In the UDF I parse out the values and return them in a DataTable. The C# code builds fine and I can create the assembly in SQL pointing to the DLL without a problem.
Problem comes in when I am trying, according to this source, to tell SQL Server how to match up a Transact SQL request with a CLR function. http://www.setfocus.com/technicalarticles/clrfunctionforsqlserver_2.aspx
or if I even have to do that? Basically I want to take in a string, parse out the seperated values and put them in a DB Table with 3 different columns, FN, MN, LN. using a CLR UDF.

A: You need to have a SQL stored procedure or function that calls the Assembly.  The parameters to the SQL stored procedure and the .NET function need to match.  So for example, if your .NET assembly has the following function:
[SqlProcedure]
public static void ProcessData(string myString_)
{
}

your SQL Stored Procedure or Function would have to look like the following:
CREATE PROCEDURE dbo.ProcessMyData (@InputText AS NVARCHAR(MAX))
AS EXTERNAL NAME SqlAssemblyName.ClassName.ProcessData
GO


text:
Q: XMLHttpRequest not sending JSON just an empty string xhttp.send(data) is sending an empty string instead of the data I look at other examples and this should work. I am looking over this over and over and can't figure out what is wrong. If anyone could help me out I would greatly appreciate it.

        <title>Tuition Reimbursement Management System </title>

User Name

      <input type="text"id="user">

Password

      <input type="password"id="pass">
      <button onclick="login()">Login</button>

 ```


text:
Q: remy inliner command line tool returns path.existsSync is now called `fs.existsSync` I'm trying to use inliner command line tool locally to combine some files. But I get the following error message in the console.
path.existsSync is now called `fs.existsSync`

So i went into /usr/local/lib/node_modules/inliner/bin/inliner and changed line 65 from:
if (path.existsSync(url))

to
if (fs.existsSync(url))

but I get still the same error message. Can anybody give me a hint what is wrong and how I can fix this?
There is already a question here but that didn't fix my problem. Or am I editing the wrong file?
Cheers
:fab

A: I got inliner working by using the -i command
#-i, --images    don't encode images - keeps files size small, but more requests
inliner -i http://fabiantheblind.info/coding.html > test2.html


text:
Q: Order of Dictionary.Keys.ToArray() vs Dictionary.Values.ToArray() I have a question regarding implementation details of Dictionary
Assume the following code:
private IDictionary<Int64, Int32> _data = new Dictionary<Int64, Int32>();

private void Foo()
{
    Int64[] keys = _data.Keys.ToArray<Int64>();
    Int32[] vals = _data.Values.ToArray<Int32>();

    // Further code goes here
}

May I assume at this point, that
_dict[keys[i]] == vals[i]

for each i in [0 .. _data.Length-1], or might the order of both arrays be unrelated?

A: Why not just do this?
private void Foo()
{
    Int64[] keys = _data.Keys.ToArray<Int64>();
    Int32[] vals = _data.Keys.Select(k => _data[k]).ToArray<Int32>();

    // Further code goes here
}

It's still O(n) time and it won't break if .NET changes in the future.


text:
Q: Partial Differentiation using chain rule I am trying to express $\frac{\partial^2u}{\partial y^2}$ and $\frac{\partial^2u}{\partial x\partial y}$ of the function $u=f(x,y,g(x,y))$ with partial derivative notation of $f$ and $g$.
However I am having a hard time doing so because I am a bit confused with the notation.
I know that $\frac{\partial u}{\partial y}=\frac{\partial f}{\partial y}+ \frac{\partial f}{\partial g}\frac{\partial g}{\partial y}$. But the problem is that I am not sure how to express $\frac{\partial^2u}{\partial y^2}$. If I differentiate the $\frac{\partial u}{\partial y}$ by $y$, I am thinking I will get $\frac{\partial^2 u}{\partial y^2}=\frac{\partial^2 f}{\partial y^2}+ ...$ , but I am not quite sure how the second term of the right hand side ($\frac{\partial f}{\partial g}\frac{\partial g}{\partial y}$) will look like. Similarly, I have trouble in expressing $\frac{\partial^2u}{\partial x\partial y}$ using partial differentiation notation of $f$ and $g$.
How should it be done?
Thanks.

A: Edit: As pointed out by Ted Shifrin, it's a bit misleading to write $\frac{\partial f}{\partial g}$ when in reality I mean $\frac{\partial f}{\partial z}$ because $f$ is a function of three variables: $x,y,z$.  I just so happens that everywhere it's relevant we evaluate $f$ at $(x,y,g(x,y))$.
It becomes clearer when you add back in the arguments.  You already have
$$\frac{\partial u}{\partial y}=\frac{\partial f}{\partial y}(x,y,g(x,y))+ \frac{\partial f}{\partial z}(x,y,g(x,y))\frac{\partial z}{\partial y}(x,y).$$  So, to find $\frac{\partial^{2} u}{\partial y^{2}}$, we compute the derivatives the same way again.
\begin{align}
\frac{\partial^{2} u}{\partial y^{2}} &=\frac{\partial}{\partial y}\frac{\partial f}{\partial y}(x,y,g(x,y))+ \frac{\partial}{\partial y}\left(\frac{\partial f}{\partial z}(x,y,g(x,y))\frac{\partial g}{\partial y}(x,y)\right)\\
&=\frac{\partial^{2} f}{\partial y^{2}}(x,y,g(x,y)) + \frac{\partial^{2}f}{\partial z\partial y}(x,y,g(x,y))\frac{\partial g}{\partial y}(x,y)\\ &\quad + \left(\frac{\partial^{2}f}{\partial y\partial z}(x,y,g(x,y)) + \frac{\partial^{2}f}{\partial z^{2}}(x,y,g(x,y))\frac{\partial g}{\partial y}(x,y)\right)\frac{\partial g}{\partial y}(x,y)\\ &\quad+ \frac{\partial f}{\partial z}(x,y,g(x,y))\frac{\partial^{2} g}{\partial y^{2}}(x,y)
\end{align}
Suppressing the arguments again, we have
$$\frac{\partial^{2} u}{\partial y^{2}} = \frac{\partial^{2} f}{\partial y^{2}} + \frac{\partial^{2}f}{\partial z\partial y}\frac{\partial g}{\partial y} + \left(\frac{\partial^{2}f}{\partial y\partial z} + \frac{\partial^{2}f}{\partial z^{2}}\frac{\partial g}{\partial y}\right)\frac{\partial g}{\partial y}+ \frac{\partial f}{\partial z}\frac{\partial^{2} g}{\partial y^{2}} $$
which if you know that the second order partial derivatives are continuous becomes
$$\frac{\partial^{2} u}{\partial y^{2}} = \frac{\partial^{2} f}{\partial y^{2}} + 2\frac{\partial^{2}f}{\partial y\partial z}\frac{\partial g}{\partial y} + \frac{\partial^{2}f}{\partial z^{2}}\left(\frac{\partial g}{\partial y}\right)^{2}+ \frac{\partial f}{\partial z}\frac{\partial^{2} g}{\partial y^{2}}.$$  You can compute the other second order partial derivative in a similar manner.  Suppressing the arguments this time from the start:
\begin{align}
\frac{\partial^2u}{\partial x\partial y} &= \frac{\partial}{\partial x}\frac{\partial f}{\partial y}+ \frac{\partial}{\partial x}\left(\frac{\partial f}{\partial z}\frac{\partial g}{\partial y}\right)\\
&=\frac{\partial^{2}f}{\partial x\partial y} + \frac{\partial^{2}f}{\partial z\partial y}\frac{\partial g}{\partial x} + \left(\frac{\partial^{2}f}{\partial x\partial z} + \frac{\partial^{2}f}{\partial z^{2}}\frac{\partial g}{\partial x}\right)\frac{\partial g}{\partial y} + \frac{\partial f}{\partial z}\frac{\partial^{2}g}{\partial x\partial y}.
\end{align}

A: First lets start by $\frac{\partial u}{\partial y}$.
You already evaluated this one right:
\begin{equation}
\left( \frac{\partial u}{\partial y} \right)_x = \left( \frac{\partial f(x,y,g)}{\partial y} \right)_x = \left( \frac{\partial f}{\partial y} \right)_{g,x} + \left( \frac{\partial f}{\partial g} \right)_{x,y} \left(\frac{\partial g}{\partial y}\right)_x
\end{equation}
For the next one, we want:
\begin{equation}
\left( \frac{\partial }{\partial y} \left( \frac{\partial u}{\partial y} \right)_x \right)_{x}
\end{equation}
We can evaluate this using the chain rule:
\begin{equation}
\left( \frac{\partial }{\partial y} \left( \frac{\partial u}{\partial y} \right) \right)_{x} =  \left(\frac{\partial}{\partial y} \left( \frac{\partial f}{\partial y} \right)_{g,x} \right)_x + \left( \frac{\partial}{\partial y} \left( \frac{\partial f}{\partial g} \right)_{x,y}  \right)_x  \left(\frac{\partial g}{\partial y}\right)_x + \left( \frac{\partial}{\partial y} \left(\frac{\partial g(x,y)}{\partial y}\right)_x \right)_x \left( \frac{\partial f}{\partial g} \right)_{x,y}
\end{equation}
Lets evaluate term by term:
Note that the variables we are keeping constant are also an indicative that the final derivative will depend on them, so for the terms that contains $f$, the first and the second, you can replace the partial derivative with this operator:
\begin{equation}
\left(\frac{\partial}{\partial y} \right)_x = \left( \frac{\partial }{\partial y} \right)_{x,g} + \left( \frac{\partial }{\partial g} \right)_{x,y} \left( \frac{\partial g}{\partial y} \right)_{x}
\end{equation}
And for the last derivative you simply get:
\begin{equation}
\left( \frac{\partial}{\partial y} \left(\frac{\partial g(x,y)}{\partial y}\right)_x \right)_x \left( \frac{\partial f}{\partial g} \right)_{x,y} = \frac{\partial^2 g}{\partial y ^2} \left( \frac{\partial f}{\partial g} \right)_{x,y}
\end{equation}
If do this calculation you will get:
\begin{equation}
2 \frac{\partial }{\partial g} \left( \frac{\partial f}{\partial y} \right) \frac{\partial g}{\partial y}+ \frac{\partial^2 f}{\partial y^2} + \left(\frac{\partial g}{\partial y}\right)^2 \frac{\partial^2 f}{\partial g^2} +\frac{\partial f}{\partial g} \frac{\partial^2 g}{\partial y^2}
\end{equation}
Where in this last equation I have not stated the variables kept constant, but you may identify them easily.
With this headstart, I think you can easily do the other derivative, which I won't put here cause it is too much to type in latex.
Any question just ask!