text:
Q: echoing simple xml objects I am able to parse and show the first object in the xml file but am not able to echo the second object.
this is the results of my get
noaa\weather\response\CurrentWeather Object
(
    [xml:protected] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [version] => 1.2
                )

            [request_index] => 664770430
            [data_source] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [name] => metars
                        )

                )

            [request] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [type] => retrieve
                        )

                )

            [errors] => SimpleXMLElement Object
                (
                )

            [warnings] => SimpleXMLElement Object
                (
                )

            [time_taken_ms] => 4
            [data] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [num_results] => 4
                        )

                    [METAR] => Array
                        (
                            [0] => SimpleXMLElement Object
                                (
                                    [raw_text] => EGGW 160750Z 21006KT 3400 BR SCT001 BKN003 05/05 Q1029
                                    [station_id] => EGGW
                                    [observation_time] => 2017-02-16T07:50:00Z
                                    [latitude] => 51.87
                                    [longitude] => -0.37
                                    [temp_c] => 5.0
                                    [dewpoint_c] => 5.0
                                    [wind_dir_degrees] => 210
                                    [wind_speed_kt] => 6
                                    [visibility_statute_mi] => 2.11
                                    [altim_in_hg] => 30.383858
                                    [wx_string] => BR
                                    [sky_condition] => Array
                                        (
                                            [0] => SimpleXMLElement Object
                                                (
                                                    [@attributes] => Array
                                                        (
                                                            [sky_cover] => SCT
                                                            [cloud_base_ft_agl] => 100
                                                        )

                                                )

                                            [1] => SimpleXMLElement Object
                                                (
                                                    [@attributes] => Array
                                                        (
                                                            [sky_cover] => BKN
                                                            [cloud_base_ft_agl] => 300
                                                        )

                                                )

                                        )

                                    [flight_category] => LIFR
                                    [metar_type] => METAR
                                    [elevation_m] => 160.0
                                )

                            [1] => SimpleXMLElement Object
                                (
                                    [raw_text] => EGNV 160750Z 21015KT 9999 SCT040 07/04 Q1023
                                    [station_id] => EGNV
                                    [observation_time] => 2017-02-16T07:50:00Z
                                    [latitude] => 54.52
                                    [longitude] => -1.42
                                    [temp_c] => 7.0
                                    [dewpoint_c] => 4.0
                                    [wind_dir_degrees] => 210
                                    [wind_speed_kt] => 15
                                    [visibility_statute_mi] => 6.21
                                    [altim_in_hg] => 30.206694
                                    [sky_condition] => SimpleXMLElement Object
                                        (
                                            [@attributes] => Array
                                                (
                                                    [sky_cover] => SCT
                                                    [cloud_base_ft_agl] => 4000
                                                )

                                        )

                                    [flight_category] => VFR
                                    [metar_type] => METAR
                                    [elevation_m] => 37.0
                                )

                     )

        )

    [cachedValues:protected] => Array
        (
            [location] =>
            [observation_time] => 2017-02-16T07:50:00Z
            [temp_f] =>
            [dewpoint_f] =>
            [relative_humidity] =>
            [wind_string] =>
            [weather] =>
            [raw_text] => EGGW 160750Z 21006KT 3400 BR SCT001 BKN003 05/05 Q1029
            [station_id] => EGGW
            [flight_category] => LIFR
            [latitude] => 51.87
            [longitude] => -0.37
            [temp_c] => 5.0
            [dewpoint_c] => 5.0
            [wind_dir_degrees] => 210
            [wind_speed_kt] => 6
            [visibility_statute_mi] => 2.11
            [altim_in_hg] => 30.383858
            [wx_string] => BR
            [sky_condition] =>
            [elevation_m] => 160.0
        )

    [cachedValues2] => Array
        (
            [location] =>
            [observation_time] => 2017-02-16T07:50:00Z
            [temp_f] =>
            [dewpoint_f] =>
            [relative_humidity] =>
            [wind_string] =>
            [weather] =>
            [raw_text] => EGNV 160750Z 21015KT 9999 SCT040 07/04 Q1023
            [station_id] => EGNV
            [flight_category] => VFR
            [latitude] => 54.52
            [longitude] => -1.42
            [temp_c] => 7.0
            [dewpoint_c] => 4.0
            [wind_dir_degrees] => 210
            [wind_speed_kt] => 15
            [visibility_statute_mi] => 6.21
            [altim_in_hg] => 30.206694
            [wx_string] => BR
            [sky_condition] =>
            [elevation_m] => 37.0
        )

)

Here is the a partial example of the code I am using to echo the first object. which is working fine.
echo "Metar: " . $current->getRawF(). "\n";
echo "
";
echo "
";
echo "Station ID: " . $current->getStationId() . '  (' . $current->getCat() .")" ;

No matter what I have tried I am in able to echo any the second object (egnv). I was hoping for some help pointing me in the right direction.
Thanks for the help
Steve


text:
Q: A little question about tag questions Yesterday, when I talked with my friends in English, I found a slightly odd sentence in the conversation.

Me: What is your idea about what restaurant we should go for dinner in this shopping street?
Tom:I think McDonald's is the best choice, isn't it?

In effect, I have never seen the subject of the independent sentence not as the same as the pronoun in tag questions, but I'm not sure whether his tag question is wrong. After all, his usage seems to have some logic…
So, can I use the sentence like his?

A: This is perfectly normal.
A tag question in effect asks whether the hearer agrees with the proposition it's attached to. In this context it would be very odd to ask whether you agree with the proposition in the matrix clause, "I think X" (surely I am the only person entitled to an opinion about what I think!), but it is entirely reasonable to ask whether you agree with the proposition "X".
Paraphrase:

I think McDonald's is the best choice—do you agree that McDonald's is the best choice?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I find the Limit of this sequence? $$\frac {2}{3}, \frac {14}{18}, \frac {43}{54},\frac {259}{324},\frac {1555}{1944},\frac {9331}{11664} \frac {55987}{69984}...$$
The pattern that I got for the numerators (not too clean) was, the first term, multiply by 7, then the next term multiply by 3 and add 1. Then from there it's all multiply by 6 and 1.
The denominators are clearly just multiplying by 6.
But how can I find the limit sequence? Or I guess more simply put, how would you generate the recursive formula for this?

A: Since you are nesting $\dfrac{1+\dfrac{1+\cdots}{3}}{2}$, if we let $x_n$ be the $n$-th term in your series, then we have \begin{align}x_{n+1} &= \dfrac{1+\dfrac{1+x_n}{3}}{2} \\ x_{n+1} &= \dfrac{1}{6}x_n+\dfrac{2}{3}\end{align}
This is a non-homogeneous linear recurrence relation. We also have the initial condition $x_1 = \dfrac{2}{3}$.
I'm not sure if you are familiar with methods for solving linear recurrence relations, but even if you aren't, you can show that $$x_n = \dfrac{4}{5}(1-6^{-n})$$ by using induction.

A: The pattern is:
$$\frac {2}{3},\frac {2*6+2}{3*6}=\frac {14}{18},\frac {14*6+2}{18*6}= \frac {86}{108},\frac {86*6+2}{108*6}=\frac {518}{648},\frac {518*6+2}{648*6}=\frac {3110}{3888},...$$
Let's work better each term:
$$\frac {2}{3}$$
$$\frac {2*6+2}{3*6}=\frac {2}{3}+\frac {2}{3*6}=\frac {14}{18}$$
$$\frac {14*6+2}{18*6}=\frac {2}{3}+\frac {2*6+2}{3*6*6}=\frac {86}{108}$$
$$......$$
Now, applying geometric progression, the sequence tends to:
$$\frac {2}{3}+\frac {2*6*6+2*6+2...}{3*6*6*6...}= \frac {2}{3}+\frac{2}{3} * \frac{1}{5}=0.8$$


text:
Q: Database / Laravel boa tarde, estou tentando criar um produto em relação à sua etiqueta identificada, por exemplo, quando envio o form uma linha nula é criada no banco de dados.
public function store(Produto $produto, Request $request)
{

    $data = $this->requestValidate();

    $produto->user_id = Auth::user()->id;
    $produto->save();
    $produto->tags()->attach(request('tags'));

    if ($request->hasFile('image') && $request->image->isValid()) {
        $name = uniqid(date('HisYmd'));
        $extension = $request->file('image')->getClientOriginalExtension();
        $nameFile = "{$name}.{$extension}";
        $imagePath = $request->image->storeAs('img_produtos', $nameFile, 'img_produtos');
        $data['image'] = $imagePath;
    }

    Produto::create($data);
    return redirect(route('user.profile'));
}

aqui está como ele aparece no banco de dados

Alguém pode me ajudar? Sou iniciante no Laravel.

A: O teu primeiro código
$produto->user_id = Auth::user()->id;
$produto->save();

é o responsavel, ele vai criar um registo na base de dados e inserir só o id do usúario.


text:
Q: Transition probability of markov chain I want to find transition probabilities of a Markov chain. However, one step probability of state transition is not a fixed but is dependent on the number of users with specific state.
Below is detail:
There are total N users. Each user have a state in a unit time. The state diagram is attached  (state diagram.jpeg).

However the state transition probability PS  is not a fixed value, but dependent on the number of users with state Ot and Bt.
Therefore, I cannot write one step transition probability as
$$
P =
\begin{pmatrix} 1-Po& 0&Po& 0\\
    0& 1-Pr& 0& Pr\\
    Ps& 1-Ps& 0& 0\\
    Ps& 1-Ps& 0& 0
\end{pmatrix}, $$where $O, B, Ot, Bt$ states are corresponded to $1, 2, 3, 4$.
Is there any idea to find a transition probability matrix?
Thanks in advance.


text:
Q: Initialize UITableView with dynamic data I am trying to display a list of friends in a UITableView.
I am loading the friends:
- (void)viewDidLoad
{
  [super viewDidLoad];
  [self apiGraphFriends];
}

Then I am setting my results in:
- (void)request:(FBRequest *)request didLoad:(id)result
{
friends = [[NSMutableArray alloc] initWithCapacity:1];
NSArray *resultData = [result objectForKey:@"data"];
if ([resultData count] > 0) {
    for (NSUInteger i=0; i<[resultData count]; i++) {
        [friends addObject:[resultData objectAtIndex:i]];
    }
} else {
    //[self showMessage:@"You have no friends."];
}

}

and I am implementing the required UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [friends count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:    (NSIndexPath *)indexPath
{
    //NSManagedObjectModel *friend [fetch

    FriendCell *cell = [tableView dequeueReusableCellWithIdentifier:   @"friendCell"];

    cell.cellName.text = [friends objectAtIndex:indexPath.row];

return cell;
}

The problem is that the method 'cellForRowAtIndexPath' is being called before my data has arrived, how do you prevent the automatic initialization of the table view and only initialyse it when you have data for it ?

A: The tableview is always loaded on launch. Instead, after the data has finished loading, call
[self.tableView reloadData];

This tells the tableView to refresh, and it calls cellForRowAtIndexPath and all that jazz again.

A:
how do you prevent the automatic initialization of the table view

You don't. The table view will automatically try to load its data when it is created and displayed. But that should not be a problem.

and only initialyse it when you have data for it.

Send a reloadData message to the table view once the data is ready.

A: Have you remembered to change the number of sections from 0 to at least 1?
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

To fully test this you can use the following code
- (void)viewDidLoad
{
    [super viewDidLoad];

    //Add your friend as you initialise the array
    NSMutableArray *array = [NSMutableArray arrayWithObjects:f1,nil];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [self.friends count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    //change this to whatever you need
    NSString *friend = [self.friends objectAtIndex:indexPath.row];
    cell.textLabel.text = friend;

    return cell;
}

A: Your numberOfRowsInSection should return 0 if you don't have anything to display. After the data is loaded and ready to display, you should call reloadData on the tableView, and only then should the data be displayed. numberOfRowsInSection should now give the number of rows you loaded.
In short, you don't prevent the tableView from initializing. You initially tell it to display no data, and once your data is loaded, you tell it to display as many rows as you have.

A: Don't set the tableview delegate and datasource until AFTER you have your data.
i.e.
-(void)viewDidLoad{
     [self apiGraphFriends];
     self.tableview.delegate = self;
     self.tableview.datasource = self;
}

I am assuming your method 'apiGraphFriends' doesn't use any background threading and isn't asynchronous. If it is, then just create a new method and put the datasource/delegate setting in there, then call it from a block in your apiGraphFriends method.

A: simply call reloadData of the tableView once you got your data, the tableview will reload its data and thus recall all your datasource methods to get its data.

A: You are so close!
- (void)viewDidLoad
{
  [self apiGraphFriends];
  [super viewDidLoad];
}

That should do it. If not, you can always call reloadData on the tableView.


text:
Q: add conditionals to a displayed external xml feed I found the following code online and customized it to pull the xml feeds from our online calendar software and display event information on several different WP pages.
function otpl_add_class_feed() {
    if ( is_page(48) ) {
        $url = "http://orion.lib.mi.us/evanced/lib/eventsxml.asp?ag=&et=Computer+Class&nd=31&dm=exml&alltime=1";
        $xml = simplexml_load_file($url);
        foreach($xml->item as$item)
            {
                echo "
";
                echo "
link."'>".$item->title."
";
                echo "
".$item->date." from ".$item->time." to ".$item->endtime."
";
                echo "
".$item->description."
";
                echo "
link."'>Register Online.
";
                echo "
";
            }
    } // END IF
}

How can I include a conditional statement so that if $item->date. is populated the above code will run but if $item->date. is empty then another code stating that there are no events scheduled will run?  I'm sure it's something simple but my understanding of syntax isn't very strong.  My few attempts have broken my functions page.

A: As @birgie pointed out, add a conditional statement to check that the date has been set:

if ( isset( $item->date ) && strlen( $item->date ) > 0 ) { ... }


text:
Q: Blank NSComboBox on OS X Yosemite I have a set of NSComboBox elements shown within the toolbar of an NSPanel, all created with XCode/Interface Builder. When I click on them on Yosemite, all I can see is a black box where the combo box items should be. On earlier versions of OS X this works just fine. No exceptions are logged at all. Here's a screen capture:

Any idea of what could be broken? I can't see any relevant release notes from Apple.

A: Bypassed this by using a NSPopup instead.


text:
Q: Use button without submit action I have this form:
    <form id="form21" runat="server" method="post" onsubmit="return send()">
          <asp:Button runat="server"  ID="submit" name="submit" type="submit" class="btn btn-send" Text="עדכן" onclick="submit_Click" />
          <asp:Button ID="other" name="other" runat="server" class="btn btn-send" onclick="other_Click" Text="control" Visible="False"/>
    </form>

The "other_Click" method loads data from my database.
I don't want the button: "other" use the "onsubmit='return send()'". Can I do that?

A: Why are you using a FORM to achive it ??
in this case at my personal advice it will be more simple this approach : a simple button which call a javascript function to retrieve data and then you may use this data as per your need.
In example:
<input type="button" id="ID" name="ID" value="Get Data" onclick="YourFunction"/>

<script type="text/javascript">
 function Yourfunction()
     {
        $.ajax({
         type: "POST/GET", url: url, data: p,
         success: function (msg) {
          //tmp = JSON.parse(msg); if needed
          //do something here
         },
         error: function (msg) {
           //do something here
         }
      });
     }
</script>

However if may give us more info it would be better to better help you


text:
Q: Getting started: where should I write the program? so I am required to do an Answer-Set-Programming project, where we should solve some problem and create test cases, using the DLV solver.
According to the specification of the project we need to make the files G.dl, Ch.dl, and test.dl so keeping in mind that I am very new to all of this, here is my question:
what is this .dl file and how do I create one? or better yet:
Where am I supposed to write all these facts and rules (which I have on paper, by the way) to be able to save the as a .dl file?

A: Those are simple text files, you can write them in any text editor. There is also an online DLV solver at this webpage.


text:
Q: What questions does Topology answer? I was reading the great Thurston's article on Mathematical Education and one thing he points out is:

People appreciate and catch on to a mathematical theory much better after
they have first grappled for themselves with the questions the theory is designed to
answer.

In this sense, what do you think are the questions Topology is designed to answer?
P.S.: My focus here is Topology, but feel welcomed to give examples from other areas as well.

A: The question might be:
How much of "geometry" (our intuition of "shapes") works without using numbers (i.e. when we are not allowed to use coordinates, measure distances, etc.)?


text:
Q: download sql table data as pdf in asp.net mvc Hello I want to download my table data into pdf format in asp.net mvc, but the problem is I am not able to find any free library for the same, all the examples on the web are with iTextSharp but iTextSharp is paid and cannot be used for commercial purpose.
is there any library which I can use.
thank you for your help


text:
Q: How to know the operation of a notification message when I subscribe redis database? I'm using redis-py. I subscribe to redis database and read notification like this:
>>> p.psubscribe("__keyspace@{}__:*".format(...))
>>> for message in p.listen():
...     # do something with the message

I want to get the operation of the message, like DELETE or ADD, how can I do this?
Thank you~

A: Per the documentation (https://github.com/andymccurdy/redis-py#publish--subscribe), when calling listen(), the message is returned as a dictionary:

*

*type: One of the following: 'subscribe', 'unsubscribe', 'psubscribe', 'punsubscribe', 'message', 'pmessage'

*channel: The channel [un]subscribed to or the channel a message was published to

*pattern: The pattern that matched a published message's channel. Will be None in all cases except for 'pmessage' types.

*data: The message data. With [un]subscribe messages, this value will be the number of channels and patterns the connection is currently subscribed to. With [p]message messages, this value will be the actual published message.

In the case of the '__keyspace*' pattern, the data key in the message dict holds the operation's name. Put differently:
>>> p.psubscribe("__keyspace@{}__:*")
>>> for message in p.listen():
...     print(message['data'])  # print the operation

Note: the call to format(...) appears to be not needed in your sample.


text:
Q: Pass DbContext to class library I am developing an API to get data from the database using the entity framework. I have a class library to handle my generic tasks, including Repository, UnitOfWork etc. My UnitOfWork class is as follows.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using AppPermission.Data.DataContext;
using AppPermission.Data.Models;
using AppPermission.Data.Repositories;

namespace AppPermission.Common.UnitOfWork
{
    public class UnitOfWork : IUnitOfWork
    {
        private readonly DbContext dbContext;

        public UnitOfWork(DbContext context)
        {
            dbContext = context;
        }

        public int SaveChanges()
        {
            return dbContext.SaveChanges();
        }

        public async Task<bool> SaveChangesAsync()
        {
            return await dbContext.SaveChangesAsync() > 0;
        }

        public void Dispose()
        {
            dbContext.Dispose();
            GC.SuppressFinalize(this);
        }

    }
}

My API's ConfigureServices is as below
public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<AppDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<AppDbContext>();
            services.AddSession();
            services.AddControllersWithViews();
            services.AddRazorPages();
            services.AddScoped<IUnitOfWork, UnitOfWork>();
        }

I want to pass AppDbContext registered in the API startup to UnitOfWork in the class library. There were a couple of solutions in StackOverflow using(services.BuildServiceProvider), but the connection is disposed of after the first API call (GetAll). Is there any way of doing it? If I place my UnitOfWork in the API project itself and changing the constructor in UnitOfWork to accept AppDbContext, it works fine?

A: It's a good idea to use Generic UnitOfWork :
public class UnitOfWork<TContext> : IUnitOfWork where TContext : DbContext

class constructor :
public UnitOfWork(TContext context, ILogger<UnitOfWork<TContext>> logger){}

Then add it to IServiceCollection like this :
services.AddScoped<IUnitOfWork, UnitOfWork<MonitoringDbContext>>();


text:
Q: prevent css/jquery popups from allowing links underneath to be clicked (mobile only) so i have created !a simple popup using css and jquery.  the problem is, when the popup is activated, links underneath the popup can still be clicked.  is there any way to prevent this from happening.  the click box for some of the links in the popup are small and one can easily click next to it which means the link underneath the popup is clicked.
the site i am working on: taxslayerplayer.com, look at it on an android and you will see what i mean. also, i have experienced this problem on many other websites while browsing on my phone.
any pointers would be appreciated, thanks!

A: I'm not sure about a strictly-mobile solution, but you could check for the pop-up being visible and, if it's visible, simply return false in the click-handler for links:
$('a').filter(
    function(){
        return !$(this).closest(popupSelector).length;
}).on('click', function(e){
    if ($(popupSelector).is(':visible')) {
        return false;
    }
    else {
        // do whatever you'd normally do with the links
    }
});

Alternatively, you could instead use a variable, for example popupIsShown, set it to false initially (on DOMReady), and then set it to true when the popup is shown, and reset to false when it's re-hidden, making the if check a little less expensive:
$('a').filter(
    function(){
        return !$(this).closest(popupSelector).length;
}).on('click', function(e){
    if (popupIsShown) {
        return false;
    }
    else {
        // do whatever you'd normally do with the links
    }
});

A: Use a boolean value and set it to false in case of pop-ups. It works!
PS : Just checked.. David has already answered it.


text:
Q: Word or Phrase for "Easily Swayed" What word or phrase best communicates the idea that a human (or other sentient being) is easily swayed, particularly between moral good and evil? Words I have found that are close are:

*

*Impressionable - Easily influenced because of a lack of critical ability.

*

*Implies that the subject lacks critical skills, and misses the concept of good and evil.

*Gullible - Easily persuaded to believe something

*

*Misses the concept of good and evil

I created a typical angels and demons scenario to demonstrate the polar extremes of the the spectrum. In this scenario, I lack the word to describe the humans, who can be influenced towards either end of the spectrum if impressed upon by an external entity.

The angels are devoted to good, and are immovable in their ideals. The demons are wicked, and will feign morality only to manipulate others. Both prey upon the humans, who are ____________.

I think that the key here is the spectrum of good an evil. Here are examples of other spectra and their associated words, for comparison.

*

*Easily pushed from calm to angry: Temperamental

*Easily moved from determined to hopeless: Weak-willed

*Easily influenced by propaganda: See answers here

A: suggestible

Open to suggestion; easily swayed:
a suggestible client would comply

From Etymonline:

1851, "capable of being influenced," from suggest + -ible.

Some important aspects of suggestibility:

When anyone is absorbed in rapt attention in someone else's inspiring words as they outline an idea or way of thinking, the subjective attention is held because of the logic, the aesthetic, and the relevance of the words to one's own personal experience and motivations. In these natural trance states, just like those orchestrated purposefully by a hypnotherapist, your 'critical faculties' are naturally less active when there is less you would naturally be critical of.
To be suggestible is not to be gullible. The latter pertains to an empirical objective fact that can be shown accurate or inaccurate to any observer. The former term does not. To be open to suggestion, has no bearing on the accuracy of any incoming suggestions: nor whether such an objective accuracy is possible. (As with metaphysical belief.)

And a well-known example of suggestibility towards the good vs. evil from the book "Everybody for Everybody: Truth, Oneness, Good, and Beauty for Everyone's Life, Liberty, and Pursuit of Happiness" by  By Samuel A. Nigro:

A: tractable

tractable: easily controlled or persuaded

malleable

malleable: able to be influenced; pliable or tractable

pliant

pliant: easily influenced; yielding readily to others

A: credulous
1.willing to believe or trust too readily, especially without proper or adequate evidence; gullible.
2.marked by or arising from credulity.

A: Pliable--yielding readily to others

A: Your best option may be to use "morally" or "ethically" as adverbs and pair them with some adjectives similar to the ones you dug up that imply a lack of commitment or dedication. For example, morally impressionable or ethically irresolute. Capricious and malleable could also be good choices.

A: "wandering in the wilderness without a compass." - Scalese
"like a float tossed about by the waves of a turbulent sea." - Tesla

A: Fallible can fit on the good/evil spectrum.

Capable of making mistakes or being wrong

Where here wrong would be a moral rather than factual judgement. Fallible has its origins in the Latin fallere - to deceive, and also has the connotation of being 'subject to failure' where in use to describe oneself or another, that failure is often moral.
Alternately, a candidate phrase to complete that sentence might be "susceptible to their influence(s)"

A: "searching for conviction" or "without conviction"
conviction: a firmly held belief or opinion.
or something using the word compliant

A: The state of acting against one's own moral values, or akratic action  -AKA acrasia

Akrasia: Weakness of will: the condition in which while knowing what
  it would be best to do, one does something else. The phenomenon
  intrigued Plato and Aristotle, because the Socratic equation between
  knowing a thing to be good and desiring it makes it difficult to see
  how weakness of will is possible. Less optimistic philosophies find it
  equally hard to see how strength of will is possible.

A: At the risk of sounding extremely arrogant:

The unthinking and unknowing are naïvely | oblivious and easily swayed.

Another somewhat perverse way to describe someone who is easily swayed is innocent.


text:
Q: Is it possible to write a function work for int and long (float, byte .etc) in F#? when use
let add a b = a + b

it works for int. and
let add2 a b:float = a + b

work for float.
Is it possible to write a function work for int and long (float, byte .etc) in F#?
i need a function whose "a" work for int and long like this:
let f a b = a >>> b
let f (a:int64) b = a >>> b

is it possible in F#?

A: When you want to write a function that can work with multiple different numeric types, you need to use inline and "static member constraints". The problem is that normal .NET generics cannot capture constraints like "supports the + operator".
To make your sample add function generic, you can use inline:
let inline add x y = x + y

When you look at the inferred type, you'll see something like this:
val inline add :
  x: ^a -> y: ^b ->  ^c
    when ( ^a or  ^b) : (static member ( + ) :  ^a *  ^b ->  ^c)

This essentially says that the function can be called on any two arguments that support the + operator. Note that this only works because the function is inline and so the F# compiler does not have to rely on .NET to express the constraints. The same works for the >>> operator:
let inline f a b = a >>> b

The function can now be used with both int64 and int arguments:
f 1024L 2
f 1024 2

I wrote an article about writing generic numeric code in F# some time ago which you may find useful too.


text:
Q: How does Gibbs sampling produce values for a variable using the univariate conditional probability? I have a question about Gibbs sampling for generating samples. The Gibbs sampling algorithm is often stated.

*

*$x^0 = (x_1^0, x_2^0, \ldots, x_n^0)$ //initialize random values

*for $t=1$ in $T$ //iterate to generat T samples

*

*$x_1^t \sim P(X_1 | x_2^{t-1}, x_3^{t-1}, \ldots, x_n^{t-1})$ //compute univariate conditional probability

*$x_2^t \sim P(X_2 | x_1^{t}, x_3^{t-1}, \ldots, x_n^{t-1})$

*$\vdots$

*$x_n^t \sim P(X_n | x_1^t, x_2^t, \ldots, x_{n-1}^{t})$

How do we actually compute the univariate conditional probability? If we assume a multivariate gaussian probability distribution for the variables, would this not be an expensive operation?
For example, if we wanted to compute the univariate conditional probability for $x_1$, that is defined by the following.
$
\begin{eqnarray*}
x_1^t & = & P(X_1 | x_2^{t-1}, x_3^{t-1}, \ldots, x_n^{t-1})
 & = & f(x_2,\ldots,x_n)
 & = &
\frac{1}{\sqrt{(2\pi)^{n-1}|\boldsymbol\Sigma|}}
\exp\left(-\frac{1}{2}({\mathbf x}-{\boldsymbol\mu})^\mathrm{T}{\boldsymbol\Sigma}^{-1}({\mathbf x}-{\boldsymbol\mu})
\right)
\end{eqnarray*}
$
Now, $\Sigma$ is the covariance matrix between $X_2, \ldots, X_n$ (if I understand correctly, it does not include covariance with $X_1$). This covariance matrix will be different for each $X_i$ (it will always be between the variables in the set, $X \setminus X_i$.
And then I also noticed $|\boldsymbol\Sigma|$, which is the determinant of the covariance matrix. If I understand correctly, this determinant too have to be computed for each $\Sigma$ associated with a $X_i$.
Is my understanding about the covariance matrix and its determinant being unique for each $X_i$?
Lastly, when I am computing the univariate conditional probability (e.g. using a multivariate gaussian distribution), I get back a value $x_i^t$, which is the value for $X_i$ in the next iteration. But what I have a problem understanding is that $x_i^t$ is a probability of $X_i$ and not a value. It doesn't seem that $x_i^t$ will be in the domain of $X_i$ since it is a probability value in the space [0, 1], and $X_i$ might have a domain $[\infty,-\infty]$.
Am I misunderstanding Gibbs sampling for variables with a multivariate gaussian distribution with respect the covariance matrix and univariate conditional probability?
If I understand correctly, for $\Sigma$, I suppose I can compute it once for $X_1, \ldots, X_n$ and then create the $\Sigma_i$ and pre-compute $|\Sigma_i|$ once.

A: You raised two broad questions

*

*How expensive is Gibbs sampling?

*In your multivariate Gaussian example, the domains don't seem to match up, since the values obtained via Gibbs sampling seem to be probabilities.

I will address the second question first.
Your interpretation of how the Gibbs sampling works is incorrect. Consider the simple example a random variable having a standard Gaussian distribution. That is $X \sim N(0,1)$. Then the density of $X$ is
$$f_X(x) = \dfrac{1}{\sqrt{2\pi}} e^{-x^2/2}. $$
When you draw an observation $x$ from the normal distribution, you don't have $x = f_X(x)$, but rather the $x$ drawn satisfies that density equation. So $x$ will not be in $[0,1]$, but rather since the normal variable is defined on all $\mathbb{R}$, $x$ could theoretically lie anywhere on the real line. A draw from a Normal distribution (multivariate or not) can be made using existing software (for example in R using rnorm). The density of the standard normal random variable looks life.

This density means that most sampled points are going to be between -2 and 2, even though the height of the function does not surpass $.5$. (Another thing, for continuous random variables, it is possible for the density function $f_X(x)$ to be larger than one, for example, the density of the N$(0, .2)$ as shown below, where the density function reaches 2.)

So basically, drawing points from a distribution is different from evaluating the density function. Gibbs draws points from a distribution. Once you have a closed form expression of the conditional distribution, you can use existing software in most case. Often the full conditionals are Normal, Gamma, Inverse Gamma, $\chi^2$, Inverse Gaussian, Beta etc.
To address your first question about how computationally intensive a Gibbs sampler can be, the answer would change from problem to problem. Sometimes a full conditional distribution requires an update from say a normal distribution that looks like
$$X_1|X_{-1}, \sigma^2,y \sim N(y^TA^{-1}y, \sigma^2), $$
where say $A$ is a large dimensional square matrix. Then every Gibbs update update requires a large matrix inverse, which will be expensive. However, in most such cases a Gibbs update will still be cheaper than a Metropolis-Hastings algorithm (since that requires 2 likelihood evaluations). In addition, some cases Gibbs updates can also be fairly cheap, so it depends from case to case really.

EDIT:
In your example, to draw from $f(x_1^T|x_2^{t-1}, \dots, x_{n}^{t-1})$ you can use existing functions in programming languages (R, python, C, C++, Java) that let you draw from known distributions like Normal, Gamma, Inverse Gamma, Beta, Poisson, Binomial, etc. Basically, the way the algorithm works is after drawing $x_0$ you have observed the first $n$ $x$s. For $t = 1$, when you update $x_1^{1}$ you use the other $x_0$ values to get $x_1^{1}$, using the $f(x_1^T|x_2^{t-1}, \dots, x_{n}^{t-1})$ distribution. So for example you can initialize
$$x_0 \sim N(0, I_n), $$
and then to update you have the conditional density for $x_1$ as
$$x_1^{1} \sim N\left( \left(\begin{array}{c}x_2^0 \\x_3^0 \\ \vdots \\x_n^0   \end{array}\right)  , \Sigma \right)$$
You can draw from this distribution just from the programs since you know $(x_2^0, x_3^0, \dots, x_n^0)$.

A: When you use a Gibbs sampler you draw from the conditional distribution. The symbol '$\sim$' means 'distributed as'. So your sampling scheme means that you draw $x_1 ^t$ from it's conditional distribution given all the other variables, then you draw $x_2 ^t$ from its distribution conditional on the other variables (including the $x_t ^t$ which we just drew). Also even if you did have to calculate a lot of multivariate normal densities as long as you don't have a very large number of variables the computational cost is probably not going to be that high.


text:
Q: half-siblings - adults' relationship I was married and we had a daughter. We divorced. My ex-husband remarried and has a son. Our daughter and his son are half-siblings - share a dad. What am I to his son? What is his new wife to my daughter - stepmother I think?

A: Stepmother is a woman:

who is married to one's father after the divorce of one's parents or the death of one's mother.

The relationship is established only when you are (legally) married to a man who had a child or children with his ex-wife or deceased wife. You would be his/her would-be stepmother if you are planning to marry him.
You are just an ex-wife or friend (if you maintain friendship with him) of his father. There is no legal relationship between you and him. The same applies to the relationship between your daughter and your ex-husband's new wife.
[Oxford Online Dictionary]


text:
Q: What's the difference between getDefaultSharedPreferences() and getPreferences()? I'm currently taking the "Developing Android Apps" Udacity course. In the "Lesson 3: New Activities and Intents >  Use SharedPreferences" segment, the instructor asked me to dig around the Android Developer site for how to get the user preferences from SharedPreferences. However, I found it different between the official documentation and the course's solution.
The Udacity course's solution says, to grab a SharedPreferences instance for the PreferenceActivity, you should call:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());

(where getActivity() is simply the Context here because it's called inside a Fragment.)
While the official documentation on Android Developer Site indicates that you should call:
SharedPreferences prefs = getActivity().getPreferences(Context.MODE_PRIVATE)

So what's the difference between PreferenceManager.getDefaultSharedPreferences(Context context) and Activity.getPreferences(int mode)?
Please note: This question does not involve anything about getSharedPreferences() which requires a file name. It's about the difference between getPreferences() and getDefaultSharedPreferences().
Thanks in advance.

A: Acoording to the link you provided to Android documentation

getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.
getPreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.

So it is, use getSharedPreferences when the data you want to save/retrieve can be used from different activities in the app. If those preferences will only be used in one Activity, you can use getPreferences.
Edit: also note that as said in the post you linked 'getDefaultSharedPreferences will use a default name like "com.example.something_preferences", but getSharedPreferences will require a name'

A: One of the major differences: getPreferences () returns a file only related to the activity it is opened from.  While getDefaultSharedPreferences () returns the application's global preferences.  Learned that the hard way yesterday.

A: If you take a look inside PreferenceManager:
public static SharedPreferences getDefaultSharedPreferences(Context context) {
    return context.getSharedPreferences(getDefaultSharedPreferencesName(context),
            getDefaultSharedPreferencesMode());
}

/**
 * Returns the name used for storing default shared preferences.
 *
 * @see #getDefaultSharedPreferences(Context)
 * @see Context#getSharedPreferencesPath(String)
 */
public static String getDefaultSharedPreferencesName(Context context) {
    return context.getPackageName() + "_preferences";
}

private static int getDefaultSharedPreferencesMode() {
    return Context.MODE_PRIVATE;
}

So getDefaultSharedPreferences() use getSharedPreferences() method with your app package name and mode private, if you use getPreferences() from activity it will use the same getSharedPreferences() method but with getLocalClassName();

A: From the first article linked below: "Note: The SharedPreferences APIs are only for reading and writing key-value pairs and you should not confuse them with the Preference APIs, which help you build a user interface for your app settings (although they use SharedPreferences as their implementation to save the app settings)."
http://developer.android.com/training/basics/data-storage/shared-preferences.html
http://developer.android.com/guide/topics/ui/settings.html


text:
Q: Generic method in asp.net I have a created a generic class in asp.net named BasketController, now BasketController handles 2 types of functionality AnonymousBasket and UserBasket, so i have created generic method to add product to basket, now based on Type specified by user, it will add products. Below is the class i have created:
public class BasketController<T>
    {
        public void AddProduct<T>(T obj)
        {
            if (obj is AnonymousBasket)
            {
                AnonymousBasket anon = obj as AnonymousBasket;
                SqlHelper.ExecuteNonQuery(Global.ConnectionString, "Basket_Add", new object[] { Enumerations.BasketType.Anonymous, anon.AnonymouseBasketID, anon.PackageID, anon.PurchasedUnits });
            }
            else
            {
                UserBasket anon = obj as UserBasket;
                SqlHelper.ExecuteNonQuery(Global.ConnectionString, "Basket_Add", new object[] { Enumerations.BasketType.User, anon.UserID, anon.PackageID, anon.PurchasedUnits });
            }

        }
    }

Now my problem is i have to specify SqlHelper.ExecuteNonQuery method twice as i cannot know the type of class until it's passed if conditions, is there anyway i can specify the SqlHelper outside if condition, so that i need to call SqlHelper only once.

A: You can create an interface like below
interface IBasket
{
}

and inherit your classes from IBasket like below
AnonymousBasket: IBasket
{
}

UserBasket : IBasket
{
}

Now as IBasket is parent interface so you can use it's reference to add the data into database.
Change your mthod as follows
public void AddProduct(IBasket basket)
{

}

A: Try
public class BasketController<T>
    {
        public void AddProduct<T>(T obj)
        {
            object[] _objects;
            if (obj is AnonymousBasket)
            {
                AnonymousBasket anon = obj as AnonymousBasket;
                _objects = new object[] { Enumerations.BasketType.Anonymous, anon.AnonymouseBasketID, anon.PackageID, anon.PurchasedUnits };
            }
            else
            {
                UserBasket anon = obj as UserBasket;
                _objects = new object[] { Enumerations.BasketType.User, anon.UserID, anon.PackageID, anon.PurchasedUnits };
            }
            SqlHelper.ExecuteNonQuery(Global.ConnectionString, "Basket_Add", _objects);
        }
    }

A: Another possibility (added as a separate answer, to let the voters decide which one is best) would be to just have a property (or method) on your basket types that gets the enum type for you. Say you define them on a common interface:
public interface IBasket
{
    Guid ID { get; set; }
    // other basket properties
    Enumerations.BasketType Type { get; }
}

and then you let each type provide their own implementation:
public class UserBasket : IBasket
{
    // Implementaiton of other basket properties
    Enumerations.BasketType Type { get { return Enumerations.BasketType.User; } }
}

Now, you don't even need a ternary statement - each basket knows its type. So now you could do
public void AddProduct(IBasket basket)
{
    SqlHelper.ExecuteNonQuery("Add_Basket", new object[] {
        basket.Type,
        basket.ID,
        basket.PackageID,
        basket.PurchasedUnits
    });
}

Note that this is future proof: if you want to add a new basket type in the future, just add another type that implements IBasket, and that returns something relevant from the Type parameter. This method will just continue working without change.

A: If I understand you correctly, the only difference in the two versions is the enum type, right?
Use an interface, which defines the properties you need:
interface IBasket {
    Guid ID { get; set; } // use for AnonBasketID or UserID depending on implementation
    Guid PackageID { get; set; }
    int PurchasedUnits { get; set; }
}

Then, let your basket types implement this interface, and use a ternary statement to determine the enum type:
public void AddProduct(IBasket basket)
{
    var type = (basket is UserBasket)
               ? Enumerations.BasketType.User
               : Enumerations.BasketType.Anonymous;

    SqlHelper.ExecuteNonQuery("Basket_Add", new object[] {
                                                            type,
                                                            basket.ID,
                                                            basket.PackageID,
                                                            basket.PurchasedUnits
                                                          });
    // Yes, I do funky things with whitespace to avoid scrollbars on SO...
}


text:
Q: How can I make a cocos2d game only support iPod4 /iPhone4 and later My game was rejected, because it crashes in iPad, but I don't want the game to support iPad. I did not even upload any screen-shoot to iTunes Connect. How can I do this?

A: You can't. All apps will be able to run on iPads, even those set to iPhone-only. They just won't use the full screen size / pixel density.
iPhone-only apps run in the 1x/2x compatibility modes on iPad where content is optionally scaled up.
You should try to confirm the crash on iPad simulator or (better) an actual iPad device.


text:
Q: How to auto update the expired GPG keys of APT? When you create your own APT repo, you have to create a GPG key for it.
So you need to import it with:
apt-key add yourkey.asc

or with a key server:
apt-key adv --keyserver keyserver.ubuntu.com --recv 3E5C1192

However, I do not know any update process for this ? When the key will expire, in both case, do we need to import-it again ?


text:
Q: Does beforeEach() work as expected in cypress? I am trying to use beforeEach() in my cypress test but my dev says that the cypress code gets loaded at once and before each might not functions as its meant to. Is that true ?

A: It depends on what your expectation is of beforeEach(). But I can tell you how it works. A beforeEach() is indeed loaded at once, but it is performed before each it() in your test. So if your goal is to have the steps in the beforeEach to be executed in every test, than it works exactly as you wish.


text:
Q: The bicategory of monoidal categories vs the tricategory of one-object bicategories. A monoidal category is a bicategory with one object.
So from this perspective, one would be tempted to define a tricategorie $ \overline{\mathbf{Mon Cat}} $ of monoidal categories with

*

*lax functors between one-object bicategories as 1-morphisms,

*lax transformations between such functors as 2-morphisms,

*modifications between such transformations as 3-morphisms.

But of course according to the usual definition $ \mathbf{Mon Cat} $ constitutes just a bicategory with 1- and 2-morphisms being monoidal functors and monoidal trafos.
In fact these two definitions still agree on the 1-morphisms. I.e. a lax functor of one-object-bicategories corresponds precisely to a lax functor of monoidal categories. They don't agree on the 2-morphisms though:
Among other things, a 2-trafo $\sigma: F \to G: \mathbf{A} \to \mathbf{B} $ carries objects $a \in A$ to morphisms $\sigma_a \in \mathbf{B}(Fa,Ga)$ and nothing in the definition of monoidal trafo corresponds to that.
Note that a similar problem arises also on the level of 1 morphisms, but there the part of a 2-functor which carries objects to objects becomes trivial, since the relevant bicategories just have one object.
Long story short, it seems to me when considering $\mathbf{MonCat}$ it is a bit misleading to think of monoidal categories as one object bicategories, because the monoidal functors and trafos are really more like special 1-categorical functors and trafos, than like 2-categorical functors and trafos.
My question is now, is $\mathbf{MonCat}$ (seen as a tricategory with idendity 3-cells) a subtricategory of $\overline{\mathbf{MonCat}}$? Or is there any other interesting relation, between these two different possibilities to interpret monoidal categories as objects in higher categories? And although this seems to be a bit of a soft question, is there a good conceptional reason, why $\mathbf{MonCat}$ is defined the way it is?
Regarding the last point, I would appreciate an argument which generalizes to the correct definition of the tricategory of monoidal bicategories. (Where completely analog to above the fact that monoidal bicategories are just one objects tricategories will immediately yield a (weak) 4-category, but not the desired tricategory I guess.)

A: I asked the $n-1$ version of this question here, and got a good answer. So I suspect you can categorify that. I'm afraid I can't fill in the details since I get a bit lost at the level of modifications.


text:
Q: How do I determine a winner in Tic Tac Toe I've been trying to figure out how can I use WinCombos to determine a winner but failed.
How can I compare my array (winCombos) with the cells in a 3x3 tic tac toe board to determine a winner?
var player1 = "X";
var player2 = "O";
let currentClass = player1
const winCombos = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [6, 4, 2]
]

let cells = document.querySelectorAll(".row>div");
console.log(cells);

for (var i = 0; i < cells.length; i++){
   cells[i].addEventListener('click', cellClicked, {once: true})
   var j =  cells[i]
}

function cellClicked(){
  if(currentClass == player1){
    event.target.textContent = currentClass;
    currentClass = player2;
    if(checkWin(currentClass)){
      console.log("winner");
    }
  }else{
    currentClass == player2;
    event.target.textContent = currentClass;
    currentClass = player1;
  }
}

A: We can use Array.prototype.some and Array.prototype.every in order to accomplish our goal.
function checkWin(player) {
    return winCombos.some(v => v.every(k => cells[k].textContent == player));
}


text:
Q: Animate letter with css and jQuery HERE'S MY JSFIDDLE
I have animation on my text when you hover them images.
But I would like to apply more effect on these texts (h1).
I showed you an exemple on my JSFIDDLE with the text "What I want" (you have to reload the page to see the effect)
I would like to apply the effect of the text "What I want" on the other h1 text. (01-One, 02-Two and 03-Three)
But it doesn't work.
JQUERY :
$('h1').lettering();

$('h1').children().each(function(i){
  var letter = $(this);
  setTimeout(function(){
    //alert('yo');
    letter.addClass('fadeBounceIn')
  }, i*50)
});

A: Check out this jsFiddle I made. I think it's pretty close to what you're trying to do.
The problem is that the lettering bounce-in effect you have only occurs one time when the page loads. So all of your h1's were getting animated just fine, but they were not animating again when you scroll.
I simply took that code and put it into a function like this:
var lettering = function() {
$('h1').lettering();
$('h1').children().each(function(i){
  var letter = $(this);
  setTimeout(function(){
    //alert('yo');
    letter.addClass('fadeBounceIn')
  }, i*50)
});
}

And then inside of your scroll function I simply added a call to the lettering() function I created.
Finally, I've made an assumption that you still want it to happen on page load so I've simply added this:
$(document).ready(function() {
lettering();
});

Which will call the function on the initial page load.
You may need to play around with things a little bit to get your specific desired effect.


text:
Q: Submitting a web form using C# I have seen projects that are similar on stackexchange but not the same.
Question:
How can I submit this form correctly. (The code I have tried is below.)
I need to fill in the username and password fields and hit submit.  When I tried submitted the form the webBrowser1.url should be redirected to another page. (Which its not) I know the URL will redirect properly because if I go to a page that I dont have permission to go to it redirects me back to this page.
    WebBrowser webBrowser1 = new WebBrowser();

    string URL_mainLoginScreen = @"192.168.2.10:8080/login.jsp";
    bool pageLoaded = false;

    public Form1()
    {
        InitializeComponent();
        webBrowser1.Navigating += new WebBrowserNavigatingEventHandler(webBrowser1_Navigating);
        webBrowser1.Navigated += new WebBrowserNavigatedEventHandler(webBrowser1_Navigated);
    }

    // Navigates to the given URL if it is valid.
    private void Navigate(String address)
    {
        if (String.IsNullOrEmpty(address)) return;
        if (address.Equals("about:blank")) return;
        if (!address.StartsWith("http://") &&
            !address.StartsWith("https://"))
        {
            address = "http://" + address;
        }
        try
        {
            webBrowser1.Navigate(new Uri(address));
        }
        catch (System.UriFormatException)
        {
            return;
        }
    }

    //Called while navigating (not ready)
    private void webBrowser1_Navigating(object sender,WebBrowserNavigatingEventArgs e)
    {
    }

    //Called after navigation (page ready to parse!)
    private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
    {
        pageLoaded = true;
    }

    private void button3_Click(object sender, EventArgs e)
    {
        Navigate(URL_mainLoginScreen);
        while (pageLoaded != true)
            Application.DoEvents();
        HtmlElement username = webBrowser1.Document.GetElementById("USERNAME");
        HtmlElement password = webBrowser1.Document.GetElementById("PASSWORD");
        HtmlElement submitForm = webBrowser1.Document.GetElementById("form1");
        if (username != null)
            username.SetAttribute("value", "user");
        if (password != null)
            password.SetAttribute("value", "password");
        if (submitForm != null)
            submitForm.InvokeMember("Click");

        Application.DoEvents();
    }

Webpage
https://www.dropbox.com/s/aijeslqtca7x0of/webpageExample.html


text:
Q: How can I get a sublist from a Record in Netsuite using Suitescript? I am trying to create a scheduled suite script where it gets a sublist and applies some conditions to evaluate the result and send automated mail. But I couldn't get the sublist ID and can't retrieve the sublist data. Can I know where to get the sublist ID and how to create a way to retrieve the sublist data?
var sublistlines = currentRecord.getLineCount({
                    sublistId: 'SublistID',
                });
for (var i = 0; i < sublistlines; i++) {
                    var item = currentRecord.getSublistValue({
                    sublistId: 'SublistID',
                    fieldId: 'SublistFieldId',
                    line: i
                    });
                    if(condition){
                       action()
                    }

Sublistlines returns -1

A: You can get the record's details of its sublist ids and field ids using schema browser here is the URL and find the record with starting letter, in lower case there will be internal ids of each fields or sublist. Schema browser URL-
https://www.netsuite.com/help/helpcenter/en_US/srbrowser/Browser2016_1/script/record/salesorder.html
And you can also download field explorer chrome extension for netsuite through google and use it to view field ids on records.
Field Explorer chrome extension-
https://chrome.google.com/webstore/detail/netsuite-field-explorer/cekalaapeajnlhphgdpmngmollojdfnd?hl=en

A: You can use the getSublists() method to get all sublists deployed to a record. Here is an example script that I wrote that if called should give you all the values associated to all sublists related to an invoice record.
// get an array of all sublistId's available to the invoice record.
// you can use this with any record type and can perform this in client script or the debugger to find the sublist you're looking for.
var rec = record.load({type: record.Type.INVOICE, id: invoiceId});
var sublistIdArr = rec.getSublists();

// if you want to, you get more information about each sublist
for (var i = 0; i < sublistIdArr.length; i++) {
  var sublistId = sublistIdArr[i];
  var sublistFields = rec.getSublistFields({sublistId: sublistId});
  var sublistLineCount = rec.getLineCount({sublistId: sublistId});
  for (var line = 0; line < sublistLineCount; line++) {
    var sublistObject = {};
    for (var j = 0; j < sublistFields.length; j++) {
      var fieldId = sublistFields[j];
      sublistObject[fieldId] = rec.getSublistValue({sublistId: sublistId, fieldId: fieldId, line: line});
    }
    // do whatever you want with that sublist object here to see what is information is available.

  }
}


text:
Q: help someone [do]/[to do]/[in doing]/[on doing] something? Given the following sentences:

*

*They helped us frame some experimental evaluations.

*They helped us to frame some experimental evaluations.

*They helped us in framing some experimental evaluations.

*They helped us on framing some experimental evaluations.

Are all them grammatically correct or not? Are there any semantical nuances introduced by each alternative (and why), or do they mean exactly the same? Are there any other alternatives besides these 4 to convey the same meaning? Finally, which alternative is the best one, or does it depend on the context or writing style?

A: The first one is normal. The second one sounds a little more formal. I would avoid the last two as they sound a little awkward.

A: "On framing" would be poor grammar.
The others are fine, save that "To frame" and "in framing" are weaker, which is considered not incorrect, but boring.


text:
Q: Add XML Attribute to serialized class property I've seen an example that uses a wrapper class to do this, but i was wondering if there is a better (simpler) way.
My classes are as follows:
public class PartData
{
  public List<PartInfo> PartList { get; set; }
}

public class PartInfo
{
  public string PartNumber { get; set; }

  public string OEMNumbers { get; set; }

  public List<VehicleApplication> VehicleApplications { get; set; }
}

public class VehicleApplication
{

  public string Year { get; set; }

  public string Make { get; set; }

  public string Model { get; set; }
}

Serialize code:
//serialize
private void serialize()
{
   PartData p = GetParts();
   SerializeClass(p);
}

public void SerializeClass(object instance)
{
  var serializer = new XmlSerializer(typeof(PartData));

  using (var writer = new StreamWriter("C:\\TestFile.xml"))
  {
    serializer.Serialize(writer, instance);
  }
}

when serialized i get the following output:
 <PartData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <PartList>
    <PartInfo>
      <PartNumber>12345</PartNumber>
      <OEMNumbers>14556, 14557, 14558, 14559</OEMNumbers>
      <VehicleApplications>
        <VehicleApplication>
          <Year>2001</Year>
          <Make>Ford</Make>
          <Model>F150</Model>
        </VehicleApplication>
        <VehicleApplication>
          <Year>2001</Year>
          <Make>Ford</Make>
          <Model>F150</Model>
        </VehicleApplication>
        <VehicleApplication>
          <Year>2001</Year>
          <Make>Ford</Make>
          <Model>F150</Model>
        </VehicleApplication>
        <VehicleApplication>
          <Year>2001</Year>
          <Make>Ford</Make>
          <Model>F150</Model>
        </VehicleApplication>
      </VehicleApplications>
    </PartInfo>
  </PartList>
</PartData>

Ideally i would like to make PartNumber an attribute like so:
 <PartData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <PartList>
    <PartInfo>
      <PartNumber Id ="12345">
      <OEMNumbers>14556, 14557, 14558, 14559</OEMNumbers>
      <VehicleApplications>
        <VehicleApplication>
          <Year>2001</Year>
          <Make>Ford</Make>
          <Model>F150</Model>
        </VehicleApplication>
        <VehicleApplication>
          <Year>2001</Year>
          <Make>Ford</Make>
          <Model>F150</Model>
        </VehicleApplication>
        <VehicleApplication>
          <Year>2001</Year>
          <Make>Ford</Make>
          <Model>F150</Model>
        </VehicleApplication>
        <VehicleApplication>
          <Year>2001</Year>
          <Make>Ford</Make>
          <Model>F150</Model>
        </VehicleApplication>
      </VehicleApplications>
    </Partnumber>
    </PartInfo>
  </PartList>
</PartData>

I've tried adding:
public class PartInfo
{
  [XmlAttribute("Id")]
  public string PartNumber { get; set; }

  public string OEMNumbers { get; set; }

  public List<VehicleApplication> VehicleApplications { get; set; }
}

but creates:
<PartInfo Id="12345">

when i need:
<PartNumber Id="12345">

A: I think this is the only way to achieve what you are trying to achieve
public class PartDetail
{
  [XmlAttribute]
  public string ID{ get; set; }

  public string OEMNumbers { get; set; }

  public List<VehicleApplication> VehicleApplications { get; set; }
}

public class PartInfo
{
  public PartDetail { get; set; }
}

In answer to your first comment, this is the easiest way to achieve it, the alternative is to write a custom serializer


text:
Q: ExitWindowsEx - External exception 80000003
Possible Duplicate:
How to get rid of exception 80000003?

to force the PC shutdown by code, we use the function ExitWindowsEx in Delphi 7
It woks well but on a PC of one of our user,
ExitWindowsEx triggers an exception :  "External exception 80000003"
Pc is : Windows 7 x64 Service Pack 1 build 7601
Why that ?


text:
Q: Javascript object is undefined This is the code snippet I have:
var records = Ext.data.Record.create([{name: 'msgId', type:'string', mapping: 'msgId'},]);
...
...
var detailGrid = new Ext.grid.GridPanel({
  id:'detailGrid',
  store: dataStore,
  cm: new Ext.grid.ColumnModel({
    columns: [
      {id:'msgId',hidden: true, dataIndex: 'msgId'},
      {header: 'info',xtype: 'templatecolumn',tpl: 'View Message Details'}
    ]
}),

When it comes to onClick = "viewMessage(records)", I get : 'records' is undefined.
What is wrong here?
EDIT:The solution given works to remove the error. But when I put in a function like this:
function viewMessage(records){
alert(Ext.util.JSON.encode(records));
}

I get {} as alert i.e. no data.

A: Others have already explained why it's not working... your handler expects records to be a global variable, your handler is called and does not know where to get records from.
What you really should be doing is setting a listener for a 'headerclick' on your column model like
// EXT 4 version: wrap with Ext.onReady
Ext.create('Ext.data.Store', {
    storeId:'simpsonsStore',
    fields:['name', 'email', 'phone'],
    data:[
        { 'name': 'Lisa',  "email":"lisa@simpsons.com",  "phone":"555-111-1224" },
        { 'name': 'Bart',  "email":"bart@simpsons.com",  "phone":"555-222-1234" },
        { 'name': 'Homer', "email":"home@simpsons.com",  "phone":"555-222-1244" },
        { 'name': 'Marge', "email":"marge@simpsons.com", "phone":"555-222-1254" }
    ]
});

Ext.create('Ext.grid.Panel', {
    title: 'Simpsons',
    store: Ext.data.StoreManager.lookup('simpsonsStore'),
    colModel: {
        listeners: {
            headerclick: function(container, column, e, target, options) {
                if (column.id == 'col-name') {
                    alert('Anything you want');
                }
            }
        },
        items: [
            { header: 'Name',  dataIndex: 'name', id: 'col-name', sortable: false},
            { header: 'Email', dataIndex: 'email', flex: 1 },
            { header: 'Phone', dataIndex: 'phone' }
        ]},
    height: 200,
    width: 400,
    renderTo: Ext.getBody()
});

You mentioned that you're using Ext 3, the headerclick is slightly different, it should be set on the grid itself, instead of in the header container (column model). Something like
var records = Ext.data.Record.create([{name: 'msgId', type:'string', mapping: 'msgId'},]);
...
...
var detailGrid = new Ext.grid.GridPanel({
  listeners: {
    headerclick: function(grid, index, e) {
       if (index == 1) {
         alert('Clicked Grid');
       }
    }
  },
  id:'detailGrid',
  store: dataStore,
  cm: new Ext.grid.ColumnModel({
    columns: [
      {id:'msgId',hidden: true, dataIndex: 'msgId'},
      {header: 'info',xtype: 'templatecolumn',tpl: 'View Message Details'}
    ]
}),

A: maybe something like this
'View Message Details'

A: This is an issue with the return value of Ext.data.Record.create if you can provide a bit more context about what Ext.data.Record.create does exactly then I can help troubleshoot.
Try setting up a console.log(records); right after you assign the records variable.

A: Basically you just need to have some way of getting the records in scope.
According to your comment, it sounds like you have this structure - a script file that contains:
function creategrid(){
    var records = Ext.data.Record.create....
    var detailGrid = new Ext.grid.GridPanel({...
    {header: 'info',xtype: 'templatecolumn',tpl: 'View Message Details'}
    ...});
}

After that code is executed and the grid is rendered, you will have html similar to this on your page:

View Message Details

When you click on the anchor tag, the viewMessage function is called with the global variable records as its argument.  This will not work, since in your snippet, records is not setup as a global variable.
You need to make records available in the scope of the page:
var GridCreation = {};
GridCreation.records = {};
GridCreation.creategrid = function(){
    var records = Ext.data.Record.create....
    GridCreation.records = records;
    var detailGrid = new Ext.grid.GridPanel({...
    {header: 'info',xtype: 'templatecolumn',tpl: 'View Message Details'}
    ...});
};


text:
Q: Hint Predicated on a False Claim? A while back I asked this question about classifying all noncommutative $p^3$ groups (with $p \ge 3$). The book (see this) I am using gave the following hint

...there is a normal subgroup $N$ of order $p^2$, which is commutative. Now show that $G$ has an element $c$ of order $p$ not in $N$, and deduce that $G = N \rtimes \langle c \rangle$, etc.

I couldn't figure out how to show that such a $c$ exists. When I spoke with some people in the chatroom, they said that the hint is based upon a false claim---that it isn't always true that such a $c$ exists. One of them offered the following as a counterexample:
$$G= \left\{ \begin{pmatrix}1+pa & b \\ 0 & 1 \end{pmatrix} \mid a,b \in \Bbb Z/p^2 \Bbb Z \right\}$$
Is this in fact a counterexample? How does one show this?

A: Yes, there exist normal subgroups of order $p^2$ for which there is no $c$ of order $p$ outside of $N$. However there exists such an $N$ for which such a $c$ exists.


text:
Q: Gridview DataKeyName I used this code to retrieve each row DataKey :
    foreach (GridViewRow row in gv.Rows)
    {
        string id = gv.DataKeys[row.RowIndex].Value.ToString();

        Response.Write(id );
    }

But where are Gridview DataKeyNames in client code?

A: GridView's DataKeys are not rendered to the client side the way ViewState is rendered to client side in a hidden field and neither the way any Asp.Net scripts are added to the page by WebResource.axd etc..
You need to add those key values yourself. Why not try encrypting and adding the DataKeys separately to a hidden field in your markup, in case if that's your requirement ( just an example ). OR you can simply add the DataKeys to ViewState too.


text:
Q: Cannot import name array Traceback (most recent call last):
  File "try5.py", line 3, in <module>
    from matplotlib import pyplot as plt
  File "/home/zaverichintan/miniconda2/lib/python2.7/site-packages/matplotlib/__init__.py", line 129, in <module>
    from matplotlib.externals.six.moves.urllib.request import urlopen
  File "/home/zaverichintan/miniconda2/lib/python2.7/site-packages/matplotlib/externals/six.py", line 90, in __get__
    result = self._resolve()
  File "/home/zaverichintan/miniconda2/lib/python2.7/site-packages/matplotlib/externals/six.py", line 158, in _resolve
    module = _import_module(self.mod)
  File "/home/zaverichintan/miniconda2/lib/python2.7/site-packages/matplotlib/externals/six.py", line 80, in _import_module
    __import__(name)
  File "/home/zaverichintan/miniconda2/lib/python2.7/urllib2.py", line 94, in <module>
    import httplib
  File "/home/zaverichintan/miniconda2/lib/python2.7/httplib.py", line 69, in <module>
    from array import array
ImportError: cannot import name array

I have imported numpy , scipy , matplotlib and opencv.
The code getting executed on windows 7 machine but after upgrading to ubuntu 16.04, getting error like this.
the python version shows 2.7 but on the ubuntu site it is showing python 3.
Any help is appreciated.


text:
Q: dyld: Library not loaded: code signature invalid I'm trying to build and run an application that uses the AVFoundation framework ...
( I know that this is duplicate, but the solutions posted elsewhere doesn't help me.)
I build successfully but the app crashes when I re-run it from Xcode with the following error:
> dyld: Library not loaded: @rpath/libswiftAVFoundation.dylib
Referenced from : /private/var/containers/Bundle/Application/B9B93BB2-F55E-4DAE-A720-0F2D22A47278/FaceMarks.app/FaceMarks
Reason: no suitable image found. Did find:
/private/var/containers/Bundle/Application/B9B93BB2-F55E-4DAE-A720-0F2D22A47278/FaceMarks.app/Frameworks/libswiftAVfoundation.dylib:

>code signature invalid for '/private/var/containers/Bundle/Application/B9B93BB2-F55E-4DAE-A720-0F2D22A47278/FaceMarks.app/Frameworks/libswiftAVfoundation.dylib'

> lldb

The complete error message :

I have found many solutions, I have tested many of them but all of those not worked for me:

*

*Clean, build and run an application

*Set "Always Embed Swift Standard Libraries" to "Yes" under the Build Settings > Build Options

*Restart Xcode

*Restart the phone

*Reinstall the Xcode

*Testing other simple application on my iPhone ( App contains just a print function )

Note: That the test app works fine on the simulator but on my iPhone it gives the same error

dyld: Library not loaded: @rpath/libswiftCore.dylib

A: Code signing issues are usually account related, so if you're using a free Apple dev account that carries certain limitations and expiration issues with it.
Firstly, make sure you have a valid and active developer account logged into Xcode under:
Xcode | Preferences | Accounts

Alternatively remove the developer account shown there and add it back in again.
Secondly make sure that the account specified under Preferences | Accounts matches what you have selected for your project target under:
<TargetName> | Signing & Capabilities

A: I fixed this error by using a paid developer account.

A: For all those still looking for a solution, I have a free dev account and solved it like this:
The problem is that you must first "trust" your account on your iPhone, and trust apps made from this developer.
See instruction with screenshots here:
https://entirefaq.helpdocs.com/mobile-apps/iphone-app-how-to-fix-the-untrusted-enterprise-developer#:~:text=Tap%20Settings%20%3E%20General%20%3E%20Profiles%20or,prompt%20to%20confirm%20your%20choice.

A: Even with the paid developer account, I had to include the $(inherited) in the linker flags at the top. This actually did the trick. Secondly, I started having this issue in the release enterprise build, the reason was the certificate was not trusted to I had to add the Certificate Authority relevant to that certificate to make it valid.

A: Are you using the -deep signing flag? It can cause this problem.
See "--deep Considered Harmful".

*

*https://forums.developer.apple.com/thread/129980

*https://forums.developer.apple.com/thread/128166


text:
Q: Printing the number of days in a given month and year [Python] I've been trying to work out a way to accomplish what's in the title, without using any imported calendar/datetime libs from Python. There's little function at the top for checking whether or not the year is a leap year, which I want to be able to reference when printing the number of days in a given February, however I'm not too sure how to do so. (I've guessed with something like output. bla bla)
So far I've come up with something like this, which should make clear what I want to do, but I'm still a bit new to Python, so I would love a few tips/help on fixing up my code for the task.
# A function to determine if a year is a leap year.
# Do not change this function.
def is_leap_year (year):
    return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)

# You should complete the definition of this function:

 def days_in_month(month, year):

    if month == 'September' or month == 'April' or month == 'June' or month == 'November'
    print 30

    elseif month == 'January' or month == 'March' or month == 'May' or month== 'July' or month == 'August' or month == 'October'\
    or month== 'December'
     print 31

    elseif month == 'February' and output.is_leap_year = True
    print 29

    elseif month == 'February' and output.is_leap_year = False
    print 28

    else print 'Blank'

Ok I've fixed up my code, and it seems to output the correct data for every month but February:
# A function to determine if a year is a leap year.
# Do not change this function.
def is_leap_year (year):
    return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)

# You should complete the definition of this function:

def days_in_month(month, year):

    if month in ['September', 'April', 'June', 'November']:
        print 30

    elif month in ['January', 'March', 'May', 'July', 'August','October','December']:
        print 31

    elif month == 'February' and is_leap_year == True:
        print 29

    elif month == 'February' and is_leap_year == False:
        print 28

Any hints to fix up outputting for February?
EDIT: Just needed to add the argument year when referencing the first function. Here is the 100% working code for future reference:
# A function to determine if a year is a leap year.
# Do not change this function.
def is_leap_year(year):
    return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)

# You should complete the definition of this function:

def days_in_month(month, year):

    if month in ['September', 'April', 'June', 'November']:
        print 30

    elif month in ['January', 'March', 'May', 'July', 'August','October','December']:
        print 31

    elif month == 'February' and is_leap_year(year) == True:
        print 29

    elif month == 'February' and is_leap_year(year) == False:
        print 28

    else:
        return None

A: A more pythonic approach would be to define the mapping in a dictionary, then simply retrieve the values from the dictionary.
Try it out:
days_in_month_dict = {"January": 31, "February": 28,
                      "March": 31, "April": 30,
                      "May": 31, "June": 30,
                      "July": 31, "August": 31,
                      "September": 30, "October": 31,
                      "November": 30, "December": 31}

def is_leap_year(year):
    return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)

def days_in_month(year, month):
    if is_leap_year(year) and month == "February":
        return 28

    try:
        #attempt to get value from dictionary
        return days_in_month_dict[month]
    except KeyError:
        #key does not exist, so we caught the error
        return None

A: Some syntax error in your code:

*

*There should be no space before def days_in_month(month,year). Python use indentation to separate code blocks. This is the error you given in comment.

*There is no elseif in python, it should be elif

*output.is_leap_year = True,  it should be is_leap_year(year) == True. The False part should be changed too.

*after if statement and else there should be a :, like
if month == 'September' or month == 'April' or month == 'June' or month == 'November':
    print 30
elif month == 'January' or month == 'March' or month == 'May' or month== 'July' or month == 'August' or month == 'October' or month== 'December':
    print 31
elif month == 'February' and is_leap_year(year) == True:
    print 29
elif month == 'February' and is_leap_year(year) == False:
    print 28
else:
    print 'Blank'

A: """
Takes the year and month as input and returns the no. of days
"""
def is_leap_year (year):
    return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)

def days_in_month(month, year):
    if month == 'September' or month == 'April' or month == 'June' or month == 'November':
        result=30
    elif month == 'January' or month == 'March' or month == 'May' or month== 'July' or month == 'August' or month == 'October'or month== 'December':
        result=31

    elif month == 'February' and output.is_leap_year ==True:
        result=29

    elif month == 'February' and output.is_leap_year == False:
        result=28
    return result

print(is_leap_year(2016))
print(days_in_month('September',2016))

A: month = int (input ('month (1-12): '))

if month < 13:
    if month == 2:
        year = int (input ('year: '))
        if year % 4 == 0:
            if year % 100 == 0:
                if year % 400 == 0:
                    print ('29')
                else:
                    print ('28')
            else:
                print ('29')
        else:
            print ('28')

    elif month >= 8:
        if month % 2 == 0:
            print ('31')
        else:
            print ('30')

    elif month % 2 == 0:
        print ('30')
    else:
        print ('31')

else:
    print ('Only 1-12 accepted')

A: month=input("month")
year=int(input("year"))
if year%4==0:
        year=('leap year')
if month in ['September', 'April', 'June', 'November']:
        print ("30")

elif month in ['January', 'March', 'May', 'July', 'August','October','December']:
        print ("31")

elif month == 'February' and year == "leap year":
        print ("29")

elif month == 'February' and  year != "leap year":
        print ("28")

else:
    print("none")

A: *# Write a function that determines how many days there are in a particular month.
Your function will have two parameters: The month as an integer between 1 and 12,
and the year as a four digit integer.
Ensure that your function reports the correct number of days in February for leap years.*
def year():
  a = int(input("insert your year"))
  def month():
    z = int(input("enter month 1-12 "))
    if z==9 or z==4 or z ==6 or z==11:
      return print(30)
    elif z==1 or z==3 or z==5 or z==7 or z==10 or z==12:
      return print(31)
    elif z ==2 and a % 4==0:
      return print("29 its a leap year")
    elif z ==2 and a % 4==1:
      return print(28)

  month()
year()


text:
Q: Python packaging: catering to different audiences I'm working on a Python package that consists of a library module and two scripts that use the library. One of the scripts is a command-line tool printing out some text and the other a JSON API server. Both scripts also serve as examples for developers looking to use the library.
Given this situation I see three main audiences or use cases for the package:

*

*Library user: needs the main module. Might want access to the scripts for testing the module and as stubs and examples for their own code.

*CLI user: wants to run the CLI script every now and then. Doesn't need the API server, and probably doesn't care about access to the script source.

*API provider: same as CLI user, but with API server script. Might want the CLI script for quick testing.
Ideally the script users could also choose whether they want to run the scripts directly from a directory or from their $PATH.
How could I structure this properly in a directory tree and in one or more distribution packages (likely using setuptools)?
The current source layout is like this:
main_folder
    README
    setup.py
    mypackage
      __init__.py # contains the library functions
      mymodule.py # link to __init__.py for easy import in the scripts
      cli.py
      api_server.py

A: Here's what I did now.
I browsed PyPI looking for similar packages, then took a look at wikidump's directory structure and its setup.py.
There I found out about the entry_points parameter which allows one to specify module functions that will be converted to scripts at build time. These scripts may also have extra dependencies.
To work with this I converted the respective __main__ blocks into named functions and marked those as entry points. The relevant block (all setuptools.setup() parameters) looks like this:
  [...]
  requires=['pyswisseph', 'numpy'],
  extras_require={'Flask':['flask']},
  entry_points={
      'console_scripts':
          ['cerridwen = cerridwen.cli:main',
           'cerridwen-server = cerridwen.api_server:main [Flask]']
  }
  [...]

Everyone gets the module and scripts, but the optional dependency will be installed only if the script that requires them is run for the first time. The script logic will also be installed as part of the main module so everyone can use their helper functions as needed.
As for having the scripts as examples, I intend to reference their github sources on the project's web site.
The directory structure was left in its original state.
I hope that helps someone else :)


text:
Q: Node exporter is not starting on a linux machine I installed node exporter to a linux machine. When is run the status command it shows error.
sudo systemctl daemon-reload
sudo systemctl start node_exporter
sudo systemctl status node_exporter

 node_exporter.service - Node Exporter
     Loaded: loaded (/etc/systemd/system/node_exporter.service; disabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Thu 2022-10-06 06:39:16 UTC; 7s ago
    Process: 1071861 ExecStart=/usr/local/bin/node_exporter (code=exited, status=1/FAILURE)
   Main PID: 1071861 (code=exited, status=1/FAILURE)

Oct 06 06:39:16 dse-ci-test1 node_exporter[1071861]: time="2022-10-06T06:39:16Z" level=info msg=" - time" source="node_exp>
Oct 06 06:39:16 dse-ci-test1 node_exporter[1071861]: time="2022-10-06T06:39:16Z" level=info msg=" - timex" source="node_ex>
Oct 06 06:39:16 dse-ci-test1 node_exporter[1071861]: time="2022-10-06T06:39:16Z" level=info msg=" - uname" source="node_ex>
Oct 06 06:39:16 dse-ci-test1 node_exporter[1071861]: time="2022-10-06T06:39:16Z" level=info msg=" - vmstat" source="node_e>
Oct 06 06:39:16 dse-ci-test1 node_exporter[1071861]: time="2022-10-06T06:39:16Z" level=info msg=" - xfs" source="node_expo>
Oct 06 06:39:16 dse-ci-test1 node_exporter[1071861]: time="2022-10-06T06:39:16Z" level=info msg=" - zfs" source="node_expo>
Oct 06 06:39:16 dse-ci-test1 node_exporter[1071861]: time="2022-10-06T06:39:16Z" level=info msg="Listening on :9100" sourc>
Oct 06 06:39:16 dse-ci-test1 node_exporter[1071861]: time="2022-10-06T06:39:16Z" level=fatal msg="listen tcp :9100: bind: >
Oct 06 06:39:16 dse-ci-test1 systemd[1]: node_exporter.service: Main process exited, code=exited, status=1/FAILURE
Oct 06 06:39:16 dse-ci-test1 systemd[1]: node_exporter.service: Failed with result 'exit-code'

A: I think you already have prometheus-node-exporter service, try to check your [ipserver]:9100 on your browser, if it shows metric, it means that it's already worked


text:
Q: How to render events by drop, full calendar I am using fullCalendar Scheduler and I am trying to render events based on the place that they are dropped.
So if I drop the event between two other events it should render there and not always at the end of the calendar. I have the drop code here:
drop: function(date, jsEvent, ui, resourceId) {
                console.log("droped");
                var employers = $("#employee_ids").val();
                var emp = [];
                     $('#external-events .fc-event.isOrNotselected').each(function() {
                         var user = $(this)[0].attributes.id.value;
                         var dropedUserId = $(this).context.attributes["data-resourceid"].value;
                         emp.push(dropedUserId);
                         employers = $("#employee_ids").val(emp);
                         [dropedUserId.split('_').length - 1];
                       $('#employee_ids').val(JSON.stringify(sys.workersArray));
                         var fullname = $("#" + user).find(".fullName").text();
                         $('#fullName').val(fullname);
                         $('#user_id').val($("#" + user + " .user_id").text());
                         var profesion = $("#" + user + " .profesion").text();
                         var photoOnDropShift = $(this).find(".innerAvatarUserLeft img").attr('src');
                         $('#profesion').val(profesion);
                         $(".placeholderForMoreWOrkers ").append(
                             '
' +
                             '
' +
                             '

' +
                             '
' + fullname + '
' +
                             '

' +
                             '
' +
                             '
'
                         );
                     });
}

Then it opens a modal where I fill in some information, but the main thing I want is to order the event based on where I drop it.
the code above is executed on drop , the event whose place is taken should not be removed , it should stay there , and with event overlap how am i suppose to do that? the problem that I have is that when I add an event I save it in my database and on success I refetch the calendar events and it should stay on the place that  I dropped and allways event should render based on where are dropped, kind of sorting or something , I use events as users , so if I set one users working day on monday,wednesday and friday , it renders the event in different positions noth in the same row


text:
Q: Is there a print_r or var_dump equivalent in Ruby / Ruby on Rails? I'm looking for a way to dump the structure of an object, similar to the PHP functions print_r and var_dump for debugging reasons.

A: In a view you can use <%= debug(yourobject) %> which will generate a YAML view of your data. If you want something in your log you should use logger.debug yourobject.inspect.

A: You can also use YAML::dump shorthand (y) under Rails console:
>> y User.first
--- !ruby/object:User
attributes:
  created_at: 2009-05-24 20:16:11.099441
  updated_at: 2009-05-26 22:46:29.501245
  current_login_ip: 127.0.0.1
  id: "1"
  current_login_at: 2009-05-24 20:20:46.627254
  login_count: "1"
  last_login_ip:
  last_login_at:
  login: admin
attributes_cache: {}

=> nil
>>

If you want to just preview some string contents, try using raise (for example in models, controllers or some other inaccessible place). You get the backtrace for free:)
>> raise Rails.root
RuntimeError: /home/marcin/work/github/project1
    from (irb):17
>>

I also really encourage you to try ruby-debug:

*

*http://railscasts.com/episodes/54-debugging-with-ruby-debug

*http://www.sitepoint.com/article/debug-rails-app-ruby-debug/

*http://www.datanoise.com/articles/2006/7/12/tutorial-on-ruby-debug
It's incredibly helpful!

A: You can use puts some_variable.inspect. Or the shorter version: p some_variable. And for prettier output, you can use the awesome_print gem.

A: In views:
include DebugHelper

...your code...

debug(object)

In controllers, models, and other code:
puts YAML::dump(object)

Source

A: Prrevious answers are great but if you don't want to use the console (terminal), in Rails you can print the result in the View by using the debug's Helper ActionView::Helpers::DebugHelper
#app/view/controllers/post_controller.rb
def index
 @posts = Post.all
end

#app/view/posts/index.html.erb
<%= debug(@posts) %>

#start your server
rails -s

results (in browser)
- !ruby/object:Post
  raw_attributes:
    id: 2
    title: My Second Post
    body: Welcome!  This is another example post
    published_at: '2015-10-19 23:00:43.469520'
    created_at: '2015-10-20 00:00:43.470739'
    updated_at: '2015-10-20 00:00:43.470739'
  attributes: !ruby/object:ActiveRecord::AttributeSet
    attributes: !ruby/object:ActiveRecord::LazyAttributeHash
      types: &5
        id: &2 !ruby/object:ActiveRecord::Type::Integer
          precision:
          scale:
          limit:
          range: !ruby/range
            begin: -2147483648
            end: 2147483648
            excl: true
        title: &3 !ruby/object:ActiveRecord::Type::String
          precision:
          scale:
          limit:
        body: &4 !ruby/object:ActiveRecord::Type::Text
          precision:
          scale:
          limit:
        published_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter
          subtype: &1 !ruby/object:ActiveRecord::Type::DateTime
            precision:
            scale:
            limit:
        created_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter
          subtype: *1
        updated_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter
          subtype: *1

A: If you just want the relevant data to be displayed to stdout (the terminal output if you're running from the command line), you can use p some_object.

A: The .inspect method of any object should format is correctly for display, just do..
<%= theobject.inspect %>

The .methods method may also be of use:
<%= theobject.methods.inspect %>

It may help to put that in <pre> tags, depending on the data

A: I use this :)
require 'yaml'

module AppHelpers
  module Debug
    module VarDump

      class << self

        def dump(dump_object, file_path)
          File.open file_path, "a+" do |log_file|
            current_date = Time.new.to_s + "\n" + YAML::dump(dump_object) + "\n"
            log_file.puts current_date
            log_file.close
          end
        end

      end

    end
  end
end

A: Lately I'm using awesome_print's ap method which works on the console as well as in views.
The type-specific colored output really makes a difference if you need to visually scan for String or  Numeric objects (Although I had to tweak my stylesheet a little bit in order to get a polished look)

A: Recently I have become a fan of PRY, I've found it incredibly for doing things like inspecting variables, debugging running code and inspecting external code. It might be a little overkill as an answer to this specific question.


text:
Q: react load grid of images based on name I have the following images in a src/assets folder of a React project.
src/assests/
     a.webp
     b.webp
     c.webp

I would like to define a functional component that is a div containing the image corresponding to its name (name is a string).
I can get it to always be 'a'
import a from "./assets/a.webp";

function ImageTile({name}){
    return

}

But if I change it to this to try and be more general then the image doesn't load correctly.
function ImageTile({name}){
    return

}

Even if this did work it seems tedious to have to import every image. I'm happy to save the images somewhere else within the react app directory.
Here is a github gist with a full App.js example if it helps people understand what I am trying to do?
https://gist.github.com/oli5679/96f4549d82b1897a91c2528a4651cd51
I have also tried the approach suggested here, but get an error
function importAll(r) {
    let images = {};
    r.keys().map(item => { images[item.replace('./', '')] = r(item); });
    return images;
}

const images = importAll(require.context('./assets', false, '/\.webp/'));
console.log(images);
# require__(...).context is not a function


text:
Q: Label Text in TextField wont center? I'm attempting to center my labelText in a TextField, but I cannot get it to center for the life of me. Anyone see a glaringly obvious issue that would be causing this? Thanks!
                      Container(
                        width:
                        MediaQuery.of(context).size.width * .85,
                        height:
                        MediaQuery.of(context).size.height * .12,
                        decoration: BoxDecoration(
                            color: Colors.white,
                            border: Border.all(color: Colors.white),
                            borderRadius: BorderRadius.all(
                                Radius.circular(12))),
                        child: TextField(
                          textAlign: TextAlign.center,
                          controller: _notesEditingController,
                          obscureText: false,
                          decoration: InputDecoration(
                              contentPadding: EdgeInsets.symmetric(vertical: 40.0),
                              fillColor: Colors.white,
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.all(
                                    Radius.circular(12.0)),
                              ),
                              labelText: 'notes',
                              labelStyle: TextStyle(
                                color: Color.fromRGBO(105, 105, 105, 10),
                              )),
                        ),
                      ),

A: Please try this, replace labelText and use hintText
Container(
   child: TextField(
     textAlign: TextAlign.center,
     decoration: InputDecoration(
       hintText: 'Center the text',
     ),
   ),
)


text:
Q: express parsing all request to json I am started to implement some API to my marketplace. I am using Shoppy.gg for get some cryptopayments. And i have got a problem about the verify their callbacks from my back end.
In their documentation explain to how validate shoppy with php:
$signature = hash_hmac('sha512', file_get_contents('php://input'), 'secret');
$is_valid = hash_equals($signature, $_SERVER['HTTP_X_SHOPPY_SIGNATURE']);

And i am trying to do it with nodejs express module
  const signature =  req.header('x-shoppy-signature')
  const verifySignature = sha512(JSON.stringify(req), shoppyWebhookSecret)
  if(signature !== verifySignature) return res.json({status: "error", message: "payment-hash-wrong"})

But in my code, ivgot an exception about Converting circular structure to JSON. Am i understand this documentation wrong ? Shouldnt i create sha512 hash from request by using my secret key ?
Edit:
Also i thought maybe it can be gave url encoded string in php and i do it with javascript as coded following:
var verifySignature = sha512(new URLSearchParams(req.body).toString(), shoppyWebhookSecret)

but doesnt works too.
The documentation:
https://shoppy.dev/#/webhooks

A: JSON.stringify(req) is not the equivalent to file_get_contents('php://input'). req is a complex object that cannnot be represented as json. That is why you are getting the error Converting circular structure to JSON.
You need to find the equivalent to file_get_contents('php://input') in node.js. This should be the full request-body.