text:
Q: why we different environments in Anaconda? I am not sure why we need to create a different environment in anaconda? To do that, we have to download some python libraries like matplotlib etc. again in that environment which will consume more drive space? My pc is running out of space. Anyone can help me understand it? Also, how to run the python script file directly under the created anaconda environment in the anaconda terminal? Thanks

A: Anaconda is used to manage different environments which means you can have different versions of python installed on the same computer without having to mix up. For example, if your computer has python 3.8.5 running you can't use a module called TensorFlow. So to use TensorFlow I installed anaconda to manage different versions of python. It depends on you and the reason why you need different versions of python.
Anyways to run a python script using anaconda environment, the steps are below.

*

*Open up your terminal window. Create an environment by typing in conda create -n Stackoverflow python=3.6 You can use any name for your environment instead of Stackoverflow Change 3.6 to your desired version of python.

*After the setup is done. Type in conda activate TensorFlow Replace TensorFlow to your environment name.

*Now navigate to your directory where you have your python file. For example if it is in the desktop, type cd Desktop

*To run the python file simply type python filename.py in your terminal.

A: Yeah, mainly because of version numbers. For example, you might work on a project which uses some code that does not support newer version of some libraries. Then you can account for that.
You can switch the environment in the shell and run the scripts there. More infos about that you can find here.

A: I'd like to add my opinion after deep diving into python.
I have some programming knowledge for the web (HTML, PHP, WordPress, light javascript), and I've only started working with python about a week ago. It was a mess the first few hours—trying installs, things not compatible with OS version, $PATH not always being set correctly, messing with .bash_profile, fighting with pyenv and homebrew. It was maddening. Luckily I stumbled onto Anaconda searching for a replacement to pyenv, which removed 99% of my headaches. Now, I honestly wouldn't want to work with python without Anaconda or something like it to manage envs because of how my productivity skyrocketed.
After an hour or so setting up environments, I had it down. I tested some projects from Github and using anaconda made the entire process fast and easy. Within a minute or two I can download a repo, setup the correct python version, install the dependencies and start using the software. Anaconda makes it fast to set things up so you can get to work. I was able to spend my time learning python and dissecting opensource code instead of battling with pyenv and homebrew and my OS.
Besides that, you don't have to worry about system conflicts as everything is being stored away from your global installs and can easily be copied or shared as yaml files. I've been messing with machine learning, image and audio manipulation, etc. and I really wouldn't want all that stuff globally loaded in my system—not to mention, I'd probably run into tons of problems. This way, it's all quarantined. The only system-wide stuff I install are mandatory things only available through homebrew or manually building them.
And if hard drive space is a problem, invest in more hard drives, especially if you want to get into machine learning or work with graphics and audio. Some of the libraries are large, the data piles up, models can be in the GBs each. You'll have lots of data flying around and you'll need the space. I amassed almost 100GB in the past week, but some I can trash. It's worth it though, because I'm learning and working and getting things accomplished.
Lastly, there was some software not even supposed to work on macOS that I was trying to make work. It worked with Anaconda though. Not sure if it was luck or I just did things right, but there you go.
So what I've found is so great about Anaconda summed up:

*

*Speed of setting up and toggling on and off environments

*Separation of installs from the system while still having access to it

*Ability to have many specific python versions installed

*No conflicts or path problems with python version bundled with OS (like mac)

*Simplicity/flexibilty of installing with conda or pip

*Shorter pip commands (you don't need to use python -m or --user

*If an env goes awry, you can dump it with one command and start fresh

*The ease of setup allows you to focus on learning and coding instead of troubleshooting

The last point is why I really like it. I'm learning python instead of fighting with installations. It's made the experience way more fun and I've learned way more than I could have without it.
YMMV, but I can't see why anyone wouldn't want to use an env management system.


text:
Q: Get value of field from link I have link with onclick function and I need to insert in this event onclick the value of field for send to function I put my little code

<input type="text" name="val_number" id="vals" value=""/>

Add Values

As you can see, I need to get the text insert in val_number for send when onclick - add_values - event it's activate, but doesn't get finally value of field, I don't know however what I write bad.

A: You had some extra quotes in there you don't need:
Add Values

redpajama_set_name: RedPajamaStackExchange


text:
Q: Image rotation and white background in php This is original image:

This is the code I am using:
<?php
$filename = 'image.jpg';
$degrees = 135;

// Content type
header('Content-type: image/jpeg');

// Load
$source = imagecreatefromjpeg($filename);

// Rotate
$rotate = imagerotate($source, $degrees, 1);

// Output
imagejpeg($rotate);

// Free the memory
imagedestroy($source);
imagedestroy($rotate);
?>

This is output:

In this picture background is black. I want to make it white after rotation. Could you help me?

A: please you can change your code just like that
$source = imagecreatefromjpeg($filename);
// Rotate
$transColor = imagecolorallocatealpha($source, 255, 255, 255, 127);
$rotate = imagerotate($source, $degrees,$transColor);

and try this i hope it will help you in color you can change it with any another color code


text:
Q: HtmlUnit - Unable to get anchors from div The divs of the HTML page I am targeting look like this:

// same content as the div above

I want to scrap collect the href in each div in a list.
This is my current code:
List<HtmlAnchor> profileDivLinks = (List)htmlPage.getByXPath("//div[@class='profile']//@href");
for(HtmlAnchor link:profileDivLinks)
{
    System.out.println(link.getHrefAttribute());
}

This is the error I am receiving (which goes on first line of the for statement):
Exception in thread "main" java.lang.ClassCastException: com.gargoylesoftware.htmlunit.html.DomAttr cannot be cast to com.gargoylesoftware.htmlunit.html.HtmlAnchor

What do you think the issue is?

A: The issue is you're getting an attribute and then you're casting that attribute to an anchor. I guess the solution with the minimal change to your code would be just modifying the XPath to return an anchor:
htmlPage.getByXPath("//div[@class='profile']//a");

A: try
//div[@class='profile']//data(@href)


text:
Q: How to Throttle CoreMIDI in Objective-C My CoreMIDI connection on iOS is apparently fast enough to handle ANYTHING that hits it... if I'm just doing some simple object creation and NSLog. In the UI, I don't have time to handle everything that comes in. The UI would blow up, or just finish processing too late.
However, I need to do real processing and UI display in response to CoreMIDI inputs. What I'd like is to process the latest messages every, say, 1ms or 2ms. I've been doing this with a collection that gets emptied by a timer-fired method every 1ms (processFromServerAsync). One problem is that some messages might fall through the cracks, I think, if I grab and substitute:
NSDictionary *queueCopy = [self.queue copy];
// here the dictionary could get messages not in the queue copy!
self.queue = [NSMutableDictionary dictionary];

I realize that I could handle this by synchronizing with a lock, which is easy to screw up:
-(NSMutableDictionary *)messageQueue {
    @synchronized(self) {
        if (!messageQueue_)
            self.messageQueue = [NSMutableDictionary dictionary];
        return messageQueue_;
    }
}

-(NSDictionary*)clearMessageQueueAndReturnCopy {
    @synchronized(self) {
        if (!messageQueue_)
            return [NSDictionary dictionary];
        NSDictionary *retVal = [messageQueue_ copy];
        self.messageQueue = [NSMutableDictionary dictionary];
        return retVal;
    }
}

However, I'm not convinced that I'm even handling this in the correct way. How is throttling typically done (even outside of Obj-C)? I surely cannot process all those messages in the UI nor the program.

A: There are some well-established patterns for throttling streams of incoming data. This comes up a lot in finance, where you might have a data feed throwing 100K messages/sec at a system.
You employ a sliding window mechanism to discard redundant messages while ensuring that the client has the latest possible copy of the data. You set your window up over some time period (a few milliseconds) then set up a queue for each data stream (meaning a particular CC, midi note etc.) You start a global timer when the first message comes in. You send that message to the client immediately. If anything else comes in during the window you push it to its queue. The queue has just one entry - the latest value - so you overwrite the queued value with each subsequent update. When the timer ticks (the window is over) you send the latest message out to the client. Then, you send the next message out as soon as it comes in, start a new window and repeat. This gives a reasonable balance between swamping the client and avoiding aliasing of update intervals to the timer window. Aliasing is less of an issue with 1-2ms intervals so a cruder rigid timer approach might work for you.
The critical thing is ensuring that you have separate windows for each data stream. You can't risk overwriting or ignoring, say, a note off because a control change came in. One timer, one single-entry queue per Midi message number.


text:
Q: How to fill in missing values to show age at a specified date I am looking to find the age of a person when comparing multiple different dates in years. I have the persons age on their first record at a specific date but I want to find their age at multiple following dates in years.
My dataframe is something like this
data;
input ID date age ;
dataline;
1  10/27/2004   21
1  02/04/2006   .
1  12/08/2009   .
2  07/25/2007   24
2  08/31/2008   .
2  08/27/2012   .
run;

I tried this but it rearanged my data & only added to the first age variable of each ID. I thought of maybe using RETAIN as well but did not have any luck using that either.
data want;
set have;
by age;
if first.id then age1=first.date-date+first.age;
run;

A: Instead of trying to calculate the age dependent on previous values I would recommend calculating the birth_year and using that going forward.
Use RETAIN to hold the birth_year across the rows and then use it to calculate the age when age is missing.
data have;
    input ID date : mmddyy10. age;
    format date date9.;
    datalines;
1  10/27/2004   21
1  02/04/2006   .
1  12/08/2009   .
2  07/25/2007   24
2  08/31/2008   .
2  08/27/2012   .
;
    ;
    ;;
run;

data want;
    set have;
    by id;
    retain birth_year;

    if first.id then
        birth_year=year(date) - age;

    if missing(age) then
        age=year(date) - birth_year;
run;

FYI your data step doesn't run as posted. Please test it before posting.


text:
Q: Simulate Exception in Environment.Exit A production console application that is shut down via Environment.Exit(0) every night prior midnight, occasionally experiences an exception during .Exit() which leaves the console application hanging, with an "Application has stopped working" screen.
This causes the process not to clean up properly and a relaunch after midnight fails because the prior process is still lingering.
Since I couldn't pin down what causes the exception in Environment.Exit, I'd like to at least handle it gracefully when it occurs and ensure that the process shuts down entirely. To do that, I'd like to simulate a crash after .Exit() but I wasn't able to find a scenario yet that would produce an exception during .Exit().
Does anyone have an idea how an exception during Environment.Exit could be simulated?

A: Sure, it's easy enough to duplicate:
private static void Main()
{
    try
    {
        new ItsATrap();
        Environment.Exit(0);
    }
    catch (Exception ex)
    {
        Console.WriteLine("During exit: {0}", ex);
    }
}

private class ItsATrap
{
    ~ItsATrap()
    {
        throw new InvalidOperationException("Ooops!");
    }
}

Note that the During exit text is never printed in the example above.
You can catch unhandled exceptions by installing a handler like this:
AppDomain.CurrentDomain.UnhandledException += (sender, args)
    => Console.WriteLine("Unhandled: {0}", args.ExceptionObject);

This way you have an opportunity to log them.
So... check your finalizers to see if they can throw.
Also, make sure they don't use other managed resources, as the finalization order isn't deterministic. As usual, Eric Lippert has some good articles to read on the subject.

A: You have an XY-problem here. You want to simulate an exception because you have no idea what else you could do. Instead of simulating something you don't exactly know, you should try to find out the real cause of the issue and fix it.
Collect a crash dump (MSDN) and load it into Visual Studio. As long as it's somewhere in your C# code, it should show you the line number.
See also: How do I take a good crash dump for .NET? here on Stack Overflow.
Modifying your code as proposed in other answers may change the timing and could just make the exception less likely or occur in different positions. Be happy that you can reproduce the problem and fix it instead of diluting it.

A: Use of a disposed/finalized object can probably cause it. This happens because there is no fixed order for finalization, so for example an hand-made logger that tries to write something on a Stream that has been finalized will cause an exception (hand made because "professional" loggers know of this :-) ).
You could try installing a first-chance exception handler just before calling the Environment.Exit that logs every exception that happens during this time. Something like:
object lck = new object();
AppDomain.CurrentDomain.FirstChanceException += (sender, e) =>
{
    lock (lck)
    {
        File.AppendAllText("log.txt", string.Format("{0}: {1}", DateTime.Now, e.Exception.ToString()));
    }
};

Environment.Exit(0);


text:
Q: Mosquitto broker not functioning with all configurations I did the following changes in mosquitto.conf
password_file "\etc\mosquitto\passwordfile.txt"
allow_anonymous false

But still when i send the command
mosquitto_pub -u admin -P (wrong password) -m "1" -t "topic"

and
mosquitto_sub -u admin -t "topic"

I am still receiving, at the broker the message I am publishing. Should that be NOT happening?
i created the password file using
mosquitto_passwd -c "etc\mosquitto\passwordfile.txt" admin

I am getting a feeling I am doing a very silly mistake. But just cant put a finger on it


text:
Q: Backbone app not initializing on production I have a Backbone (1.1.0) on Rails (4.1.0) app using RequireJS (requirejs-rails gem) that works fine on my local machine. But when I precompile assets and start the server, the Backbone app, having been compiled/compressed by r.js, does not start. No errors are thrown anywhere. Here are some snippets:
requirejs.yml
paths:
    jquery: "jquery/jquery"
    underscore: "underscore/underscore"
    backbone: "backbone/backbone"
    "jquery-mobile": "jquery-mobile-bower/js/jquery.mobile-1.4.2.min"
    tpl: "requirejs-tpl/tpl"
    "backbone-query-parameters": "backbone-query-parameters/backbone.queryparams"
    serializeJSON: "jquery.serializeJSON/jquery.serializejson"
    "jqm-config": "jqm-config"
    fastclick: "fastclick/lib/fastclick"

shim:
    "backbone-query-parameters":
        deps: ['backbone']
    'jqm-config':
        deps: ["jquery-mobile"]
    'jquery-mobile':
        deps: ["jquery"]

modules:
  - name: 'application' # default

tpl:
    extension: '.html' # default

application.js
define(["backbone", "./router", "jquery-mobile", "jqm-config", "fastclick"],
function(Backbone, Router) {

var BackboneApp = {

    start: function() {
        this.router = new Router();
        Backbone.history.start();
    }
};

return BackboneApp.start();
})

application.html.erb
<!DOCTYPE html>
<html>
<head>
  <title></title>
  <%= stylesheet_link_tag "application", :media => "all" %>
  <%= csrf_meta_tags %>
</head>
<body>
    hello
    <%= yield %>
<%= requirejs_include_tag "application" %>
</body>
</html>

Here's my server logs:
18:57 $ RAILS_ENV=production rails server
=> Booting WEBrick
=> Rails 4.1.0 application starting in production on http://0.0.0.0:3000
=> Run `rails server -h` for more startup options
=> Notice: server is listening on all interfaces (0.0.0.0). Consider using 127.0.0.1 (--binding option)
=> Ctrl-C to shutdown server
[2014-05-06 19:04:01] INFO  WEBrick 1.3.1
[2014-05-06 19:04:01] INFO  ruby 2.1.1 (2014-02-24) [x86_64-darwin12.0]
[2014-05-06 19:04:01] INFO  WEBrick::HTTPServer#start: pid=60796 port=3000
Started GET "/" for 127.0.0.1 at 2014-05-06 19:04:03 -0500
Processing by MainController#index as HTML
  Rendered main/index.html.erb within layouts/application (1.4ms)
Completed 200 OK in 16ms (Views: 13.3ms | ActiveRecord: 0.0ms)

and just to clear up any confusion, here's the html that loads:
<!DOCTYPE html>
<html>
<head>
  <title></title>
  <link href="/assets/application-34af7785e9260ce67d287c5a05fc3583.css" media="all" rel="stylesheet" />
  <meta content="authenticity_token" name="csrf-param" />
  <meta content="MjhW2IjblGRfvIsAq/hphJT/WlFckUsQ/jSv8skdysk=" name="csrf-token" />
</head>
<body>
  hello

   <script>var require = {"baseUrl":"/assets","paths":{"application":"/assets/application-4d1052c11b8765cc7707a5f8643e33bf"},"priority":["application"],"shim":{"backbone-query-parameters":{"deps":["backbone"]},"jqm-config":{"deps":["jquery-mobile"]},"backbone":{"deps":["underscore","jquery"],"exports":"Backbone"}}};</script>
   <script data-main="application-4d1052c11b8765cc7707a5f8643e33bf" src="/assets/require-e48b9057622ee54d9d9b4dd773d4f295.js"></script>

</body>
</html>

I am guessing that the mistake is in either how I initialize my app in application.js or in the config in requirejs.yml, but I just can't solve it.

A: Solved in this issue. Used a require call instead of a define call in my top-level javascript (application.js)


text:
Q: nearest timestamp price - ready data structure in Python? Price interpolation. Python data structure for efficient near miss searches?
I have price data
[1427837961000.0, 243.586], [1427962162000.0, 245.674], [1428072262000.0, 254.372], [1428181762000.0, 253.366], ...

with the first dimension a timestamp, and the second a price.
Now I want to know the price which is nearest to a given timestamp e.g. to 1427854534654.
What is the best Python container, data structure, or algorithm to solve this many hundred or thousand times per second? It is a standard problem, and has to be solved in many applications, so there should be a ready and optimized solution.
I have Googled, and found only bits and pieces that I could build upon - but I guess this question is so common, that the whole data structure should be ready as a module?

EDIT: Solved.
I used JuniorCompressor's solution with my bugfix for future dates.
The performance is fantastic:
3000000 calls took 12.82 seconds, so 0.00000427 per call (length of data = 1143).
Thanks a lot! StackOverFlow is great, and you helpers are the best!

A: It is very common for this problem to have your data sorted by the timestamp value and then binary search for every possible query. Binary search can be performed using the bisect module:
data = [
    [1427837961000.0, 243.586],
    [1427962162000.0, 245.674],
    [1428072262000.0, 254.372],
    [1428181762000.0, 253.366]
]

data.sort(key=lambda l: l[0]) # Sort by timestamp
timestamps = [l[0] for l in data] # Extract timestamps

import bisect

def find_closest(t):
    idx = bisect.bisect_left(timestamps, t) # Find insertion point

    # Check which timestamp with idx or idx - 1 is closer
    if idx > 0 and abs(timestamps[idx] - t) > abs(timestamps[idx - 1] - t):
         idx -= 1

    return data[idx][1] # Return price

We can test like this:
>>> find_closest(1427854534654)
243.586

If we have n queries and m timestamp values, then each query needs O(log m) time. So the total time needed is O(n * log m).
In the above algorithm we search between two indexes. If we use only the midpoints of the timestamp intervals, we can simplify even more and create a faster search:
midpoints = [(a + b) / 2 for a, b in zip(timestamps, timestamps[1:])]
def find_closest_through_midpoints(t):
    return data[bisect.bisect_left(midpoints, t)][1]

A: Try this to get nearest value
l = [ [1427837961000.0, 243.586], [1427962162000.0, 245.674], [1428072262000.0, 254.372], [1428181762000.0, 253.366]]
check_value = 1427854534654
>>>min(l, key=lambda x:abs(x[0]-check_value))[0]
1427837961000.0

A: Solved!
I used JuniorCompressor's solution with my bugfix for future dates.
The performance is fantastic:
3000000 calls took 12.82 seconds, so 0.00000427 per call (length of data = 1143).
Thanks a lot! StackOverFlow is great, and you helpers are the best!


text:
Q: Why doesn't this command fill a 4x4x4 area with ice after a splash potion flies out? I've got this "magic" system in place where if I throw the right thing, it turns into lightning or fire. I'm trying to make an ice-element trap like this:
/execute at @e[type=potion] if entity @p[distance=3..5] positioned as @p run fill ~2 ~2 ~2 ~-2 ~-2 ~-2 ice

It's throwing a splash potion that shatters harmlessly on the ground.
Intended effect: I throw it, it gets a few blocks from me, then turns into a 4x4x4 block of ice.
It's doing nothing.
What am I doing wrong?
I'm using repeat command blocks to run that. Ver. 1.14.2

A: Your command works for me, but it does not do what you intend it to do.
Make sure that it is in a repeating command block and that the command block is actually loaded, it may have to be powered by redstone depending on how you set it up. Please give some more details about your problem if this does not help.
Altering the command does make it work the way you explained, as long as you are in a single player world and the potion actually gets far enough.
/execute at @e[type=potion] if entity @p[distance=3..5] run fill ~2 ~2 ~2 ~-2 ~-2 ~-2 ice

It may not always work as intended if you have multiple players in your world at the same time, in that case I would suggest a two commands solution like this:
/execute as @e[type=minecraft:potion,nbt={PortalCooldown:0}] run data modify entity @s PortalCooldown set value <time>
/execute at @e[type=minecraft:potion,nbt={PortalCooldown:1}] run fill ~2 ~2 ~2 ~-2 ~-2 ~-2 minecraft:ice

I set time to 10, it works quite well for me, but you may want it to fly for longer, or shorter
This solution is time based, so it is not affected by how many players are online. I am not sure if it works with lag though. You will not be able to throw the potion into another dimension through a portal, because this command uses the portal cooldown to keep track of time.
Neither of these solutions do anything if the splash potion breaks before the effect takes place (if the potion is not far enough away from you in the first case, or if it breaks too early in the second case)
Note: This part (~2 ~2 ~2 ~-2 ~-2 ~-2) specifies a 5x5x5 volume and not 4x4x4
Note 2: The potions will set everything close to it to ice, so it may potentially break barriers, bedrock, or any decoration that you may have. You can change that by putting replace air after the fill command. Doing this will prevent it from setting grass to ice though and it will not work under water anymore, so it may not always work in those situations.
/execute at @e[type=potion] if entity @p[distance=3..5] run fill ~2 ~2 ~2 ~-2 ~-2 ~-2 ice replace air

Note 3: Throwing the potion directly at your target may break it, before it "explodes", making it uneffective


text:
Q: Deleting controls each time ShowDialog is called I have a form that I display exclusively with the ShowDialog method. In the Form_Shown event, I dynamically create a set of labels and text boxes based on a public variable set in the form making the call.
I understand that the form is not closed or destroyed but simply hidden between calls, and as such I added code at the top of my Form_Shown event to clear out any controls from a previous call, but the controls aren't being removed. I have tried ctrl.Dispose (as in the code below) and Me.Controls.Remove(ctrl). Neither produces an error, but the Textboxes are not removed and new ones are created over them. (For some reason,
This is the first time I've dynamically created/removed controls in .NET, so it's possible my yearning for VB6's control arrays have something to do with the error.
The form builds itself based on the calling form's public ListView variable. The calling form makes certain this variable is not nothing and that items are selected if and only if the user is editing an existing row.
Public Class frmTableEdit

Private isNew As Boolean
Private inputText() As TextBox

Private Sub FormTableEdit_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
    For Each ctrl As Control In Me.Controls
        If TypeOf (ctrl) Is TextBox Or TypeOf (ctrl) Is Label Then
            ctrl.Dispose()
        End If
    Next
    With frmKioskData.TBLobj
        Dim fieldCount As Integer = .Columns.Count - 1
        isNew = .SelectedIndices.Count = 0

        '(code setting size of form and location of OK/Cancel buttons is here)

        ReDim inputText(fieldCount)
        For i As Integer = 0 To fieldCount
            Dim lbl As New Label, txt As New TextBox
            inputText(i) = txt
            Me.Controls.Add(lbl)
            Me.Controls.Add(txt)

            '(code setting size and and position of lbl & txt is here)

            'lbl.Tag = i    (I commented these lines out because I never used the
            'txt.Tag = i    Tag property, but can if a solution calls for it.)

            lbl.Text = .Columns(i).Text
            If isNew Then
                txt.Text = ""
            Else
                txt.Text = .Items(.SelectedIndices(0)).SubItems(i).Text
            End If
        Next
    End With
End Sub

End Class

A: If @Plutonix's suggestion in the comment above does not quite work for you, I think it would be easiest and make more sense to dispose of the form after calling ShowDialog, and then when you need to show that form you create a new instance with a parameter that tells it what dynamic controls to load.
So you'd have a New method in frmTableEdit that uses this parameter:
Public Sub New(ByVal fieldCount As Integer)
        InitializeComponent()
        fieldCount = fieldCount  'Where fieldCount is a class variable
End Sub

And when you call this form from frmKioskData, you can do so like this:
Dim newTableEdit As New frmTableEdit(Me.TBLobj.Columns.Count - 1)
newTableEdit.ShowDialog()
newTableEdit.Dispose()

Then the code in your frmEditTable's Shown event just simply has to add the controls accordingly, without the need to remove old ones:
ReDim inputText(fieldCount)
For i As Integer = 0 To fieldCount
    Dim lbl As New Label, txt As New TextBox
    inputText(i) = txt
    Me.Controls.Add(lbl)
    Me.Controls.Add(txt)

    '(code setting size and and position of lbl & txt is here)

    'lbl.Tag = i    (I commented these lines out because I never used the
    'txt.Tag = i    Tag property, but can if a solution calls for it.)

    lbl.Text = .Columns(i).Text
    If isNew Then
        txt.Text = ""
    Else
        txt.Text = .Items(.SelectedIndices(0)).SubItems(i).Text
    End If
Next

How you get the isNew value is up to you - you can add that as a second parameter to the form's New, or get it the same way you are now...w/e.  If it were me I'd normally add that as another New parameter.


text:
Q: Shift operation returning weird error I'm programming a plc by ABB in the codesys environment, and I can't figure out why I'm getting this error:
Error 4024: ... Expecting ELSIF,  ELSE or END_IF before 'SHL'

The code returning this error is something like:
IF flag THEN
    iState := 0;
    Step := false;
    SHL(1,iReg);
END_IF

Basically two assignments and a shift left operation on an unsigned integer. The shift is what gives the error, and commenting the line eliminates it.
I've checked the syntax many times, also inverted the arguments a few times following contradicting documentation.
Can anyone tell me what I'm missing?

A: your SHL needs to have a result
IF flag THEN
    iState := 0;
    Step := false;
    result := SHL(1,iReg);
END_IF


text:
Q: Mongoose Performance issues I'm staring having issue with mongoose at high concurrency,
in this case:
mock.js  send a lot (10K per sec) data via socket.io to the server
server.js receive and process them, call db.js to save it (async)
db.js storage processed data to mongodb via mongoose (insert only)
first, I started the server, and try to do some load test by mock.js,
Normally, mongoose will create hundreds of connections to mongodb, with about 9K insert operations.
However, the situation I met was:
Mongodb will not react during the load test. It only has dozens of inserts and about 10 connections.
After the load test is canceled (stop sending data), the number of inserts and connections of mongodb will soar instantly until the execution is completed.
If the load test is not canceled, mongodb will not be loaded until server.js meets OOM


text:
Q: LocalDate pattern that shows day as weekday I search for a pattern which looks like this: Thu, 11. 05. 1999
So I tried this syntax:
String pattern = "DDD, dd. mm. uuuu";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);

But it won't work. When trying to format a LocalDate I get java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: MinuteOfHour.

A: A look into the official documentation of Java explaining the format pattern syntax is always good:

*

*E = day-of-week

*M = month

*m = minute

So you should try this pattern:
EEE, dd. MM. uuuu

And setting the locale explicitly to English is also a good idea.


text:
Q: How does App Store "complete my bundle" work when I've spent more than the bundle cost? I have bought the Hitman app for $4.99. When I checked for the app bundle, it says GET. Does this mean that the bundle is free, or do I still have to pay for it?

A: Since you've already paid more for one app than the total cost of the bundle, you get the rest of the bundle for free. This is why it says GET without a price.
If you had to pay anything, it would show you a price instead. For instance, in my case I see $3.99 where you see GET.
iTunes albums work the same way. Every time you purchase a track on an album, the cost to complete the album goes down, as reflected on the Purchase button. If the cumulative cost you've paid for the tracks on an album exceeds the cost of the album as a whole, the button changes to GET and you can download the remaining tracks "for free."


text:
Q: How to do syntax analysis of a c code in c programming language? The lexical analysis of the c code is done and the tokens are obtained. How to do the syntax analysis of the same code in c language?

A: Try these tutorial links:
http://www.pling.org.uk/cs/lsa.html
http://www.c4learn.com/c-programming/syntax-analysis/
https://www.tutorialspoint.com/compiler_design/compiler_design_syntax_analysis.htm
i hope it will help you!


text:
Q: Why did emacs doesn't have scroll one line keybinding? I am switching from vim to emacs. I have been using vim for two years, so when i editing with emacs i always thinking about the way i used with vim.
Vim got quite a few keybinding to scroll buffer, one line, half screen, page up and so on. But emacs can only scroll a page with CTRL-V. Yes, i can define a custom keybinding to scroll one line by myself easily, but what i thinking now is whether i should do this. If it is a really necessary fundamental keybinding, then emacs must got by default.
Don't you feel getting lost where the line is when you enter CTRL-V

A: If you feel lost, try setting scroll-preserve-screen-position to 1:
(setq scroll-preserve-screen-position 1)

You can either add that line to your init file to make it permanent or press M-: and enter it at the prompt to try it out in the current session.
Also, if you find yourself missing vim a lot in general, you can always use e.g. evil-mode. Remember, though, that emacs is not vi, and if you really want to switch and use it as your main editor you will only benefit if you stop thinking too much about what you are used to doing in vim.

A: I think you want to try CTRL-N.

A: You can also scroll using a mouse wheel. Depending on your settings for that, it can easily scroll one line at a time. Just another possibility to mention.


text:
Q: interrupt oracle query with Oracle data access client I want to kill oracle query after 10 mins of its execution through c#, I achieve it by using Oracle.ManagedDataAccess.Client.dll, but my existing project is using System.Data.OracleClient.dll in which cmd.CommandTimeout is not updating on runtime see here. I searched alot but couldn't find anything, Its not logical to switch to new dll on which whole project is relying. Is there anything that can be done to update/set CommandTimeout in System.Data.OracleClient.dll.
Below code is with System.Data.OracleClient;
string connString = "Data Source=xx; User ID=xx; Password=xx;";
var conn = new OracleConnection(connString);
var cmd1 = new OracleCommand(cmdString1, conn);

cmd1.CommandTimeout = 6;

conn.Open();

try
{
    cmd1.ExecuteNonQuery();
}
catch (Exception exception)
{

}

cmd1.CommandTimeout remains 0 even after code execution. Below is with Oracle.ManagedDataAccess.Client;
string connString = "Data Source=(DESCRIPTION=xxx); User Id=xx; Password=xx;";

conn = new OracleConnection(connString);
var cmd1 = new OracleCommand(cmdString1, conn);
cmd1.CommandTimeout = 6;

conn.Open();

try
{
    cmd1.ExecuteNonQuery();
}
catch (Exception exception)
{
}

this code is killing the query but I cant use this dll.


text:
Q: Interpreting the effects of dummy interactions Warning
This question is quite long, and maybe a lot of you will think it is too long. I however thought, and hope, that if this question gets a proper answer, it will actually be a really good post to help people with getting a quite comprehensive understanding of the slightly more advanced workings of dummy variables. Related to this, please feel free to edit this question if you think some parts could be made clearer.
Background
Although I think I am getting quite up to standards when interpreting dummy interaction effects, I always get confused in some situations. For example when trying to control for a sample imbalance. Added because of a question in the comments: The problem with the sample imbalance that I perceive, is that because I have substantially more females in my sample. I am worried that the effects that I pick up (not only for the treatment, I just wanted to not over-complicate the example), are not purely attributable to the variables I include, but also to potential confounding characteristics which are more present in the female subsample.
In this example, there are three types of variables:

*

*Choice, a dummy variable, which is the dependent variable in all regressions.

*treatment, a dummy variable (treatment = 1, control = 0)

*Gender, a dummy variable (Male or Female)

.
one <- glm(Choice ~ as.factor(gender), family = binomial(link=logit), data=data)
two <- glm(Choice ~ as.factor(treatment), family = binomial(link=logit), data=data)
three <- glm(Choice ~ treatment + as.factor(gender), family = binomial(link=logit), data=data)
four <- glm(Choice ~ as.factor(gender):as.factor(treatment), family = binomial(link=logit), data=data)
five <- glm(Choice ~ as.factor(gender):as.factor(treatment) +  as.factor(gender), family = binomial(link=logit), data=data)
six <- glm(Choice ~ as.factor(gender)*as.factor(treatment), family = binomial(link=logit), data=data)
====================================================================================================
                                                             Dependent variable:
                                         -----------------------------------------------------------
                                                                   Choice
                                            (1)       (2)       (3)       (4)       (5)       (6)
----------------------------------------------------------------------------------------------------
treatment                                                     0.200*
                                                              (0.120)

Male                                     -0.340***           -0.340***            -0.140    -0.140
                                          (0.120)             (0.120)             (0.170)   (0.170)

as.factor(treatment)1                               0.200*                                  0.350**
                                                    (0.120)                                 (0.140)

Female:as.factor(treatment)0                                            0.210
                                                                        (0.170)

Male:as.factor(treatment)0                                               0.077
                                                                        (0.200)

Female:as.factor(treatment)1                                            0.570***   0.350**
                                                                        (0.180)   (0.140)

Male:as.factor(treatment)1                                                        -0.077    -0.430*
                                                                                (0.200)   (0.240)

Constant                                 -0.210*** -0.420*** -0.300*** -0.590*** -0.380*** -0.380***
                                          (0.071)   (0.080)   (0.090)   (0.140)   (0.099)   (0.099)

----------------------------------------------------------------------------------------------------
Observations                               1,242     1,242     1,242     1,242     1,242     1,242
Log Likelihood                           -840.000  -843.000  -839.000  -837.000  -837.000  -837.000
Akaike Inf. Crit.                        1,685.000 1,690.000 1,684.000 1,683.000 1,683.000 1,683.000
====================================================================================================
Note:                                                                    *p<0.1; **p<0.05; ***p<0.01

My understanding
Regression 3: I know that normally, adding a dummy, causes an intercept change, between the base group (treatment=0). However, my experiment had a gender imbalance, so I wanted to correct for that, adding a gender dummy. Now I started to doubt the interpretation. To check, I ran the regression once with only with the gender and once with only the treatment, once with both. Since the coefficients do not change, I have to assume that BOTH dummies signify independent intercept changes. So actually I am in no way controlling for the gender imbalance.
Regression 4: Here I only interacted the gender with the treatment. As there is no coefficient on as.factor(gender)2:as.factor(treatment)1, I assume that this is the base level, which I believe means that all other coefficients are the interaction effects, compared to the base level. Thinking about this, I realised this is super uninformative, because if I understand correctly, it says nothing anymore about the effects on Choice, just how one compares to the other.
Regression 5: Compared to regression (4), I now added a separate gender dummy. It now seems that I have what I want, because I get a treatment effect for men and a treatment effect for women. The gender dummy, if I understand correctly, now simply gives me the difference between men and women for the non treatment group.
Regression 6: I thought I would get the most information by interacting the dummmies, and also add them separately, but I think this does not work, because there are only 6 different groups. The treatment effect for men in this regression is I believe, the treatment effect plus the treatment interaction, which coincides with the effect of as.factor(gender)2:as.factor(treatment)0 in regression 4.
My questions

*

*Are my interpretations above correct?

*Am I correct in saying that only regression (5), gives me the treatment effect, corrected for the sample imbalance? If so, why did it necessitate me to add a separate gender dummy?

*Which variable/interaction, tells me whether the difference in treatment effect between men and women is significantly different? Do I need to run even another regression for this?

A: I will try to answer your question, feel free to comment if somthing is unclear or i have misunderstood you.
1) to your question: Are my interpretations above correct?
I will try to go trough the models one at a time, rather than answer wit a simple yes or no.
Lets look at model 1.
one <- glm(Choice ~ as.factor(gender), family = binomial(link=logit), data=data)

To be sure we are on the same understanding, this is the same model as
one <- glm(Choice ~ gender, family = binomial(link=logit), data=data)

When gender is a string variable. R will make sure the interpretation is correct. Below I will omit the as.factor() function if reasonable to simplify the answer.
Model one is a simple model investigating the association between an outcome Choice and the gender gender. The coefficient estimate for gender, -0.340 indicates how much the probability of Choice=1 for males diverge (in this case decrease) from females. Of cause in this model we ignore any other variables that may influence the association between gender and Choice.
In conclusion, model 1 allow us to test and interpretant the crude relation between Choice and gender.
If you are not with me so far, try to look up simple models. Otherwise lets look at model 2.
two <- glm(Choice ~ treatment, family = binomial(link=logit), data=data)

Model 2 is very similar to model 1. Only this time instead of association between Choice and gender, we now look at the relation of Choice and treatment. The above should allow you to extend to this case.
So far so good, lets move to model 3.
three <- glm(Choice ~ treatment + gender, family = binomial(link=logit), data=data)

Say we are interested in the treatment effect on Choice, but we know that gender will affect both the Choice and treatment. Then gender is a so called confounder. I expect this is indirectly what you mean when you talk about imbalance. You expect that gender may influence the model result.
The output here will give an estimate for both gender and treatment. If we are only interested in the effect of treatment on choice, we would ignore the coefficient estimate for gender and only look at the estimate for treatment. Thus we can check if treatment has an effect on the choice, when correcting/adjusting for gender.
Are we on the other hand interested in the effect of gender, we would consider the estimate for gender and ignore the treatment effect. Thus we would get the effect of gender on choice when we correct for treatment.
I model 3 have no interaction-term, that is we assume that the treatment influence the choice in an equal manner for both men and women. Or vice versa if we switch treatment and gender.
So lets consider an interaction term. Model 4 is not actually reasonable because it only ad the cross term between gender and treatment but dont allow a separate effect. If this is new to you, I suggest you learn about interaction models. The internet should help you here.
The same goes for model 5. Since only one of the terms gender or treatment is allowed to have a separate effect.
So let's look at model 6.
six <- glm(Choice ~ gender*treatment, family = binomial(link=logit), data=data)

Model 6 is equivalent to the model
six <- glm(Choice ~ gender+treatment+gender:treatment, family = binomial(link=logit), data=data)

Shortly it asks the program to model the effect of treatment (or gender) on Choice when corrected for gender (or treatment) and the treatment(gender) effect is allowed to vary across levels of gender (treatment).
Forget interpretation of the value of the coefficients, this usually lead to confusion. Focus on the interaction term gender:treatment. If it influence the choice significantly, a cross effect exists.
This should also answer question 2)
3) Which variable/interaction, tells me whether the difference in treatment effect between men and women is significantly different? Do I need to run even another regression for this
The interaction term should tell you this.


text:
Q: swift 4 timeIntervalSinceReferenceDate instead of actual date string after JSONSerialization i have an object which i set the value of date like this
notificToSubmit.NotificDateCreated = Date()
notificToSubmit.NotificOccDateTime = dtPicker.date

Now I want to send my object to my api using ALAMO fire. I need to convert it to JSONObject. Which would look something like this:
let data = try! JSONEncoder().encode(notifToSubmit)
let jsonD = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)

All is good but its giving me the wrong date value.
It gives me the timeIntervalSinceReferenceDate instead of the actual date value:
(2 elements)
  - key: NotificDateCreated #1
    - super: NSMutableString
      - super: NSString
        - super: NSObject
  - value: 552834752.59258 #2
    - super: NSNumber
      - super: NSValue
        - super: NSObject

instead of
NotificDateCreated: 2018-07-09 13:12:32 +0000
NotificOccuredDateTime: 2018-07-09 13:12:28 +0000

and yes I know, that the number which is 552834752.59258 is a valid date valid, but the API doesnt recognize it.
Any Ideas how I can get the actual date which is 2018-07-09 13:12:32 after JSONSerialization

A: If you need a string representation of a date you can pass a custom date encoding strategy to the encoder for example
struct Foo : Codable {
    let date : Date
}

let foo = Foo(date: Date())

let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .formatted(formatter)
do {
    let data = try encoder.encode(foo)
    print(String(data: data, encoding:.utf8)!) // {"date":"2018-07-10 10:44:16"}
} catch {
    print(error)
}

A: Leaving this here for the Google Code Warriors - Alamofire 5:
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = JSONEncoder.DateEncodingStrategy.iso8601
AF.request(api, method: httpMethod, parameters: encodableRequestData, encoder: JSONParameterEncoder.init(encoder: encoder))

This will encode any Date fields in your encodableRequestData to iso8601 strings.  You can choose other DateEncodingStrategies as well or make your own


text:
Q: Periodicity of the triginometric function $g(x) = \sin\Big(2 \pi b (x-a) \cos\big(2 \pi c (x - a) \big)\Big) + d$ I have a trigonometric function and I'm interested to know whether or not it has a period. At this stage I'm fairly certain that it is not periodic. However, I don't know how to prove it. Can anyone help?
This is the function:
$$g(x) = \sin\Big(2 \pi b (x-a) \cos\big(2 \pi c (x - a) \big)\Big) + d$$
Thanks

A: Substitute $\xi=2\pi(x-a)$ and set $d=0$ w.l.o.g, then your period $T$ should satisfy
$$\sin[(\xi+T)b\cos((\xi+t)c)]=\sin[\xi b \cos(\xi c)]$$
i.e. for $bc\neq 0$ the arguments must differ by an integer multiple of $2\pi$ for all $x$:
$$(\xi+T)b\cos(\xi x+Tc)=\xi b \cos(\xi c) + 2\pi k(x)$$
with some function $k(x)\in\mathbb{Z}$. As this function has to be smooth and is restricted to $\mathbb{Z}$, it must be constant and you get
$$\xi \cos(\xi c + Tc)+T\cos(\xi c +Tc)=\xi\cos(\xi c)+2\pi k,\qquad \forall \xi.$$
This is obviously not possible for $T\neq 0$.
Edit: Of course as mentioned, the specific case $bc=0$ has to be excluded.

A: In some cases the function is periodic. Specifically, if $c=0$ and $b\neq 0$, the function has period $\frac1b$.


text:
Q: value is not displayed when enter the value to the text box This is works fine when the form does not have any value. But, Once i entered the value on the textbox, it still alert the same messages i.e it is omitting 'You must enter value' for both cases,see at the if else statement. what is the mistake on the below code?
<!doctype html>

        <title>A Basic Example</title>

A Basic Form Example

        <form action="#">

Name (Required): <input id="textbox1" name="textname" type="text" />

<input id="submitbutton1" type="submit" />

        </form>

A: You are fetching the length of the value when the page loads instead of when the the function runs.
Move
var item = document.getElementById("textbox1").value.length

inside the function.

A: Use this syntax in addEventListener  formEl.addEventListener("click", formValid,false);
Also replace var item inside the function formValid().
Here is the fiddle

A: try this

<!doctype html>

            <title>A Basic Example</title>

A Basic Form Example

            <form action="#">

Name (Required): <input id="textbox1" name="textname" type="text" />

<input id="submitbutton1" type="submit" />

            </form>


text:
Q: What kind of software is part of an "Implementation" exactly when stating "Implementation-defined"? What is an "Implementation" exactly? I often see the statement "implementation-defined" in the C Standard documentations, as well as getting it as answer very much.
I have then searched in the C99 Standard for it, and:
In ISO/IEC 9899/1999 (C99) is stated under §3.12:

3.12
Implementation
particular set of software, running in a particular translation environment under particular control options, that performs translation of programs for, and supports execution of functions in, a particular execution environment

As well under §5:

*Environment

An implementation translates C source files and executes C programs in two dataprocessing-system environments, which will be called the translation environment and the execution environment in this International Standard. Their characteristics define and constrain the results of executing conforming C programs constructed according to the syntactic and semantic rules for conforming implementations.

But to which software applications exactly it refers to?
Which set of software in particular?
It is stated as providing a translation AND an execution environment. So it couldn´t be the compiler alone, or am i wrong about this assumption?
About which parts of my system i can think of as part of "the implementation"?
Is it the Composing of the used Compiler with its relying C standard, the operation system, the C standard used itself or a mix between those all?
Does it despite the previous statement also include a piece of hardware (used processor, mainboard, etc)?
I quite do not understand, what an implementation exaclty is.
I feel like i have to be a 100-year experienced cyborg to know what it all includes entirely and exactly.

A: Generally speaking, an "implementation" refers to a given compiler and the machine it runs on.  The latter is important due to things such an endianness, which dictates the byte ordering of integer and floating point types, among other considerations.
An implementation is required to document its implementation defined behavior.  For example you can find GCC's implementation defined behavior here.
Compilers often support multiple versions of the C standard, so each operating mode can also be considered an implementation.  For example, you can pass the -std option to GCC to specify c89, c99. or c11 modes.

A: I think you have a good formal sense of what it is, and are focusing your question on specifics of real-world implementations, so that's what I'll address. "The implementation" actually tends to encompass a number of components which act and depend upon one another via a number of interface contracts, all of which need to be honored in order to have any hope of the implementation as a whole being conforming.
These include possibly:

*

*the compiler

*possibly an assembler, if the compiler produces asm as an intermediate form

*the linker

*library code that's part of the standard library (which is part of the language, as the language is specified, not a separate component, but only for hosted implementations not freestanding ones)

*library code that's "compiler glue" for implementing language constructs for which the compiler doesn't directly emit code (on GCC, this is libgcc), often used for floating point on machines that lack hardware fpu, division on machines that lack hardware divider, etc.

*the dynamic linker, if the implementation uses dynamic-linked programs

*the operating system kernel, if the implementation's library functions don't directly drive the hardware, but depend on syscalls or "software interrupts" or similar defined by the operating system having their specified behavior in order to implement part of the standard library or other (e.g. startup or glue) library code

*etc.

Arguably you could also say the hardware itself is part of the implementation.

A: The C99 Standard defines many things, but some are just not that relevant so they did not care to define them in the Standard in detail. Instead, they write "implementation defined" which means that whoever actually programs a compiler according to their standard can choose how exactly they do that.
For example, gcc is an implementation of that standard (Actually, gcc implements various different Standards, as pmg points out in his comment. But that's not too important right now). If you were to write your own compiler, you can only call it a "C99 Compiler" if it adheres to the standard. But where the standard states that something is implementation dependent, you are free to choose what your compiler should do.


text:
Q: Dockerfile setting ENV in different file I have a Dockerfile which builds a Rails app. The Rails app is dependent upon 20+ environment variables. I would like to extract the setting of these variables away from the original Dockerfile into a different file which is then called by the Dockerfile.
Current implementation
# Dockerfile
RUN gem install bundler
RUN bundle install

ENV SECRET_KEY1=abcdef
ENV MY_URL=CRAZYURL
ENV MY_DB=tisMyDB
# .... + 20 lines of setting
ENV LAST_ENV=FinallyItsOver

Obviously this is cumbersome to a supposedly neatly organized Dockerfile
Seeking something like:
# Dockerfile
RUN gem install bundler
RUN bundle install

config/set_envs

+
# config/set_envs
ENV SECRET_KEY1=abcdef
# ...
ENV LAST_ENV=FinallyItsOver


text:
Q: UITableViewCell animation is hit or miss. Sometimes table data/cells just pop in without the animation So I'm using a custom animation for how the table cells appear. They sort of fade in and slide up a little. I'm populating the table with data from an API call.
What I'm noticing is that it doesn't always happen. Sometimes it works as expected, other times the cells/data just appear abruptly, no animation/movement. They just sort of pop in at what would would be the end of the animation. I don't really see any consistent pattern in when it works and when it doesn't. Seems pretty random.
Any idea what is causing this behavior?
Here's the code for the animation and where it is in the tableview function:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell: RecentActivityCell = recentActivityView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! RecentActivityCell

    var lastInitialDisplayableCell = false

        //change flag as soon as last displayable cell is being loaded (which will mean table has initially loaded)
    if userActivityArray.count > 0 && !finishedLoadingInitialTableCells {
            if let indexPathsForVisibleRows = tableView.indexPathsForVisibleRows,
                let lastIndexPath = indexPathsForVisibleRows.last, lastIndexPath.row == indexPath.row {
                lastInitialDisplayableCell = true
            }
        }

        if !finishedLoadingInitialTableCells {

            if lastInitialDisplayableCell {
                finishedLoadingInitialTableCells = true
            }

            //animates the cell as it is being displayed for the first time
            cell.transform = CGAffineTransform(translationX: 0, y: 40/2)
            cell.alpha = 0

            UIView.animate(withDuration: 0.5, delay: 0.05*Double(indexPath.row), options: [.curveEaseInOut], animations: {
                cell.transform = CGAffineTransform(translationX: 0, y: 0)
                cell.alpha = 1
            }, completion: nil)
        }

    cell.backgroundColor = UIColor.clear

    if userActivityArray[indexPath.row].status == "Success" {
        cell.statusImage.image = UIImage(named: "passImage")
    } else {
        cell.statusImage.image = UIImage(named: "failImage")
    }

    cell.activity = userActivityArray[indexPath.row]
    return cell
}

A: Try to use your animation in "yourTableViewCell" by overriding:
override func prepareForReuse() {
        super.prepareForReuse()
        \\ Animation code over here
    }

dont use in "CellForRowAt"


text:
Q: How to keep assembly instructions of asm functions in c file unchanged when creating the executable for mac os x lion 10.7 Here is the asm function in c file copyed from inject-bundle project:
asm void mach_thread_trampoline(void)
{

    // Call _pthread_set_self with pthread_t arg already on stack
    pop     eax
    call    eax
    add     esp, 4

    // Call cthread_set_self with pthread_t arg already on stack
    pop     eax
    call    eax
    add     esp, 4

    // Call function with return address and arguments already on stack
    pop     eax
    jmp     eax

}

After gcc (i do the work on mac os x lion 10.7.4):
$gcc -m32 -fasm-blocks  -o a a.c -g
gdb the target, watch the mach_thread_trampoline content in gdb:
(gdb) x/17i mach_thread_trampoline

0x1f80 <mach_thread_trampoline>:    pop    %eax
0x1f81 <mach_thread_trampoline+1>:  call   *%eax
0x1f83 <mach_thread_trampoline+3>:  mov    %esp,%eax
0x1f85 <mach_thread_trampoline+5>:  mov    %eax,%esp
0x1f87 <mach_thread_trampoline+7>:  add    $0x4,%esp
0x1f8a <mach_thread_trampoline+10>: mov    %esp,%eax
0x1f8c <mach_thread_trampoline+12>: mov    %eax,-0x8(%ebp)

0x1f8f <mach_thread_trampoline+15>: pop    %eax
0x1f90 <mach_thread_trampoline+16>: call   *%eax
0x1f92 <mach_thread_trampoline+18>: mov    %esp,%eax
0x1f94 <mach_thread_trampoline+20>: mov    %eax,%esp
0x1f96 <mach_thread_trampoline+22>: add    $0x4,%esp
0x1f99 <mach_thread_trampoline+25>: mov    %esp,%eax
0x1f9b <mach_thread_trampoline+27>: mov    %eax,-0x8(%ebp)

0x1f9e <mach_thread_trampoline+30>: pop    %eax
0x1f9f <mach_thread_trampoline+31>: jmp    *%eax
0x1fa1 <mach_thread_trampoline+33>: ret

The target added some instructions for the mach_thread_trampoline functions.
Is there any methods to keep the asm functions unchanged?

A: It doesn't appear that you can do that with gcc, but you could write the function in a.asm & assemble a.asm with nasm.  a.asm would look something like:
[BITS 32]
global _mach_thread_trampoline
_mach_thread_trampoline:
; Call _pthread_set_self with pthread_t arg already on stack
pop     eax
call    eax
add     esp, 4

; Call cthread_set_self with pthread_t arg already on stack
pop     eax
call    eax
add     esp, 4

; Call function with return address and arguments already on stack
pop     eax
jmp     eax

To use it from C, you'd need a.h containing:
void mach_thread_trampoline(void);

Note that the function is intituled _mach_thread_trampoline in a.asm &  mach_thread_trampoline in a.h.  This is because function names have an underscore prepended to them on OS X.  If you moved it to linux, the assembly would have mach_thread_trampoline as well because linux doesn't prepend anything.

A: If you have asm functions of non-trivial size, you should put it / them in separate .S files where you can use .intel_syntax noprefix if you like, or use NASM like another answer suggests.
But you can use an asm(""); statement at global scope to work around any compile bugs / weirdness if you want to stick a small function written in GAS syntax into a .c or .cpp, see the last section of this answer.

asm as a function type appears to be an Apple extension, it's not supported by (Linux) gcc or clang on the Godbolt compiler explorer.
It looks like it serves the same purpose as __attribute__ ((naked)) (supported on x86 by mainstream (not just Apple) clang 3.3 and later, and recent GCC).  But @MichaelPetch reports that gcc on OS X 10.7 (gcc version 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)) does not support __attribute__ ((naked)).
(Newer OS X make gcc an alias for clang, but older OS X had custom versions of GCC).
It appears that there's a compiler bug with the asm void func(void) { syntax in the compiler version you're using; it doesn't make sense that it can assume the existence of a frame point and insert stuff like mov  %eax,-0x8(%ebp).  I don't see how that asm extension could be useful if the compiler's allowed to do that.  Maybe it doesn't happen at -O3, so you might be able to work around it by enabling optimization.
BTW, regular (non-Apple) GCC doesn't support MSVC-style asm blocks, though, only GNU C asm("instructions"); asm statements.  But Apple's version of gcc that uses LLVM does support it.

__attribute__ ((naked)) (not supported by OS X 10.7 gcc)
If you have a buggy compiler that introduces extra instructions into asm blocks, IDK if this will make any difference.  (Even if it was supported, which it isn't on OS X 10.7 gcc)
This syntax works on modern clang.  (Not gcc, because it still doesn't support -fasm-blocks)
This compiles correctly on Godbolt with clang 3.3.  I used "binary" output to make sure I was seeing the real machine code in the object file, so I had to use -nostdlib to get it to link.  It avoids distorting your asm with -O0 or -O3, but I'm using a very different compiler this syntax change is probably not relevant.
__attribute__ ((naked)) void mach_thread_trampoline(void)
{
    // asm block *inside* a function
    asm {
    // Call _pthread_set_self with pthread_t arg already on stack
    pop     eax
    call    eax
    add     esp, 4

    // Call cthread_set_self with pthread_t arg already on stack
    pop     eax
    call    eax
    add     esp, 4

    // Call function with return address and arguments already on stack
    pop     eax
    jmp     eax
    }
}

Portable GNU C asm("");
You can put Basic ASM statements at global scope in GNU C.
This syntax probably will work around the compiler bug on OS X 10.7, because we're not using -fasm-blocks at all, and the compiler has no chance to think it's inside a function.  It should just assemble this code in the .text section.
void mach_thread_trampoline(void);   // prototype

// definition: name mangling / leading underscore must be done manually
asm(".globl  _mach_thread_trampoline\n\t"
    "_mach_thread_trampoline:\n\t"
    "pop   %eax\n\t"
    "call  *%eax\n\t"
    ...
    "jmp    *%eax"
);

So a naked function could have advantages in C++ where the name mangling is non-trivial.  Probably naked functions are automatically noinline.
If you want really portable, you can use dialect-alternatives like jmp {*%eax|eax} so your code works if compiled with -masm=intel or not.
I don't recommend using .intel_syntax noprefix inside an asm block, and then switching back to .att_syntax at the end for the rest of the compiler's code.  It's a hack that breaks if you (or a tool like the Godbolt compiler explorer) compiles with -masm=intel.


text:
Q: R: How to colorize the diagonal panels in a pairs() plot? The following code colorizes the panel backgrounds of a pairs plot in R. How can I colorize the diagonal panel (where the variable names are printed)? As you can see, I tried it but the variable names are not correctly aligned (for whatever reason).
count <- 0
mypanel <- function(x, y, ...){

   count <<- count+1
   bg <- if(count %in% c(1,4,9,12)) "#FDFF65" else "transparent"    ll <- par("usr")
   rect(ll[1], ll[3], ll[2], ll[4], col=bg)    points(x, y, cex=0.5)
}

mydiag.panel <- function(x, ...){

   ll <- par("usr")
   rect(ll[1], ll[3], ll[2], ll[4], col="#FDFF65") }

U <- matrix(runif(4*500), ncol=4)
pairs(U, panel=mypanel, diag.panel=mydiag.panel)

A: Explicitly setting label.pos = 0.5 seems to work for me:
pairs(U,panel = mypanel, diag.panel=mydiag.panel,label.pos = 0.5)

The default appears to be 0.5 + has.diag/3, where has.diag is set to TRUE when you specify your own custom diag.panel function, which ends up changing the default to 0.5 + 1/3. Honestly, I'm not sure why that would be.
Possibly the thinking is that if you define your own plotting function for the diagonals, the assumption is that you're plotting data in those panels, and so it makes sense to move the default label positioning away from the center of the panel...?

A: I was able to shade my diagonal without a complicated code:
panel.diag <- function(x,...){
usr <- par("usr")
rect(usr[1],usr[3],usr[2],usr[4],col="pink")
}

pairs(U,upper.panel=panel.cor,lower.panel=panel.pts, diag.panel=panel.diag, label.pos=0.5)


text:
Q: Add XML element to complex XML file with Powershell Have a very complex task for Powershell on remote work for me. It's hard to explain but I will try.
I have XML file with complex structure (it's a file with settings for Visual Studio):
<UserSettings>
<ToolsOptions>
<ToolsOptionsCategory RegisteredName="Environment" name="Environment">
</ToolsOptionsCategory>
</ToolsOptions>
</UserSettings>

The task is add to section "ToolsOptionsCategory" following sub-node:
<ToolsOptionsSubCategory PackageName="VS Setup Composition" RegisteredName="ProductUpdates" name="ProductUpdates">
<PropertyValue name="IsBackground">true</PropertyValue>
</ToolsOptionsSubCategory>

I tried to AppendChild and CreateElement, but I don't have an idea how to add such attributes as "PackageName" and "RegistereName". This subnode is absent from the target file and I need to add it.
I would be great if you can help me and show me the way.
Thank you in advance! Be health and stay at home :)

A: For demo, I'm using a Here-String
[xml]$xml = @"
<UserSettings>
<ToolsOptions>
<ToolsOptionsCategory RegisteredName="Environment" name="Environment">
</ToolsOptionsCategory>
</ToolsOptions>
</UserSettings>
"@

In real life, you would load it from file with [xml]$xml = Get-Content -Path 'D:\config.xml'
$node = $xml.UserSettings.ToolsOptions.ToolsOptionsCategory
# update the attributes for this node
$node.SetAttribute("PackageName", "VS Setup Composition")
$node.SetAttribute("RegisteredName", "ProductUpdates")
$node.SetAttribute("name", "ProductUpdates")
# create the new sub node (XmlElement)
$newNode = $xml.CreateElement("PropertyValue")
$newNode.SetAttribute("name", "IsBackground")
$newNode.InnerText = "true"
# add this new subnode to the 'ToolsOptionsCategory' node
$node.AppendChild($newNode)

$xml.Save('D:\newConfig.xml')

Result:
<UserSettings>
  <ToolsOptions>
    <ToolsOptionsCategory RegisteredName="ProductUpdates" name="ProductUpdates" PackageName="VS Setup Composition">
      <PropertyValue name="IsBackground">true</PropertyValue>
    </ToolsOptionsCategory>
  </ToolsOptions>
</UserSettings>

A: Here's another way to do is as well. I've added comments to explain the approach.
# Create XML object to load data into
$xml = New-Object -TypeName System.Xml.XmlDocument

# Load in XML file
$xml.Load("test.xml")

# Get root tools node to add children
$toolsRootNode = $xml.UserSettings.ToolsOptions.ToolsOptionsCategory

# Store attributes in a hashtable
$toolsAttributes = [ordered]@{
    PackageName="Setup Composition"
    RegisteredName="ProductUpdates"
    name="ProductUpdates"
}

# Set each attribute from hashtable
$toolsSubNode = $xml.CreateElement("ToolsOptionsSubCategory")
foreach ($kvp in $toolsAttributes.GetEnumerator())
{
    $toolsSubNode.SetAttribute($kvp.Key, $kvp.Value)
}

# Create property sub node
$propertyNode = $xml.CreateElement("PropertyValue")
$propertyNode.SetAttribute("name", "IsBackground")
$propertyNode.InnerText = "true"

# Append property node to tools sub node
$toolsSubNode.AppendChild($propertyNode)

# Finally add tools sub node to root node
$toolsRootNode.AppendChild($toolsSubNode)

# Save to new output XML file
$xml.Save("output.xml")

output.xml
<UserSettings>
  <ToolsOptions>
    <ToolsOptionsCategory RegisteredName="Environment" name="Environment">
      <ToolsOptionsSubCategory PackageName="Setup Composition" RegisteredName="ProductUpdates" name="ProductUpdates">
        <PropertyValue name="IsBackground">true</PropertyValue>
      </ToolsOptionsSubCategory>
    </ToolsOptionsCategory>
  </ToolsOptions>
</UserSettings>


text:
Q: Disabling Asp.Net Auto Naming Is there a way to disable the ASP.Net auto-naming?
For instance: When I have a control on my page that sits inside a masterpage instead of being named
theLabel
it is renamed to
ctl00_ContentPlaceHolder1_clist0_rptSelected_ctl05_theLabel
This is the behavior I don't want.

A: This is a common headache with ASP.NET.  If ASP.NET 4 is an option for you, you can use the new ClientID functionality to customize the naming convention.
More information, courtesy of The Gu:
http://weblogs.asp.net/scottgu/archive/2010/03/30/cleaner-html-markup-with-asp-net-4-web-forms-client-ids-vs-2010-and-net-4-0-series.aspx

A: If you're lucky enough to be able to target ASP.NET 4.0...
In your page directive, set ClientIDMOde="Static".  This will emit ID's exactly as you have them in your controls.
So if you have:
<asp:Label ID="example" runat="server" />

It will emit this clean ID:
something...

A: If you're using ASP.NET 4.0 then yes you can.
Otherwise, it's difficult. If you want the client id in javascript you can do something like this::


text:
Q: Firebase multiple queries in android I have this database:

The candidates collection contains several categories such as president and secretary. It also has totalVotes for each candidate.
I would like to query:

*

*Results by category eg President or Secretary

*The candidate with highest 'totalVotes' per category, i.e, the President with the highest votes, and the secretary with highest votes.

Here is my code that is not working:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
        DatabaseReference candidatesRef = rootRef.child("candidates");
        Query specific = candidatesRef.orderByChild("category").equalTo("President");

        specific.orderByChild("totalVotes").limitToFirst(1);

        specific.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot){
                for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
                    String firstname = childSnapshot.child("firstname").getValue(String.class);
                    String lastname = childSnapshot.child("lastname").getValue(String.class);
                    Long votes = childSnapshot.child("totalVotes").getValue(Long.class);
                    pres.setText(firstname + " " + lastname+" - "+votes+" Votes");
                }
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
                throw databaseError.toException(); // don't swallow errors
            }
        });

How can I achieve this? Thanks

A: Unfortunately, there is no OR clause in Firebase. So you cannot filter the candidates on the category property based on multiple values.
There is a solution that might work but only if those values are in a range. In your case, you can get all candidates matching President or Secretary with:
ref.child("candidates")
   .orderByChild("category")
   .startAt("President")
   .endAt("Secretary")

The issue here is that it will also match candidates for other categories whose category is between President and Secretary if it exists. Besides that, you can not limit the query to 1 or 2 because you'll never know which candidate will have the highest number of votes. It might be a president, as well as a secretary.
So, there is no way in the Firebase Realtime Database to pass multiple values into a query. You need to perform separate queries for that and merge the result on the client.
If you consider at some point in time to try using Cloud Firestore, you can find there Query's whereIn(String field, List values) method that can help you solve this issue.


text:
Q: How to sort and pair as per Keys in Javascript First of all i am new to Nosql database but for my app tried using firebase for the first time.
I am creating an App about something and in that app i have applicants which submit some amount of money every month at specific date
in order to store that in my firebase Firestore i created a collection name transaction and in that for a user i am saving all his transactions.
transaction2018(collection) -> userId1(collection) -> { ....result1 }
                        -> userId2(collection) -> { ....result2 }
                     -> userId3(collection) -> { ....result3 }

transaction2019(collection) -> userId1(collection) -> { ....result1 }
                         -> userId2(collection) -> { ....result2 }
                         -> userId3(collection) -> { ....result3 }

That is the reason i have designed like that so for every user i can
  get all his transaction in one object One more thing in my resuly
  object amount_2,data_2 two is actually month(feb) and if i dont do
  this that I'll have to go deeper something like :

transaction2018 -> userId1 -> January -> {amount,date.....}
                        -> February
                        .....

which is not actually a good practice in Nosql databases.

I am using NoSql database and the result which I am getting is in below format,
How can I convert this in my desired format after fetching data:
let result = {
  amount_2       : "1000",
  amount_3       : "1200",
  date_2         : "15/2/2019",
  date_3         : "15/3/2019",
  modeOfPayment_2: "Cash",
  modeOfPayment_3: "Cash",
  note_2         : "áßðáßðáßð↵áß",
  note_3         : "",
  refNum_2       : "11111",
  refNum_3       : "Fffff",
  submittedByID_2: "T62tgJcjieSJsAEJT69VfpRc5Mw2",
  submittedByID_3: "T62tgJcjieSJ"
};

I want something like:
var output = [
  {
    amount2,
    date2,
    ....
  },
  {
   amount3,
   date3,
   ......
  }
]

A: You can do this in plain JavaScript using Object.entries and Array.reduce to build an intermediate dictionary whose keys are the digits at the end of your keys. This will group your key/value pairs by this digit, you can then get your result by taking the values of this dictionary using Object.values.
With key.match(/(\d+)$/) you can extract the number at the end of your keys and use it as the key for the intermediate dictionary.
Using a positive lookahead regex /_(?=\d)/, you can remove the underscore if it precedes a digit a the end of your keys to get your new key names.

const data = {
  amount_2       : "1000",
  amount_3       : "1200",
  date_2         : "15/2/2019",
  date_3         : "15/3/2019",
  modeOfPayment_2: "Cash",
  modeOfPayment_3: "Cash",
  note_2         : "áßðáßðáßð↵áß",
  note_3         : "",
  refNum_2       : "11111",
  refNum_3       : "Fffff",
  submittedByID_2: "T62tgJcjieSJsAEJT69VfpRc5Mw2",
  submittedByID_3: "T62tgJcjieSJ"
};

const result = Object.values(Object.entries(data).reduce((dict, [key, val]) => {
  // reduce is called for each key/value pair in your input data
  // here we add the key/value pair in the proper entry based
  // on the number extracted at the end
  const num = key.match(/(\d+)$/); // get number at end of key
  const newKey = key.replace(/_(?=\d)/, ''); // remove underscore before digit
  dict[num] = dict[num] || {}; // create a default entry if needed
  dict[num][newKey] = val; // set value for the new key
  return dict; // return intermediate dictionary
}, {}));

console.log(result);

A: You might consider the use of a single regular expression to extract both the name and number from each key of the input (results) object via the following:
const [, name, number] =  key.match(/^(.*)_(\d+)$/);

Where key is the current key of result being iterated. This single regular expression will return the name and number of the key according to the format you have prescribed. A full solution can be achieve independent of lodash, as shown:

let result = {
  amount_2       : "1000",
  amount_3       : "1200",
  date_2         : "15/2/2019",
  date_3         : "15/3/2019",
  modeOfPayment_2: "Cash",
  modeOfPayment_3: "Cash",
  note_2         : "áßðáßðáßð↵áß",
  note_3         : "",
  refNum_2       : "11111",
  refNum_3       : "Fffff",
  submittedByID_2: "T62tgJcjieSJsAEJT69VfpRc5Mw2",
  submittedByID_3: "T62tgJcjieSJ"
};

/* Compose Object.values() and Object.entries() with reduce. Here we get
the key/value pairs (entries) of the input "results" object, and reduce
the key/values into an object of nsted objects of key/values grouped by
number.
We then aquire an array of the grouped objects using Object.values() */
const groupedResult = Object.values(Object.entries(result).reduce((output, [key,value]) => {

  /* Extract key and number parts of current entry of result object */
  const [, name, number] =  key.match(/^(.*)_(\d+)$/);

  /* Fetch or insert (empty) object for the number corresponding to
  this entries key */
  const group = output[ number ] = output[ number ] || {}

  /* Compose a key with number suffix and insert value into group
  object for composed key */
  group[ `${name}${ number }` ] = value;

  /* Return current output object for next iteration of reduce */
  return output;

}, {}))

console.log(groupedResult);

A: You can create a function using _.flow() that breaks the object to an array of entries (_.pairs()), groups by the number in the key, and then maps the result back to an object (_.fromPairs), and updates the keys (_.mapKeys()).

const { flow, toPairs, groupBy, partialRight: pr, map, fromPairs, mapKeys } = _;

const pattern = /_+(\d+)$/;
const getKeyId = ([k]) => (k.match(pattern) || [''])[0];

const fn = flow(
  toPairs, // convert to entries
  pr(groupBy, getKeyId), // group by the number in the key
  pr(map, flow( // map back to object
    fromPairs, // combine the entries in the group
    pr(mapKeys, (v, k) => k.replace(pattern, '$1')) // update the keys
  ))
);

const data = {
  amount_2       : "1000",
  amount_3       : "1200",
  date_2         : "15/2/2019",
  date_3         : "15/3/2019",
  modeOfPayment_2: "Cash",
  modeOfPayment_3: "Cash",
  note_2         : "áßðáßðáßð↵áß",
  note_3         : "",
  refNum_2       : "11111",
  refNum_3       : "Fffff",
  submittedByID_2: "T62tgJcjieSJsAEJT69VfpRc5Mw2",
  submittedByID_3: "T62tgJcjieSJ"
};

const result = fn(data);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

And the same solution using lodash/fp:

const { flow, toPairs, groupBy, map, fromPairs, mapKeys, replace } = _;

const pattern = /_+(\d+)$/;
const getKeyId = ([k]) => (k.match(pattern) || [''])[0];

const fn = flow(
  toPairs, // convert to entries
  groupBy(getKeyId), // group by the number in the key
  map(flow( // map back to object
    fromPairs, // combine the entries in the group
    mapKeys(replace(pattern, '$1')) // update the keys
  ))
);

const data = {
  amount_2       : "1000",
  amount_3       : "1200",
  date_2         : "15/2/2019",
  date_3         : "15/3/2019",
  modeOfPayment_2: "Cash",
  modeOfPayment_3: "Cash",
  note_2         : "áßðáßðáßð↵áß",
  note_3         : "",
  refNum_2       : "11111",
  refNum_3       : "Fffff",
  submittedByID_2: "T62tgJcjieSJsAEJT69VfpRc5Mw2",
  submittedByID_3: "T62tgJcjieSJ"
};

const result = fn(data);

console.log(result);
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

A: By now it seems you want to group fields into objects depending on numbers in tail of each index.
const result = [];
_.each(inputObject, (key, value) => {
    const [,keyName, indexPart] = key.match(/^(.*)_(\d+)$/);
    result[indexPart] = result[indexPart] || {};
    result[indexPart][keyName] = value;
});


text:
Q: Use of Bera Mono font with \mlttfamily described by matlab-prettifier I am using latex with pdftex and trying to use the Bera Mono font with the \mlttfamily described by matlab-prettifier documentation.  However, my generated output seams to ignore my \lstset basicstyle = \mlttfamily setting and uses the default \ttfamily instead? Below is image of my output.
\documentclass[border=30pt]{standalone}

\usepackage[final]{matlab-prettifier}

\usepackage[T1]{fontenc}

\lstset{
  style              = Matlab-editor,
  basicstyle         = \mlttfamily, %\ttfamily
  escapechar         = ",
  mlshowsectionrules = true,
}

\begin{document}

\begin{lstlisting}[style=Matlab-editor]
%% Code sections are highlighted.
% System command are supported...
!gzip sample.m
% ... as is line continuation.
A = [1, 2, 3,... % (mimicking the ouput is good)
 4, 5, 6]
fid = fopen('testFile.text', 'w')
for i=1:10
  fprintf(fid,'%6.2f \n', i);
end
x=1; %% this is just a comment, though
% Context-sensitive keywords get highlighted correctly...
p = properties(mydate); %(here, properties is a function)
x = linspace(0,1,101);
y = x(end:-1:1)
% ... even in nonsensical code.
]end()()(((end end)end ))))end (function end
%{
    block comments are supported
%} even
runaway block comments
are
   \end{lstlisting}

\end{document}

A: This fixes the problem, \lstset defines the default setting for \lstlisting and I was overwriting this style setting earlier without the change in font.
The following code now correctly changes the font to Bera Mono.
\documentclass[border=30pt]{standalone}

\usepackage[final]{matlab-prettifier}

\usepackage[T1]{fontenc}

\lstset{
  style              = Matlab-editor,
  basicstyle         = \mlttfamily, %\ttfamily
  escapechar         = ",
  mlshowsectionrules = true,
}

\begin{document}

\begin{lstlisting}
%% Code sections are highlighted.
% System command are supported...
!gzip sample.m
% ... as is line continuation.
A = [1, 2, 3,... % (mimicking the ouput is good)
     4, 5, 6]
fid = fopen('testFile.text', 'w')
for i=1:10
  fprintf(fid,'%6.2f \n', i);
end
x=1; %% this is just a comment, though
% Context-sensitive keywords get highlighted correctly...
p = properties(mydate); %(here, properties is a function)
x = linspace(0,1,101);
y = x(end:-1:1)
% ... even in nonsensical code.
]end()()(((end end)end ))))end (function end
%{
    block comments are supported
%} even
runaway block comments
are
\end{lstlisting}

\end{document}

A: I see now from the overview description of matlab-prettier that the following works.
            \documentclass[border=30pt]{standalone}

            \usepackage[final]{matlab-prettifier}

            \usepackage[T1]{fontenc}

            \begin{document}

            \begin{lstlisting}[
              style      = Matlab-editor,
              basicstyle = \mlttfamily,
            ]

            %% Code sections are highlighted.
            % System command are supported...
            !gzip sample.m
            % ... as is line continuation.
            A = [1, 2, 3,... % (mimicking the ouput is good)
                 4, 5, 6]
            fid = fopen('testFile.text', 'w')
            for i=1:10
              fprintf(fid,'%6.2f \n', i);
            end
            x=1; %% this is just a comment, though
            % Context-sensitive keywords get highlighted correctly...
            p = properties(mydate); %(here, properties is a function)
            x = linspace(0,1,101);
            y = x(end:-1:1)
            % ... even in nonsensical code.
            ]end()()(((end end)end ))))end (function end
            %{
                block comments are supported
            %} even
            runaway block comments
            are

            \end{lstlisting}

            \end{document}


text:
Q: Dataset breaks multi-character StringSplit Given
ds = Dataset[{"a b", "c-d"} ]

multi-character StringSplit is broken with Dataset (10.1 regression?)
ds[All, StringSplit[#, {" ", "-"}] &]

though single split charaters works:
ds[All, StringSplit[#, " "] &] // Normal

{{"a", "b"}, {"c-d"}}

As does plain non-Dataset version of multi-char of course (same output as above)
ds // Normal // Map[StringSplit[#, {" ", "-"}] &]

A: This issue is due to the same type-inferencing problem described here.
Using printSignatures from the referenced answer, we can see that the type inferencer will only accept a single string as the second argument, not a list:
printSignatures[StringSplit]
  (*
    {Vector[Atom[String], n_]}
    {Atom[String]}
    {Atom[String], Atom[String]}
    {Vector[Atom[String], n_], Atom[String]}
  *)

This list of valid signatures will only accept a single string as the second argument.
The referenced answer shows how to dodge the type-inferencer.  We can use similar work-arounds here:  either by using Query directly on the raw data...
ds // Normal // Query[Dataset, StringSplit[#, {" ", "-"}] &]

... or by disguising the StringSplit operator:
ds[All, StringSplit&[][#, {" ", "-"}] &]

Notice how the second work-around loses useful type information in this case, causing the dataset visualization to fall back to a cruder form.  We can restore the missing type information by inserting a terminal Dataset ascending operator into the query:
ds[Dataset, StringSplit&[][#, {" ", "-"}] &]

This last operation causes the proper type information to be deduced from the final output data (using TypeSystem`DeduceType), restoring the proper visualization.

A: It seems to be a problem of your specific version. Im running 10.0.1.0 MacOS and it works just fine.


text:
Q: how do i add stuff to listbox (tkinter python) I'm making a log/chat system in my program (just Tkinter default looks) and i came across a problem where I can't add or change a listbox. Here is what I'm trying to do:
import tkinter
from tkinter import *
from tkinter import messagebox
import random

window = tkinter.Tk()
window.geometry("250x195")
window.title(" ")
window.iconbitmap("icon.ico")

global loglength, log

log = []
loglength = len(log)
inventorylist = []

def sendmessage(event):
    chatstring = chatentry.get()
    log.append(chatstring)
    print(log, loglength)
    checknew() #dont worry abt this it works

serverlog = tkinter.Listbox(
    width=20,
    height=11,
    bg="darkgray",
    listvariable=log
).place(x=128,y=-2)

I want to add items to the listbox. Here is an image of my program:

When I press enter (the key bound to the function to add the string to the listbox) this happens:

A: is Listbox like a program u want?
if u want a program that will make u program list in tkinder this is the code :
from tkinter import *
a= Tk()
a.geometry("400x400")
a.title("test")
Lb1 = Listbox(a,bg = "pink", bd = 10, fg = "black",\
              font = "Castellar", cursor = "target")
Lb1.insert(1, "lion")
Lb1.insert(2, "tiger")
Lb1.insert(3, "zebra")
Lb1.insert(4, "elephant")
Lb1.insert(5, "deer")
Lb1.insert(6, "fox")
Lb1.insert(7, "Wolf")
Lb1.insert(8, "Gorilla")
Lb1.insert(9, "Jackal")
Lb1.insert(10, "Otter")
Lb1.pack()
a.mainloop()

hope that i helped u.


text:
Q: Kotlin check if two lists are the same apart from one list having an additional element? So I have list A and list B.
A is of size n and B is of size n + 1.
I need to know if all elements in A are the same as all elements in B.sublist(0, n - 1).
A: [5,7,2,9]
B: [5,7,2,9,1]
true

A: [5,7,2,9]
B: [5,7,2,9,9]
true

A: [7,5,2,9]
B: [5,7,2,9,1]
false (order matters)

Is there any elegant ways to do this using library functions maybe?

A: List has a subList method, so you can express your conditions directly:
(b.size() == a.size() + 1) && (b.subList(0, a.size()).equals(a))

A: Very simple solution:
return B.take(A.size+1) == A

A: As long as b cannot be empty, you could write:
return a == b.dropLast(1)


text:
Q: How to develop a "Check All" feature on a large, paginated grid/table I am looking for advice on best practices regarding the following scenario.
I have a grid that supports server-side pagination.
Let's say that there are 100,000 records in the grid, and each page size is 100 records.
Let's say they "Select All".
Considering the records are paginated, do you store a list of "selected" records client-side or server-side?
My first pass was to have the service page that populates the grid to return a comma delimited list of all the records primary keys for future reference alongside the normal dataset, but this seems clunky or even dangerous with large datasets.
My second pass was to store all the records in a special table for future reference, but this adds a lot of overhead in the form of table management to the process.
Or something else? Thanks!


text:
Q: Is it possible to write vlookup functions in Google's connected sheets? So there is a requirement to build tables and charts in google sheets with data in bigquery.
The data can be brought in to google sheets using connected sheets. Is it possible to use connected sheets like normal spreadsheets with all the functionalities? Specifically is it possible to write vlookup functions in connected sheets data?
The only resource I could find on the internet is this tutorial video: https://www.youtube.com/watch?v=rkimIhnLKGI.  In this video, I see that in connected sheets there are no row and column reference available like in normal spreadsheets. Is it possible to show the row and column reference? Is it possible to write cell references in functions? Is it possible to write vlookup functions in connected sheets?

A: The answer is no.
I got a chance to work with connected sheets, they don't have the functionalities of a normal spreadsheet.
https://www.youtube.com/watch?v=rkimIhnLKGI, This video pretty much shows all the features of connected sheets.

A: You can use an indirect method to accomplish that.
Use the extract function to create a new sheet and don't set any condition. Then you could use that new sheet with any function you want.
However, there is a 25000-row limitation. So if you want to process a large table, you may have to connect your sheet back to BigQuery and do the ETL on the BigQuery side.
I hope that helps you well!


text:
Q: Extension not found error on calling an extension I have setup a SIP server and connected two polycom soundstation duo devices to it. They both register line with the SIP server fine but when I try to place a call from one device to the other, asterisk's CLI returns following NOTICE:

Call from '1000' (58.65.17.222:5060) to extension '1001' rejected
  because extension not found in context 'polycom'.

Related snipped of extension.conf look like:
[polycom]
exten => 1000,1,Dial(SIP/1000)
exten => 1000,2,VoiceMail,u1000
exten => 1000,102,VoiceMail,b1000
exten => 1001,1,Dial(SIP/1001)
exten => 1001,2,VoiceMail,u1001
exten => 1001,104,VoiceMail,b1001

and sip.conf look like:
[1000]
type=friend
host=dynamic
dtmfmode=rfc2833
context=polycom

[1001]
type=friend
host=dynamic
dtmfmode=rfc2833
context=polycom

Can you spot any error in these configurations?

A: Your configuration files look fine. And pardon if this is stupid question, but - have you reloaded the dialplan? And what result does it have to add
exten=>s,1,Answer()
exten=>s,n,Playback(beep)
exten=>s,n,Hangup()

this to to your polycom context?


text:
Q: Binarize pixels by value I want to binarize a gray image by value, so pixels that are between a and b will be 0, and 255 otherwise. I tried cv2.threshold but this didn't produce the right effect. So I tried:
def cut(img,d,u):
    for x,line in enumerate(img):
        for y,px in enumerate(line):
            if px < d or px > u:
                img[x][y]=0
            else:
                img[x][y]=255

But this way is low performance, what is the right way to do that, use histogram equalization?

A: Have a look at inRange function.
You can do something like:
binary = cv2.inRange(gray_image, d, u)

You then probably need to invert the binary image:
binary_inv = cv2.bitwise_not(binary)

A: First, you need to make sure your image is in an allowed data format for opencv Then you should use the threshold function or inRange function to create the binary image/matrix according to your needs. With the threshold function, you'd need to apply it twice, since you have a range, but that's not too complicated. There's a really nice blog post on this here.


text:
Q: How to make a query with query builder in three tables? I have three tables employe, skills and technologies
tables
=====================
|    employe        |
=====================
|id_employe         |
|name               |
|id_skill           |

=====================
|    skills         |
=====================
|id_skill           |
|Id_technologie     |
=====================

=====================
|    technologies   |
=====================
|id_technologie     |
|name               |
=====================

In each table I have these
records
employe
=============================
|id_employe|name  |id_skill |
=============================
|1         |jhon  |1        |
|2         |tom   |2        |

skill
=============================
|id_skill  | id_technologie  |
=============================
|1         |          1      |
|1         |          2      |
|2         |          1      |
|2         |          4      |

technologies
============================
|id_technologie| name      |
============================
|1             |  PHP      |
|2             |  Java     |
|3             |  Python   |
|4             |  C        |

I want to get a result like
this
=============================================
id_employe| name |  id_skill|   name  | name
=============================================
1         | jhon |     1    |    PHP  | Java

I tried to do this but the result is not what I expected
function listar(){
    $users = DB::table('employe')
        ->join('skills', 'skills.id_skill', '=', 'employe.id_skill')
        ->join('technologies', 'technologies.id_technologie', '=', 'skills.id_technologie')
        ->where('skills.id_skill', '=', 1)
        ->get();
    return response()->json($users,200);
}

A: Original:
Are you sure you entered the correct columns?
What I see in your picture is id_skills and id_technologie.
DB::table('employe')
->join('skills', 'skills.id_skills', '=', 'employe.id_skills')
->join('technologies', 'technologies.id_technologie', '=', 'skills.id_technologie')
->where('skills.id_skills', 1)
->get();

New:
You want 2 results in 1 row.
And by 1 Query SQL.
You don't know how many technologie one skills related.
The way I think to resolve is select skills first.
Then find technologie and you can named as Name1,Name2 etc.
Forgive me poor English.


text:
Q: Why I can not get message pusher in Laravel? Here is a private channel:
public function broadcastOn()
{
    // Here I get $user object successfully
    return new PrivateChannel('user-'.$this->user->id); // it is 1
}

The permissions are:
Broadcast::channel('user-{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

The sender is:
Route::post('sender', function () {
    PrivateEvent::dispatch(Auth::user());
})->middleware('auth:sanctum');

The client was tested in pusher debug console, it works:
var channel = pusher.subscribe('user-1');
channel.bind('PrivateEvent', function(data) {
  alert(JSON.stringify(data));
});

Why when I send message using routing I dont get the message in JS? JS has not errors too.