text:
Q: GPUImage shader crashing with "ERROR: One or more attached shaders not successfully compiled" I'm trying to build a Vibrance filter for GPUImage based on this Javascript:
/**
 * @filter       Vibrance
 * @description  Modifies the saturation of desaturated colors, leaving saturated colors unmodified.
 * @param amount -1 to 1 (-1 is minimum vibrance, 0 is no change, and 1 is maximum vibrance)
 */
function vibrance(amount) {
    gl.vibrance = gl.vibrance || new Shader(null, '\
        uniform sampler2D texture;\
        uniform float amount;\
        varying vec2 texCoord;\
        void main() {\
            vec4 color = texture2D(texture, texCoord);\
            float average = (color.r + color.g + color.b) / 3.0;\
            float mx = max(color.r, max(color.g, color.b));\
            float amt = (mx - average) * (-amount * 3.0);\
            color.rgb = mix(color.rgb, vec3(mx), amt);\
            gl_FragColor = color;\
        }\
    ');

    simpleShader.call(this, gl.vibrance, {
        amount: clamp(-1, amount, 1)
    });

    return this;
}

One would think I should be able to more/less copy paste the shader block:
GPUImageVibranceFilter.h
@interface GPUImageVibranceFilter : GPUImageFilter
{
    GLint vibranceUniform;
}

// Modifies the saturation of desaturated colors, leaving saturated colors unmodified.
// Value -1 to 1 (-1 is minimum vibrance, 0 is no change, and 1 is maximum vibrance)
@property (readwrite, nonatomic) CGFloat vibrance;

@end

GPUImageVibranceFilter.m
#import "GPUImageVibranceFilter.h"

#if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE
NSString *const kGPUImageVibranceFragmentShaderString = SHADER_STRING
(
    uniform sampler2D inputImageTexture;
    uniform float vibrance;
    varying highp vec2 textureCoordinate;
    void main() {
        vec4 color = texture2D(inputImageTexture, textureCoordinate);
        float average = (color.r + color.g + color.b) / 3.0;
        float mx = max(color.r, max(color.g, color.b));
        float amt = (mx - average) * (-vibrance * 3.0);
        color.rgb = mix(color.rgb, vec3(mx), amt);
        gl_FragColor = color;
    }
);
#else
NSString *const kGPUImageVibranceFragmentShaderString = SHADER_STRING
(
    uniform sampler2D inputImageTexture;
    uniform float vibrance;
    varying vec2 textureCoordinate;
    void main() {
        vec4 color = texture2D(inputImageTexture, textureCoordinate);
        float average = (color.r + color.g + color.b) / 3.0;
        float mx = max(color.r, max(color.g, color.b));
        float amt = (mx - average) * (-vibrance * 3.0);
        color.rgb = mix(color.rgb, vec3(mx), amt);
        gl_FragColor = color;
    }
);
#endif

@implementation GPUImageVibranceFilter

@synthesize vibrance = _vibrance;

#pragma mark -
#pragma mark Initialization and teardown

- (id)init;
{
    if (!(self = [super initWithFragmentShaderFromString:kGPUImageVibranceFragmentShaderString]))
    {
        return nil;
    }

    vibranceUniform = [filterProgram uniformIndex:@"vibrance"];
    self.vibrance = 0.0;

    return self;
}

#pragma mark -
#pragma mark Accessors

- (void)setVibrance:(CGFloat)vibrance;
{
    _vibrance = vibrance;

    [self setFloat:_vibrance forUniform:vibranceUniform program:filterProgram];
}

@end

But that doesn't compile, crashing with:
Failed to compile fragment shader
Program link log: ERROR: One or more attached shaders not successfully compiled
Fragment shader compile log: (null)
Vertex shader compile log: (null)

The error is certainly clear, but being inexperienced with OpenGL ES shaders, I have no idea what the problem actually is.

A:
One would think I should be able to more/less copy paste the shader block.

This might be the case in desktop GLSL, but in OpenGL ES you cannot declare a float variable (this includes types derived from float such as vec2 or mat4 as well) without first setting the precision - there is no pre-defined default precision for float in the fragment shader.
Implementations guarantee support for mediump and lowp floating-point precision in the fragment shader. You will have to check before setting highp as the default, however.
This whole problem screams "missing precision" to me, but why the compiler is not telling you this in the compile log I really do not know.
        Brush up on 4.5.3 Default Precision Qualifiers (pp. 35-36)

Side-note regarding your use of CGFloat:
Be careful using CGFloat.
Depending on your compile target (whether the host machine is 32-bit or 64-bit), that type will either be single-precision or double-precision. If you are passing something declared CGFloat to GL, stop that =P
Use GLfloat instead, because that will always be single-precision as GL requires.
       See a related answer I wrote for more details.


text:
Q: Angular 2 (v6) inline if else? I use Angular Material Tables. And display in a table a list of columns (displayedColumns).
I need to display the "birthday" column using the "date" filter ({{element[column] | date}}), but let other columns as is. How do I say, if the column=="birthday" then apply the filter "date"?
<ng-container matColumnDef="{{column}}" *ngFor="let column of displayedColumns">
  <th mat-header-cell *matHeaderCellDef> {{column}} </th>
  <td mat-cell *matCellDef="let element"> {{element[column]}} </td>
</ng-container>

A: Try that :
<ng-container matColumnDef="{{column}}" *ngFor="let column of displayedColumns">
  <th mat-header-cell *matHeaderCellDef> {{column}} </th>
  <td mat-cell *matCellDef="let element"> {{column === 'birthday' ? (element[column] | date) : element[column]}} </td>
</ng-container>

A: You could create your own pipe that checked column and displays element appropriately, or you can just do a ternary check:
{{column !== "birthday" ? element[column] : element[column] | date}}

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is a single word for "Currently Working" I'm listing all my work experiences on resume but for my current job I added a little label which reads "Currently Working". For some reason this doesn't seem right to me. What's the best way to specify this ?

A: I would suggest employed;

persons who are employed full-time or part-time during a specified payroll period. Temporary employees and those on paid-leave are included in this definition.

Read more: http://www.businessdictionary.com/definition/employed.html#ixzz3T1K6aihK

A: If you have shown beginning and end dates on your prior jobs, you can simply put this (e.g.) for your current job:

*

*April 2012–present

(by the way, that's an en-dash, not a hyphen. Ranges of dates are separated by en-dashes.)

A: How about working? Having a paying job; employed.


text:
Q: How to make `docker run` inherit ulimits Running a command via docker does not seem to adhere to my currently configured ulimits:

$ ulimit -t
5
~ $ sudo -- bash -c "ulimit -t"
5
~ $ sudo -- docker run --rm debian:wheezy bash -c "ulimit -t"
unlimited

How can I make it do that?

A: You can set global limits in the Docker daemon config. On Ubuntu, this is managed in Upstart. Add limit cpu <softlimit> <hardlimit> to /etc/init/docker.conf and restart the daemon.
On a per container basis, you must use the --privileged flag with docker run in order to set ulimits. AFAIK there is no way to do it without --privileged.
See also Runtime constraints on CPU and memory.

A: Currently (v1.5.0) these limits are inherited from the docker daemon's limits. But docker team is about to release limits per containers.
For a workaround you can set the limits inside the container like
# docker run ubuntu bash -c "ulimit -t 5; doSomething"


text:
Q: MDX query result All element should show last tuple not a sum I would like to have a different value on the All element of the mdx query result. This value should be the value of the last tuple from a specified dimension attribute. For example:
Student     Schoolyear      Grade
Fred        All             B
Fred        2009 / 2010     A
Fred        2010 / 2011     A
Fred        2011 / 2012     B
Wilma       All             C
Wilma       2009 / 2010     B
Wilma       2010 / 2011     C

So the value on the All element should be the last element in the second column, in this case "Schoolyear", but could be any dimension attribute. For "Wilma" it wil be the Grade in "2010 / 2011" and for "Fred" the grade in "2011 / 2012".
I tried to limit the measure on the All member to the lastChild but this wont work. In the example below I have a working query but it's not dynamic because "Schoolyear" "2010 / 2011" is not dynamic but hardcoded.
MEMBER [Measures].[GradeFixed] AS
Iif( [Dimension School].[Schoolyear].Currentmember IS
[Dimension School].[Schoolyear].[All],
[Dimension School].[Schoolyear].[2011 / 2012]
,
[Measures].[Grade] )

Has anyone an idea to limit this measure dynamicly to the last element in a dimension for the All element?

A: Scope (
    [Dimension School].[Schoolyear].[All],
    [Measures].[Grade]
);
This = Tail (
    NonEmpty (
        [Dimension School].[Schoolyear].[Schoolyear],
        [Measures].[Grade]
    ), 1
).item(0)


text:
Q: When using the spread syntax, should I copy the whole object, level by level? When using Redux, I have my initial state:
const initialState = {
  foo: {
    bar: {
      foobar: 1,
      barfoo: 2
    }
  },
  xyz: true,
  abc: {
    jkl: [1,2,3,4]
  }
}

Then I have the reducer, and inside a switch. Suppose I have a case X in which I want to change xyz to false.
Is this enough?
return {
  ...state,
  xyz: false
}

or should I do?
return {
  foo: {
    bar: {
      ...state.foo.bar
    }
  },
  xyz: false,
  abc: {
    jkl: [...state.abc.jkl]
  }
}

A: No need to do your second implementation! That would create a catastrophe of reducers lol.
Just use:
return {
  ...state,
  xyz: false
}

Not only is this the way that is advised in Redux apps, imagine having to debug reducers where you use your second implementation, and you make typos.
On the case of nested properties, you would need to do something like this:
return {
   ...state,
   foo: {
      bar: { ...state.foo.bar, roflWaffle: 3 }
   }
}

Also, recommend checking out other answers here too, very helpful in depth information that will greatly help you understand how JavaScript and Redux works under the hood.

A: It is enough if you are aware that the spread operator only does a shallow clone:

const a = {x: {y: 10}};
const b = {...a};

b.x.y = 42;

console.log(b.x.y); //=> 42
console.log(a.x.y); //=> 42

I understand that with Redux you want to return new state. Just know that this potentially opens up the gate to unwanted mutations and side effects.
With this simple example, I have shown how a simple reducer can potentially tamper with the history of your Redux states.

A: Dan's answer gives you a practical and working syntax (do that! it's cleaner), but let's understand why.
Each spread copy is shallow, not deep. Only the first level is duplicated. For example, let's say you attempt to clone an object this way:
> let original = { someNumber: 1, someArray: [1, 2] }
> let copy = { ...original }

The objects original and copy are distinct. If you set properties, they won't reflect each other.
> x2.someNumber = 2
> x2.newProperty = "hello"

> console.log(x1)
{ someNumber: 1, someArray: [1,2] } // same someNumber, no newProperty!

But the value of each individual key is not duplicated, it's just a reference to the original. The someArray property references the very same array instance in both objects. So:
> console.log(x1.someArray)
[1, 2]

> x2.someArray.push(3)
> console.log(x1.someArray)
[1, 2, 3]

Both original.someArray and copy.someArray are referencing the same array instance. Two references in two objects, but only one underlying array.
There's no easy, 100% foolproof way to actually clone an object, because not all objects are simple JSON-like dictionaries. But you have some options in this other answer.
When working with React and Redux, many problems can be avoided by using a library like ImmutableJS, which ensures each object is distinct and every modification produces a different object. The performance is good and the syntax more comfortable in many cases, as well.


text:
Q: How can I use MOSFETs to increase the power rating of an output? I have a board that drives three bistable relays for turning on/off three 12V loads.
To switch the relays, the board provides 6 outputs that connects a battery-negative pulse of 150ms at a maximum power rating of 10W at 12V. Each of these outputs drives one of the two coils (either on/off) of one of the 3 relays.
However the relays require a 150ms pulse of 36W at 12V, which is too much for the board to handle.
I plan to get 6 MOSFETs to increase the power rating of these outputs. I will connect each MOSFET gate pin to a board output, the source to the battery positive. This way, when the board attempts to switch a relay, it will apply a voltage between the gate and the source and turn the MOSFET on. The drain pin of the MOSFET goes to the relay coil (the other side being connected to the battery negative).
I think I need N-channel MOSFETs with a minimum voltage gate-source threshold (VGSTH) of ~10V and a maximum drain-source voltage of at least 15V. Considering how brief and infrequent the pulse will be I don't think the other specs really matter, but ideally the drain/source resistance when on (RDS-on) of as low as possible.
Will this work? Am I speccing the MOSFETs needed correctly?

A: Gate-source voltage threshold is the value when the MOSFET just barely starts to conduct. In other words, you don't care about that value for MOSFETs used as a switch. What you care about is the Vgs used to achieve the rated RDson.
You also do not need a MOSFET whos rated RDson is achieved at the 12V your board outputs. As long as the Vgs at which the MOSFET achieves its rated RDson is lower than 12V your board sends to it, and 12V is lower than the maximum tolerable Vgs, you are fine.


text:
Q: ITextSharp PdfReader not opening PDF file I am putting together a proof of concept application that will run on a Windows 8.1 tablet using C# and the ITextSharp library.  The requirements for the proof of concept is the ability to use the FileOpenPicker class to select a PDF file, load the file to memory, fill in the form fields of the PDF programmatically and then save the file to a new location.
I have the proof of concept working, if the source PDF file is installed with the application itself within the application installed location (Windows.ApplicationModel.Package.Current.InstalledLocation.Path) however if I put the source PDF someplace else, and use the FileOpenPicker to let the user pick the PDF file, the PdfReader throws the following exception:
C:\\aaa\\PDFTemplates\\ScribusPDF2.tpdf not found as file or resource.

Note I am using the tpdf extension to signify a PDF template file for my application however this still does not work even if I use the standard pdf extension.
Here is my code for the file picker:
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
openPicker.FileTypeFilter.Add(".tpdf");

StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
           StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFileToken", file);
    String path = file.Path.ToString();
    var reader = new PdfReader(path);
}
else
{
    Debug.WriteLine("Operation cancelled.");
}

It is the var reader = new PdfReader(path); line that causes the exception.  My first thought was I had a permission issue so I added the .tpdf extension and the Documents Library capability to the manifest file like this:
<Extensions>
    <Extension Category="windows.fileTypeAssociation">
      <FileTypeAssociation Name="pdf_template">
       <DisplayName> PDF Template</DisplayName>
       <SupportedFileTypes>
          <FileType>.tpdf</FileType
       </SupportedFileTypes>
      </FileTypeAssociation>
     </Extension>
</Extensions>

And
<Capability Name="documentsLibrary" />
    <Capability Name="internetClient" />
</Capabilities>

I still got the same error so I wrote a test routine to see if I could access the file outside of iTextSharp.  This route has the following code:
Debug.WriteLine("Checking:  " + templatePath);
StorageFile file = await StorageFile.GetFileFromPathAsync(templatePath);
var read = await FileIO.ReadBufferAsync(file);
var prop = await file.GetBasicPropertiesAsync();
Debug.WriteLine("Passed: " + templatePath);

This code works perfectly and does not throw an error therefore I know that the file (with path) exists and I have permission to access the file however the PdfReader with iTextSharp still throws the above exception when it tries to read the file.
Does anyone know what could be causing this issue?
Below is the full stack trace:
   at iTextSharp.text.io.RandomAccessSourceFactory.CreateByReadingToMemory(String filename)
   at iTextSharp.text.io.RandomAccessSourceFactory.CreateBestSource(String filename)
   at iTextSharp.text.pdf.PdfReader..ctor(String filename, Byte[] ownerPassword, Boolean partial)
   at iTextSharp.text.pdf.PdfReader..ctor(String filename, Byte[] ownerPassword)
   at iTextSharp.text.pdf.PdfReader..ctor(String filename)
   at PDFFromTemplateTest.MainPage.<findFile>d__0.MoveNext()

EDIT:  Answer
Based on the comment from Chris Hass and also other information I read last night I ended up not relying on the PdfReader to read the file.  I changed this line:
var reader = new PdfReader(path);

to this:
StorageFile file = await StorageFile.GetFileFromPathAsync(templatePath);
var buf = await FileIO.ReadBufferAsync(file);
var reader = new PdfReader(buf.ToArray());

and everything worked as expected.

A: Based on the comment from Chris Hass and also other information I read last night I ended up not relying on the PdfReader to read the file. I changed this line:
var reader = new PdfReader(path);

to this:
StorageFile file = await StorageFile.GetFileFromPathAsync(templatePath);
var buf = await FileIO.ReadBufferAsync(file);
var reader = new PdfReader(buf.ToArray());

and everything worked as expected.


text:
Q: Do I need to remove breakpoints before building release exe? I'm testing a Visual Studio C# program mostly in debug mode with breakpoints. Sometimes I need to build the release version .exe to run some tests, but then go back to testing in debug mode.
Before I build the release version I'm not removing my breakpoints. Is there any reason to remove the breakpoints? Does anything carry over to the release exe? I don't see anything, but i just want to be sure.
Thanks!

A: Back in the good old days, you could have an INT 3 machine instruction in the binary code of exe and dll files, which is the assembly definition of a breakpoint and would (and still will) cause to break into a debugger. No .NET compiler/linker does that. Actually, it cannot - because managed exe files contain IL which is just-in-time compiled.
In .NET and especially in the Microsoft environment, breakpoints are a feature of the IDE in connection with
the runtime, and never end up in the binary.
An old, but thorough writeup of the mechanism of managed breakpoints can be found here: https://blogs.msdn.microsoft.com/jmstall/2004/12/28/how-do-managed-breakpoints-work/
Breakpoints are stored in a configuration file of the VS solution only for convenience (so developers would not lose their breakpoitns between Visual Studio sessions).
In contrast, a Debug.Assert call can cause harm in release builds, if used or configured incorrectly.


text:
Q: Hibernate Stored Procedure returning same value for multiple calls I have a stored procedure which returns me more than one result set. The output varies for different inputs to the stored procedure.
When I call the stored procedure separately (2 runs) with different inputs, it is returning as expected.
When I call them twice withing a same method,it is returning the same value.
@NamedNativeQuery(
              name = "getFees",
              query = "call SCHEMA1.RES_FEES(:id,:type,:orig,:dest)",
              resultClass = Fees.class)

For ex: id=1, type="R", orig="Vegas" dest="London" it returns fee to be $100
for id=2, type="V", orig="London" dest="Vegas" it returns fee to be $90
When i execute the SP with with ip1 separately it returns $100
When i execute the SP with with ip2 separately it returns $90
But when i execute the SP twice withing a same method in JAVA with different sets of input, it returns $100 twice.
What could be the problem?

A: Weird problem. Here are few suggestions and tests that you can do to debug the issue.

*

*Switch on the query log of hibernate and see if there any abnormal thing.

*Check if you are using  second level caching in your application. If yes disable it and run your test again to see if there is any issue with caching.


text:
Q: c# ftp client retry delay i was able to create a basic ftp client that is working, but i want to make it more robust.  one of the features i want to add is retry delay (The time between each retry).  unfortunately i couldn't find a lot of materials online.  can someone help me?  thanks.

A: How about using System.Threading.Thread.Sleep() ?

Thread.Sleep Method
Blocks the current thread for the specified number of milliseconds.


text:
Q: Update button on VS works SQL SP, on IIS it just saves the information already there, no update I have a web form that shows some header information, you can change that information (text boxes, check box, etc.) and hit the update information button to post the information to a SQL Stored Procedure..
When I run this on Visual Studio and hit the button the information gets updated.
====VISUAL STUDIO====
declare @p14 varchar(200)
set @p14=NULL
declare @p15 int
set @p15=NULL
exec DLI_BENEFITS_HEADER_UPDATE @EMP_ID=N'ADA04',@K401_TYPE=N'DECLINED',@CONTRIBUTION_RATE_401K_AMOUNT=NULL,@CONTRIBUTION_RATE_401K_PCT=NULL,@COMPANY_LIFE_EMP=1,@COMPANY_LIFE_SPOUSE=0,@COMPANY_LIFE_CHILD=1,@COMPANY_LIFE_DEPENDENTS=99,@HEALTH_DECLINE=1,@DENTAL_DECLINE=0,@VISION_DECLINE=1,@LIFE_DECLINE=0,@NOTES=N'MY RECORD NEW RECORD INFO',@SP_MESSAGE=@p14 output,@SP_ERROR_NUMBER=@p15 output
select @p14, @p15
go
exec sp_reset_connection
go

When I run the exact same thing in IIS it basically just puts the information back into SQL as if nothing had changed.
=====IIS=====
declare @p14 varchar(200)
set @p14=NULL
declare @p15 int
set @p15=NULL
exec DLI_BENEFITS_HEADER_UPDATE @EMP_ID=N'ADA04',@K401_TYPE=N'DECLINED',@CONTRIBUTION_RATE_401K_AMOUNT=NULL,@CONTRIBUTION_RATE_401K_PCT=NULL,@COMPANY_LIFE_EMP=1,@COMPANY_LIFE_SPOUSE=0,@COMPANY_LIFE_CHILD=1,@COMPANY_LIFE_DEPENDENTS=99,@HEALTH_DECLINE=1,@DENTAL_DECLINE=0,@VISION_DECLINE=1,@LIFE_DECLINE=0,@NOTES=N'MY RECORD NEW RECORD INFO',@SP_MESSAGE=@p14 output,@SP_ERROR_NUMBER=@p15 output
select @p14, @p15

I changed in the textbox 99 to 4 and MY RECORD NEW RECORD to MY RECORD NEW RECORD INFO WITH NEW NOTES HERE and hit the submit button.
@COMPANY_LIFE_DEPENDENTS=99 to 4
and @NOTES to @NOTES=N'MY RECORD NEW RECORD INFO WITH NEW NOTES HERE'
I am not sure what I am missing here.. sorry if it is something pretty basic and I should know better, but I have searched around trying to figure it out.
The SQL connection is SQL username and password not integrated.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EmployeeBenefits.aspx.cs" Inherits="DLI_EMPLOYEE_BENEFITS.EmployeeBenefits" MaintainScrollPositionOnPostback="true" %>

<!DOCTYPE html>

    <title>DLI Employee Benefit Maintenance</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="/resources/demos/style.css">

    <form id="form1" runat="server">

                EMPLOYEE BENEFIT MAINTENANCE

                        EMP ID :

                            <asp:TextBox ID="tbEMPLOYEE_ID" runat="server" Width="92px"></asp:TextBox>
                            <asp:ImageButton ID="ibGET" runat="server" ImageUrl="~/Image/elcmark.png" OnClick="ibGET_Click" />
                            <asp:ImageButton ID="ibRESET" runat="server" ImageUrl="~/Image/reset.png" PostBackUrl="https://dlihome.deseretlabs.com/HR/EMP_BENEFITS/EmployeeBenefits.aspx" />

                            <asp:Label ID="lbEMPLOYEE_NAME" runat="server" Text="DOE, JOHN" Font-Bold="True" Font-Size="X-Large" ForeColor="Red"></asp:Label>

                        HIRE DATE :

                            <asp:Label ID="lbHIRE_DATE" runat="server"></asp:Label>

                        ENROLL DATE :

                            <asp:Label ID="lbENROLL_DATE" runat="server"></asp:Label>

                        INITAL MEETING :

                            <asp:Label ID="lbINITIAL_MEETING" runat="server"></asp:Label>
                            <asp:ImageButton ID="ibINITIAL_DATE" runat="server" ImageUrl="~/Image/plus16.gif" />

                        401K :

                            <asp:DropDownList ID="ddl401_TYPE" runat="server">
                                <asp:ListItem></asp:ListItem>
                                <asp:ListItem>DECLINED</asp:ListItem>
                                <asp:ListItem>401K</asp:ListItem>
                                <asp:ListItem>ROTH</asp:ListItem>
                            </asp:DropDownList>
   ♦
                            <asp:TextBox ID="tb401_PCT" runat="server" Width="25px" Wrap="False" style="text-align:center"></asp:TextBox>
  PERCENT  ♦  $
                            <asp:TextBox ID="tb401_AMOUNT" runat="server" Width="64px" Wrap="False"></asp:TextBox>
 AMOUNT

                        COMPANY LIFE :
                         <asp:CheckBox ID="cbCOMP_LIFE_EMP" runat="server" Text="EMPLOYEE" />
                              ♦  <asp:CheckBox ID="cbCOMP_LIFE_SPOUSE" runat="server" Text="SPOUSE" />
                              ♦  <asp:CheckBox ID="cbCOMP_LIFE_CHILDREN" runat="server" Text="CHILDREN" />
                              ♦  <asp:TextBox ID="TbCOMP_LIFE_DEPENDENTS" runat="server" Width="25px" Wrap="False" style="text-align:center"></asp:TextBox>
 DEPENDENTS

                        DECLINED BENEFITS :

                            <asp:CheckBox ID="cbDECLINE_HEALTH" runat="server" Text="HEALTH" />
                              ♦  <asp:CheckBox ID="cbDECLINE_DENTAL" runat="server" Text="DENTAL" />
                              ♦  <asp:CheckBox ID="cbDECLINE_VISION" runat="server" Text="VISION" />
                              ♦  <asp:CheckBox ID="cbDECLINE_LIFE" runat="server" Text="VOLUNTARY LIFE" />

                        NOTES:

                            <asp:TextBox ID="tbNOTES" runat="server" style="margin-left: 0px" TextMode="MultiLine" Width="100%" Height="50px"></asp:TextBox>

                            <asp:ImageButton ID="ibUPDATE_HEADER" runat="server" ImageUrl="~/Image/button_update-record.png" OnClick="ibUPDATE_HEADER_Click" />

                            <asp:Label ID="lblSPMessageSuccess" runat="server"></asp:Label><asp:Label ID="lblSPMessageError" runat="server"></asp:Label>

                <asp:GridView ID="gvEnrolledBenfits" runat="server" AllowPaging="True" AutoGenerateColumns="False" CellPadding="4" DataSourceID="dsEnrolledBenefits" Width="100%" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px">
                    <Columns>
                        <asp:BoundField DataField="INS_DESCRIPTION" HeaderText="DESCRIPTION" SortExpression="INS_DESCRIPTION">
                        <HeaderStyle Font-Bold="True" Font-Size="Small" HorizontalAlign="Center" VerticalAlign="Middle" Width="20%" />
                        <ItemStyle Font-Size="Small" HorizontalAlign="Center" VerticalAlign="Middle" />
                        </asp:BoundField>
                        <asp:BoundField DataField="AMOUNT" DataFormatString="{0:c}" HeaderText="AMOUNT PPC" SortExpression="AMOUNT" >
                        <HeaderStyle Font-Bold="True" Font-Size="Small" HorizontalAlign="Center" VerticalAlign="Middle" Width="10%" />
                        <ItemStyle Font-Size="Small" HorizontalAlign="Center" VerticalAlign="Middle" Width="10%" />
                        </asp:BoundField>
                        <asp:BoundField DataField="LIFE_AMOUNT" DataFormatString="{0:c}" HeaderText="LIFE AMOUNT" SortExpression="LIFE_AMOUNT" >
                        <HeaderStyle Font-Bold="True" Font-Size="Small" HorizontalAlign="Center" VerticalAlign="Middle" Width="10%" />
                        <ItemStyle Font-Size="Small" HorizontalAlign="Center" VerticalAlign="Middle" Width="10%" />
                        </asp:BoundField>
                        <asp:BoundField DataField="DEPENDENT_CHIDREN" HeaderText="DEPENDENT CHIDREN" SortExpression="DEPENDENT_CHIDREN" >
                        <HeaderStyle Font-Bold="True" Font-Size="Small" HorizontalAlign="Center" VerticalAlign="Middle" Width="10%" />
                        <ItemStyle Font-Size="Small" HorizontalAlign="Center" VerticalAlign="Middle" Width="10%" />
                        </asp:BoundField>
                        <asp:BoundField DataField="START_DATE" DataFormatString="{0:d}" HeaderText="START DATE" SortExpression="START_DATE" >
                        <HeaderStyle Font-Bold="True" Font-Size="Small" HorizontalAlign="Center" VerticalAlign="Middle" Width="10%" />
                        <ItemStyle Font-Size="Small" HorizontalAlign="Center" VerticalAlign="Middle" Width="10%" />
                        </asp:BoundField>
                        <asp:BoundField DataField="END_DATE" DataFormatString="{0:d}" HeaderText="END DATE" SortExpression="END_DATE" >
                        <HeaderStyle Font-Bold="True" Font-Size="Small" HorizontalAlign="Center" VerticalAlign="Middle" Width="10%" />
                        <ItemStyle Font-Size="Small" HorizontalAlign="Center" VerticalAlign="Middle" Width="10%" />
                        </asp:BoundField>
                    </Columns>
                    <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
                    <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
                    <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
                    <RowStyle BackColor="White" ForeColor="#330099" />
                    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
                    <SortedAscendingCellStyle BackColor="#FEFCEB" />
                    <SortedAscendingHeaderStyle BackColor="#AF0101" />
                    <SortedDescendingCellStyle BackColor="#F6F0C0" />
                    <SortedDescendingHeaderStyle BackColor="#7E0000" />
                </asp:GridView>

                <asp:SqlDataSource ID="dsEnrolledBenefits" runat="server" ConnectionString="<%$ ConnectionStrings:PAYROLL %>" SelectCommand="DLI_BENEFITS_EMPLOYEE_ENROLLED" SelectCommandType="StoredProcedure">
                    <SelectParameters>
                        <asp:ControlParameter ControlID="tbEMPLOYEE_ID" Name="EID" PropertyName="Text" Type="String" />
                    </SelectParameters>
                </asp:SqlDataSource>

    </form>

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Data.SqlClient;
    using System.Configuration;

    namespace DLI_EMPLOYEE_BENEFITS
    {
        public partial class EmployeeBenefits : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                //if (!IsPostBack)

                //{

                //    lbEMPLOYEE_NAME.Text = "";
                //    tbEMPLOYEE_ID.Text = "";
                //}

                ibINITIAL_DATE.Visible = false;
                lblSPMessageSuccess.Text = "";

                string qsEmpID = Request.QueryString["qsEmpID"];

                if (string.IsNullOrEmpty(qsEmpID))
                {

                }
                else
                {
                    tbEMPLOYEE_ID.Text = qsEmpID.ToUpper();
                    MyLookup();

                }
            }

            protected void ibGET_Click(object sender, ImageClickEventArgs e)
            {
                MyLookup();
            }

            private void MyLookup()
            {
                if (string.IsNullOrEmpty(tbEMPLOYEE_ID.Text))
                {
                    lbEMPLOYEE_NAME.Text = "INVALID EMPLOYEE ID";
                }
                else
                {
                    lbEMPLOYEE_NAME.Text = tbEMPLOYEE_ID.Text.ToUpper();
                    tbEMPLOYEE_ID.Text = tbEMPLOYEE_ID.Text.ToUpper();

                    int EmpID = -1;

                    string constr = ConfigurationManager.ConnectionStrings["PAYROLL"].ConnectionString;
                    using (SqlConnection con = new SqlConnection(constr))
                    {
                        using (SqlCommand cmd = new SqlCommand("DLI_BENEFITS_EMP_ID_VALIDATE"))
                        {

                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.AddWithValue("@EmployeeID", tbEMPLOYEE_ID.Text.ToUpper());
                            cmd.Connection = con;
                            con.Open();
                            EmpID = Convert.ToInt32(cmd.ExecuteScalar());
                            con.Close();
                        }
                    }

                    if (EmpID != -1)
                    {
                        using (SqlConnection con = new SqlConnection(constr))
                        {
                            using (SqlCommand cmd = new SqlCommand("DLI_BENEFITS_HEADER"))
                            {

                                cmd.CommandType = CommandType.StoredProcedure;
                                cmd.Parameters.AddWithValue("@EmployeeID", tbEMPLOYEE_ID.Text.ToUpper());
                                cmd.Connection = con;
                                con.Open();
                                SqlDataReader dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                                while (dataReader.Read())
                                {

                                    lbEMPLOYEE_NAME.Text = dataReader["EMPLOYEE_NAME"].ToString();
                                    ddl401_TYPE.SelectedValue = dataReader["401K_TYPE"].ToString();
                                    tb401_PCT.Text = dataReader["CONTRIBUTION_RATE_401K_PCT"].ToString();
                                    tb401_AMOUNT.Text = dataReader["CONTRIBUTION_RATE_401K_AMOUNT"].ToString();
                                    cbCOMP_LIFE_EMP.Checked = Convert.ToBoolean(dataReader["COMPANY_LIFE_EMP"]);
                                    cbCOMP_LIFE_SPOUSE.Checked = Convert.ToBoolean(dataReader["COMPANY_LIFE_SPOUSE"]);
                                    cbCOMP_LIFE_CHILDREN.Checked = Convert.ToBoolean(dataReader["COMPANY_LIFE_CHILD"]);
                                    TbCOMP_LIFE_DEPENDENTS.Text = dataReader["COMPANY_LIFE_DEPENDENTS"].ToString();
                                    cbDECLINE_HEALTH.Checked = Convert.ToBoolean(dataReader["HEALTH_DECLINE"]);
                                    cbDECLINE_DENTAL.Checked = Convert.ToBoolean(dataReader["DENTAL_DECLINE"]);
                                    cbDECLINE_VISION.Checked = Convert.ToBoolean(dataReader["VISION_DECLINE"]);
                                    cbDECLINE_LIFE.Checked = Convert.ToBoolean(dataReader["LIFE_DECLINE"]);
                                    tbNOTES.Text = dataReader["NOTES"].ToString();
                                    lbENROLL_DATE.Text = Convert.ToDateTime(dataReader["ENROLL"]).ToString("MM/dd/yyyy");
                                    lbHIRE_DATE.Text = Convert.ToDateTime(dataReader["HIRE_DATE"]).ToString("MM/dd/yyyy");
                                    lbINITIAL_MEETING.Text = "";
                                    ibINITIAL_DATE.Visible = true;
                                    if (dataReader["INIT_MEETING"].GetType() != typeof(DBNull))
                                    {
                                        lbINITIAL_MEETING.Text = Convert.ToDateTime(dataReader["INIT_MEETING"]).ToString("MM/dd/yyyy");
                                        ibINITIAL_DATE.Visible = false;
                                    }

                                }
                                con.Close();
                            }

                        }
                    }
                    else
                    {

                        lbEMPLOYEE_NAME.Text = tbEMPLOYEE_ID.Text.ToUpper() + " is not valid.";
                    }

                }
            }

            protected void ibUPDATE_HEADER_Click(object sender, ImageClickEventArgs e)
            {
                string @EMP_ID = Convert.ToString(tbEMPLOYEE_ID.Text).ToUpper();
                string @K401_TYPE = Convert.ToString(ddl401_TYPE.SelectedValue).ToUpper();
                string @NOTES = Convert.ToString(tbNOTES.Text).ToUpper();

                string cnString = ConfigurationManager.ConnectionStrings["PAYROLL"].ConnectionString;

                //Response.Write(cnString);

                lblSPMessageSuccess.Text = "";

                SqlConnection cn = null;
                try
                {
                    cn = new SqlConnection(cnString);
                    cn.Open();
                    SqlCommand cmd = new SqlCommand("DLI_BENEFITS_HEADER_UPDATE", cn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@EMP_ID", @EMP_ID);
                    cmd.Parameters.AddWithValue("@K401_TYPE", @K401_TYPE.ToString());

                    if (decimal.TryParse(tb401_AMOUNT.Text, out decimal parsed))
                    {
                        cmd.Parameters.AddWithValue("@CONTRIBUTION_RATE_401K_AMOUNT", decimal.Parse(tb401_AMOUNT.Text));
                    }
                    else
                    {
                        cmd.Parameters.AddWithValue("@CONTRIBUTION_RATE_401K_AMOUNT", DBNull.Value);
                    }

                    if (Int16.TryParse(tb401_PCT.Text, out Int16 parsed1))
                    {
                        cmd.Parameters.AddWithValue("@CONTRIBUTION_RATE_401K_PCT", Int16.Parse(tb401_PCT.Text));
                    }
                    else
                    {
                        cmd.Parameters.AddWithValue("@CONTRIBUTION_RATE_401K_PCT", DBNull.Value);
                    }

                    cmd.Parameters.AddWithValue("@COMPANY_LIFE_EMP", cbCOMP_LIFE_EMP.Checked);
                    cmd.Parameters.AddWithValue("@COMPANY_LIFE_SPOUSE", cbCOMP_LIFE_SPOUSE.Checked);
                    cmd.Parameters.AddWithValue("@COMPANY_LIFE_CHILD", cbCOMP_LIFE_CHILDREN.Checked);

                    if (Int16.TryParse(TbCOMP_LIFE_DEPENDENTS.Text, out Int16 parsed2))
                    {
                        cmd.Parameters.AddWithValue("@COMPANY_LIFE_DEPENDENTS", Int16.Parse(TbCOMP_LIFE_DEPENDENTS.Text));
                    }
                    else
                    {
                        cmd.Parameters.AddWithValue("@COMPANY_LIFE_DEPENDENTS", DBNull.Value);
                    }

                    cmd.Parameters.AddWithValue("@HEALTH_DECLINE", cbDECLINE_HEALTH.Checked);
                    cmd.Parameters.AddWithValue("@DENTAL_DECLINE", cbDECLINE_DENTAL.Checked);
                    cmd.Parameters.AddWithValue("@VISION_DECLINE", cbDECLINE_VISION.Checked);
                    cmd.Parameters.AddWithValue("@LIFE_DECLINE", cbDECLINE_LIFE.Checked);
                    cmd.Parameters.AddWithValue("@NOTES", @NOTES.ToString());
                    cmd.Parameters.Add("@SP_MESSAGE", SqlDbType.VarChar, 200).Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@SP_ERROR_NUMBER", SqlDbType.Int).Direction = ParameterDirection.Output;
                    cmd.ExecuteNonQuery();

                    int output = (int)cmd.Parameters["@SP_ERROR_NUMBER"].Value;
                    string output_message = (string)cmd.Parameters["@SP_MESSAGE"].Value;

                    if (output == -1)
                    {
                        lblSPMessageSuccess.Text = "";
                        lblSPMessageError.Text = output_message;
                    }
                    else
                    {
                        lblSPMessageError.Text = "";
                        lblSPMessageSuccess.Text = output_message;

                        //dsEnrolledBenefits.EnableCaching = false;
                        //dsEnrolledBenefits.EnableCaching = true;
                        //this.dsEnrolledBenefits.DataBind();
                        //this.gvOpenProjects.DataBind();

                    }
                }

                catch (Exception ex)
                {
                    lblSPMessageError.Text = ex.Message;
                }
                finally
                {
                    if (cn != null)
                    {
                        cn.Close();
                        MyLookup();
                    }
                }

            }
        }
    }

USE [PAYDEMO]
GO

/****** Object:  StoredProcedure [dbo].[DLI_BENEFITS_HEADER_UPDATE]    Script Date: 7/23/2019 8:46:39 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[DLI_BENEFITS_HEADER_UPDATE]
      @EMP_ID [varchar](15),
      @K401_TYPE [nvarchar](10),
      @CONTRIBUTION_RATE_401K_AMOUNT [decimal](12, 2),
      @CONTRIBUTION_RATE_401K_PCT [tinyint],
      @COMPANY_LIFE_EMP [bit],
      @COMPANY_LIFE_SPOUSE [bit],
      @COMPANY_LIFE_CHILD [bit],
      @COMPANY_LIFE_DEPENDENTS [tinyint],
      @HEALTH_DECLINE [bit],
      @DENTAL_DECLINE [bit],
      @VISION_DECLINE [bit],
      @LIFE_DECLINE [bit],
      @NOTES [nvarchar](max),
      @SP_MESSAGE varchar(200) OUTPUT,
      @SP_ERROR_NUMBER int OUTPUT

AS
BEGIN

SET @SP_ERROR_NUMBER = 0

IF @SP_ERROR_NUMBER = 0
BEGIN

UPDATE       EMPLOYEE_PTO_401k
SET                [401K_TYPE] = @K401_TYPE, CONTRIBUTION_RATE_401K_AMOUNT = @CONTRIBUTION_RATE_401K_AMOUNT, CONTRIBUTION_RATE_401K_PCT = @CONTRIBUTION_RATE_401K_PCT, COMPANY_LIFE_EMP = @COMPANY_LIFE_EMP,
                         COMPANY_LIFE_SPOUSE = @COMPANY_LIFE_SPOUSE, COMPANY_LIFE_CHILD = @COMPANY_LIFE_CHILD, COMPANY_LIFE_DEPENDENTS = @COMPANY_LIFE_DEPENDENTS, HEALTH_DECLINE = @HEALTH_DECLINE, DENTAL_DECLINE = @DENTAL_DECLINE,
                         VISION_DECLINE = @VISION_DECLINE, LIFE_DECLINE = @LIFE_DECLINE, NOTES = @NOTES
WHERE        (EMP_ID = @EMP_ID)

SELECT @SP_MESSAGE = 'RECORD UPDATED SUCCESSFULLY',  @SP_ERROR_NUMBER = 0
END

END

Any help is greatly appreciated.

A: Accoridng to your description and codes, I found you call the MyLookup in the page load method. If the query string qsEmpID has the value. It will call the MyLookup method again.
If you call button click event, it will re-binding the server control if the query string has the value before calling the update method. I suggest you could re-desgin your page load method.


text:
Q: having problems saving data to a text file the data isn't saving correctly, the first loop of the for loop gives us random characters, however the following loop gives us the correct numbers
any help would be greatly appreciated
int    saveDroneSimResults(delivery_info deliveryinfo, int no_of_deliveries){
        int numdel, i;
        numdel = no_of_deliveries;

        printf("NUM DEL: %d\n\n", numdel);

        FILE file = fopen("results.txt", "w");
        if(file == NULL){

            printf("ERROR! The file failed to open!\n");
            exit(-1);

        }

        for(i=0; i < numdel; i++){

            fprintf(file, "%d %d %19s %.2lf %.2lf %.2lf %.2lf %.2lf %.2lf %.2lf %.2lf\n", deliveryinfo[i].deliveryID,
            deliveryinfo[i].drone_ID, deliveryinfo[i].drone_name, deliveryinfo[i].max_distance , deliveryinfo[i].load_capacity ,
            deliveryinfo[i].Delivery_Orig_loc_x , deliveryinfo[i].Delivery_Orig_loc_y , deliveryinfo[i].Delivery_Desti_loc_x ,
            deliveryinfo[i].Delivery_Desti_loc_y , deliveryinfo[i].load_capacity, deliveryinfo[i].Delivery_distance);
        }

        fclose(file);

        return 0;

A: I'm not sure how you're not getting an error message, but you're missing * (FILE *file = fopen(...)).

A: If it is working correctly when i = 1, then you could just change your for loop to:
for(i =1; i< numdel; i++)

With the code given, I can't know if the rest is wrong as I do not know anything about deliveryinfo. It may help you to debug the code if you separate the one long fprintf into multiple different fprintf statements.
I would change it to:
fprintf(file,"%d %d ",deliveryinfo[i].deliveryID, deliveryinfo[i].drone_ID);
fprintf(file, "%19s %.2lf ",deliveryinfo[i].drone_name, deliveryinfo[i].max_distance);
fprintf(file, "%.2lf %.2lf ",deliveryinfo[i].load_capacity ,
            deliveryinfo[i].Delivery_Orig_loc_x);
fprintf(file, "%.2lf %.2lf ", deliveryinfo[i].Delivery_Orig_loc_y , deliveryinfo[i].Delivery_Desti_loc_x );
fprintf(file, "%.2lf %.2lf "deliveryinfo[i].Delivery_Desti_loc_y , deliveryinfo[i].load_capacity);
fprintf(file, "%.2lf\n", deliveryinfo[i].Delivery_distance);

Purely to make the code easier for you and anyone else to read in the future. You could have 3 variable per fprintf as well but anything more than 3 becomes more difficult to check quickly.
For further trouble shooting, I recommend you take a look at the contents of delivery info and ensure that what is stored there is correct for what you want.
Edit: as @Majkl pointed out your file open is also wrong. It should be:
 FILE *file = fopen("results.txt", "w");


text:
Q: How to get an object in Firestore (iOS) How do you get an object in Firestore by its id in Swift? I would then need to use this object to generate content in the UI. I am using SwiftUI.
The object I am trying to get is a user and it has the following structure:
struct AppUser: Codable {

    var id: String
    var displayName: String
    var photoURL: String
    var points: Int
    var knownLanguageCodes: Set<String>

}

The each document in the "users" collection has the fields in the AppUser struct. Ideally, I would like to write a function that returns an AppUser object from Firestore:
func getUser(withId id: String) -> AppUser {
    //I don't know how to write this function
}

The object would then be used like this:
struct ProfileHeadingView: View {

    let userId: String
    let user = getUser(withId: userId)

    var body: some View {
        HStack {
            ImageView(withURL: self.user.photoURL)
                .frame(width: 90, height: 90)
                .clipShape(Circle())
            VStack (alignment: .leading) {
                Text(self.user.displayName)
                    .font(.largeTitle)
                    .fontWeight(.heavy)
                HStack {
                    Text(String(self.user.points))
                        .font(.title)
                    Spacer()
                }
            }.padding(.horizontal)
        }
    }
}

A: Most of Firebase's APIs are asynchronous - this is due to the fact that most of them involve a network call, which is much slower than code gets executed on your phone!
So, your getUser method would need to be rewritten like this:
import FirebaseFirestoreSwift

func getUser(userId: String, completion: @escaping (_ user: AppUser?, _ error: Error?) -> Void) {
  db.collection("users").document(userId).getDocument { (snapshot, error) in
    let user = try? snapshot?.data(as: AppUser.self)
    completion(user, error)
  }
}

Note: to be able to use Firestore's Codable support, you will have to add pod 'FirebaseFirestoreSwift' to your Podfile
As for how (and when) to fetch the user, this largely depends on whether ProfileHeadingView is part of a list view (or is being navigated to from a list view), or not.
If it is part of a list view, I'd recommend fetching all users at once - you can either use a snapshot listener to listen for any updates to the users collection, or perform a one-time fetch to read the users collection once.
Then, from the list view, pass the respective user object into the ProfileHeadingView.


text:
Q: Android Bluetooth Connectivity with RN42 Module I'm trying to connect my app to the RN42 module.
            // Create a socket based on the application ID with a paired device
            // Fetch the published UUIDs from the mbed and use the first one
            bluetoothSocket = connectedDevice.createRfcommSocketToServiceRecord(connectedDevice.getUuids()[0].getUuid());

            // Connect to the device
            if (!bluetoothSocket.isConnected())
                bluetoothSocket.connect();

            // Create the input and output streams for sending/receiving messages
            socketInput = bluetoothSocket.getInputStream();
            socketOutput = bluetoothSocket.getOutputStream();

I've got these in the Android Manifest
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>

I'm getting this error when I call bluetoothSocket.connect().
Attempt to invoke virtual method 'void android.bluetooth.BluetoothSocket.connect()' on a null object reference

After calling this line
bluetoothSocket = connectedDevice.createRfcommSocketToServiceRecord(connectedDevice.getUuids()[0].getUuid());

I've inspected the variable bluetoothSocket using Android Studio and it's not null. It somehow becomes null when bluetoothSocket.connect() is called.
Is that the expected behaviour? What can I do to fix it? The RN42 module works fine as I've tested it with the RN Bluetooth Chat app on Play Store.
I'm on Android 5.1 on a Nexus 7 if that helps.

A: I've managed to sort the issue by removing my Bluetooth connectivity code and instead basing it around the Android Bluetooth Chat example. I don't know what the exact issue was but Bluetooth Chat example managed to fix it. Nothing obvious stands out so my best guess is, it was something subtle. If you are having a similar issue and connection between RN42 and Android is fiddly, create a sample Bluetooth Chat application and reuse that Bluetooth connectivity code.
Many less headaches! :)

A: Seethis reference guide for the module (p. 21) .
This might or might not apply to your case but is probably worth trying. They have special recommendations (default UUID and custom UUID respectively) for the module when connecting to Android devices.

A: Use the createInsecureRfcommSocketToServiceRecord instead. Insecure socket allows the RFCOMM to communicate with a non-authenticated paired device. Embedded devices like the RN42 or KC2114 have a difficult time performing authenticated pairing, because user interaction is required (numeric comparison, yes-no response). The "Just Works" automatic pairing will not produce an authenticated pairing. KC2114 supports both automatic authenticated pairing (with a small hack) and Just Works non-authenticated pairing.


text:
Q: How to show all iterations of foreach loop in a single MessageBox? As you can see by the commented code below, I'm trying to display the name and checksum for each file in a folder inside a message box. The problem is that this pops up a separate message box for each file, rather than displaying them all in one window. I realize that I need to move the MessageBox.Show() line outside of the foreach loop, but then it only displays the last file and not all of them.
What would be the code to display all the files in one message box?
// for each file in selected folder, print out its name and MD5 checksum value
   foreach (string file in Directory.GetFiles(folderBrowserDialog1.SelectedPath))
   {
       using (var md5 = MD5.Create())
       {
           using (var stream = File.OpenRead(file))
           {
               checksum = BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower();
               MessageBox.Show(file + ": " + checksum);
           }
       }
   }

A: Use a StringBuilder and then append the file/checksum to the stringbuilder object during each iteration, then call MessageBox.Show() on the stringbuilder object, for example:
StringBuilder s = new StringBuilder();
foreach (string file in Directory.GetFiles(folderBrowserDialog1.SelectedPath))
{
    using (var md5 = MD5.Create())
    {
        using (var stream = File.OpenRead(file))
        {
            checksum = BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower();
            s.AppendLine(file + ": " + checksum);
        }
    }
}
MessageBox.Show(s.ToString());

Or use:
s.AppendFormat("{0}: {1}", file, checksum).AppendLine();

Inside the loop to avoid the overhead of creating a new string for each iteration of the loop *credit goes to Destrictor*

A: The easiest way to do this is to create a List variable and add each string you want to display. After the foreach loop you add a line:
MessageBox.Show(string.Join(Environment.NewLine,MyList.ToArray()));
That should do the trick.

A: How about declaring a string variable string foo = ""; before the loop, and adding this line of code to the inside of the loop:
foo += file + ": " + checksum + System.Environment.NewLine;

And, after the loop:
MessageBox.Show(foo);


text:
Q: Android image Upload problem Hello i am wanting to upload image from android emulator to asp.net server. The code below can communicate the server. When I tried to create a text file to see the data sent from android was successful or not . But no the file data didn't send across to the server. I tried sending the plain text to the server but the file I created on the server didn't print the text.
The code here:
        HttpURLConnection conn = null;
    String boundary = "==============";

        try
        {
            String disposition = "Content-Disposition: form-data; name=\"userfile\"; filename=\"" + filename + ".jpg\"";
            String contentType = "Content-Type: application/octet-stream";

            String t1   = "Content-Disposition: form-data; name=\"test\";";
            String t2 = "Content-Type: text/plain";

            // This is the standard format for a multipart request
            StringBuffer requestBody = new StringBuffer();
            /*
            requestBody.append("--"+boundary);
            requestBody.append('\n');
            requestBody.append(disposition);
            requestBody.append('\n');
            requestBody.append(contentType);
            requestBody.append('\n');
            requestBody.append('\n');
            requestBody.append(new String(getByteFromStream(stream)));
            */

            requestBody.append('\n');
            requestBody.append('\n');
            requestBody.append("--"+boundary);
            requestBody.append('\n');
            requestBody.append(t1);
            requestBody.append('\n');
            requestBody.append(t2);
            requestBody.append('\n');
            requestBody.append('\n');
            requestBody.append("basdfsdafsadfsad");
            requestBody.append("--"+boundary+"--");

            // Make a connect to the server
            URL url = new URL(targetURL);
            conn = (HttpURLConnection) url.openConnection();

            // Put the authentication details in the request
           /*
             if (username != null) {

                String usernamePassword = username + ":" + password;
                String encodedUsernamePassword = Base64.encodeBytes(usernamePassword.getBytes());
                conn.setRequestProperty ("Authorization", "Basic " + encodedUsernamePassword);
            }
            */
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("MIME-Version:", "1.0");
            conn.setRequestProperty("Content-Type", "multipart/mixed; boundary=" + boundary);

            // Send the body
            DataOutputStream dataOS = new DataOutputStream(conn.getOutputStream());
            dataOS.writeBytes(requestBody.toString());
            dataOS.flush();
            dataOS.close();

            // Ensure we got the HTTP 200 response code
            int responseCode = conn.getResponseCode();
            if (responseCode != 200) {
                throw new Exception(String.format("Received the response code %d from the URL %s", responseCode, url));
            }

Is my request body layout not correctly ?

A: I am using asp.net for as file handler. Below is the simple Android code for the event you will use to upload the file
    String pathToOurFile = "/mnt/sdcard/sysdroid.png";//this will be the file path        String urlServer = "http://yourdomain/fileupload.aspx";
int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1*1024*1024;

    try
    {
    FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );

    URL url = new URL(urlServer);
    connection = (HttpURLConnection) url.openConnection();

    // Allow Inputs & Outputs
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    // Enable POST method
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type",  "multipart/form-data");
    connection.setRequestProperty("SD-FileName", "sysdroid.png");//This will be the file name

    outputStream = new DataOutputStream( connection.getOutputStream() );
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // Read file
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

    while (bytesRead > 0)
    {
        outputStream.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

     int serverResponseCode = connection.getResponseCode();
     String serverResponseMessage = connection.getResponseMessage();
     Log.d("ServerCode",""+serverResponseCode);
     Log.d("serverResponseMessage",""+serverResponseMessage);
    fileInputStream.close();
    outputStream.flush();
    outputStream.close();

}
    catch (Exception ex)
    {
        //ex.printStackTrace();
        Log.e("Error: ", ex.getMessage());
    }

So far so good. Lets look into the asp.net code. I used simple 'Web Form' for this. The code behind is
protected void Page_Load(object sender, EventArgs e)
{
    string uploadDir = Server.MapPath("~/images");
    string imgPath = Path.Combine(uploadDir, Request.Headers["SD-FileName"]);

    try{
        byte[]bytes = new byte[Request.InputStream.Length];
        Request.InputStream.Read(bytes, 0, bytes.Length);
        System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes);
        Bitmap btMap = (Bitmap)System.Drawing.Image.FromStream(ms);
        btMap.Save(imgPath, ImageFormat.Jpeg);
        ms.Close();
    }
    catch (Exception exp)
    {
        Response.Write(exp.Message);
    }
}

Hope this will work and you have the knowledge of read/write permissions on both Android's SD card and asp.net folders.
cheers
Fahar

A: Because you upload two files, so you should see the last format. Good luck for you.
6. Examples
Suppose the server supplies the following HTML:
 <FORM ACTION="http://server.dom/cgi/handle"
       ENCTYPE="multipart/form-data"
       METHOD=POST>
 What is your name? <INPUT TYPE=TEXT NAME=submitter>
 What files are you sending? <INPUT TYPE=FILE NAME=pics>
 </FORM>

and the user types "Joe Blow" in the name field, and selects a text
   file "file1.txt" for the answer to 'What files are you sending?'
The client might send back the following data:
    Content-type: multipart/form-data, boundary=AaB03x

    --AaB03x
    content-disposition: form-data; name="field1"

    Joe Blow
    --AaB03x
    content-disposition: form-data; name="pics"; filename="file1.txt"
    Content-Type: text/plain

     ... contents of file1.txt ...
    --AaB03x--

If the user also indicated an image file "file2.gif" for the answer
   to 'What files are you sending?', the client might client might send
   back the following data:
    Content-type: multipart/form-data, boundary=AaB03x

    --AaB03x
    content-disposition: form-data; name="field1"

    Joe Blow
    --AaB03x
    content-disposition: form-data; name="pics"
    Content-type: multipart/mixed, boundary=BbC04y

    --BbC04y
    Content-disposition: attachment; filename="file1.txt"
    Content-Type: text/plain

    ... contents of file1.txt ...
    --BbC04y
    Content-disposition: attachment; filename="file2.gif"
    Content-type: image/gif
    Content-Transfer-Encoding: binary

      ...contents of file2.gif...
    --BbC04y--
    --AaB03x--

Form-based File Upload in HTML


text:
Q: Ruby: How do I convert from UNIX struct tm? I'm trying to work with Linux's RTC in Ruby. The RTC driver via ioctl returns soemthing very similar to struct tm, as found in the standard time.h file. Alas, I cannot find a standard Ruby method that understands this structure (month number is 0-based, year is 1900-based). Short of some trivial coding, is there a standard library/object in Ruby that can convert a tm struct/array into a Time object?
The current solution is:
rtctm_raw=rtc.unpack("iiiiii")   # see rtc(4) or time.h
rtctm=[ *rtctm_raw, 0,0,0,0 ]
rtctm[4]+=1
rtctm[5]+=1900
rtc_values=Time.gm(*rtctm)

But I consider this ugly, since one would think Ruby's "gm" and "mktime" calls mirror the POSIX counterparts. But they don't. If such calls are available, I would prefer to use them.

A: If there's an offset, just apply it before creating a Time instance :
tm_struct = {
  tm_year: 117,
  tm_mon: 2,
  tm_mday: 7,
  tm_hour: 14,
  tm_min: 32,
  tm_sec: 30
}

puts Time.local(
  tm_struct[:tm_year] + 1900,
  tm_struct[:tm_mon] + 1,
  *tm_struct.values_at(:tm_mday, :tm_hour, :tm_min, :tm_sec)
)
#=> 2017-03-07 14:32:30 +0100


text:
Q: How to undo multiple steps in a Tic-Tac-Toe game in C I want to program a version of the Tic-Tac-Toe game using C, in which we have 'n × n' board decided by the user, and the loser is decided by the first who get first 'n' X's or O's in a row or column etc..
One of the requirements is to let the players be able to undo multiple steps, that means to get back to the board status as it was a couple of steps ago by entering a negative odd number.
For example, if player 1 entered '-3' as the row index, the game needs to revert back how it was 3 steps before (in case there has already been 3 steps done within the game), show the board and give the turn to player 2.
Any idea how I would be able to make such a function or at least a tip how would I start programming it?
Thanks!

A:
idea how I would be able to make such a function or at least a tip how would I start programming it?

An alternative to undoing a step it to instead keep a history (linked list) of all actively.  Replay the list sans the last one to "undo".  Less efficient yet less complicated and less error prone to undo complicated steps - which may be present in more advanced games.  Sometimes, "backing up" is wrought with subtle complexities where the prior state is not truly fully restored.  Akin to @Tom Karzes @David C. Rankin
As a bonus, you have a game record.

Consider your game has events like:

*

*Default setup-up

*Select size n.

*Select X or O to go first

*Make a move

*Rotate view

*Save game

*Restore game

*Undo last command <-- now one can undo more than just the last "move"

*etc.

A: Normally you would have a stack where you can put each new move and when you want to undo a move, you just pop it from the stack and do the reverse move on your game model.


text:
Q: Why my AngularJS + RequireJS application is not building via grunt-contrib-requirejs? I have src of my application. I use AngularJS. I use RequireJS as module loader. I use Grunt as task runner. When I run application using src: everything is good. When I build application with Grunt, application is not working. I got no errors in console.
Main thing I noticed: my code (code of my application: app.js and files under js/) does not appear in output file which is set in grunt task settings. Also, I don't think there is something about AngularJS.
Main config file:
require.config({
  paths: {
    'angular' : '../components/angular/angular',
    /* etc..... */
    'jquery': '../components/jquery/dist/jquery',
    'application': './app'
  },
  shim: {
    /* etc */
    application: {
      deps: ['angular']
    },
    angular: {
      exports : 'angular'
    }
  },
  baseUrl: '/js'
});

require(['application', 'angular', 'ngRoute', 'bootstrap' /* ngRoute and bootstrap from etc :) */], function (app) {
  app.init();
});

My app in app.js is:
define([
  'require', 'angular', 'main/main', 'common/common'
], function (require) {
  'use strict';
  var angular = require('angular');
  var app = angular.module('myApp', ['ngRoute', 'main', 'common']);
  app.init = function () {
    angular.bootstrap(document, ['myApp']);
  };
  app.config(['$routeProvider',
    function ($routeProvider) {
      $routeProvider
        ./* ... some code */

    }
  ]);

  return app;
});

I add main RequireJS config file at the end of body tag:
<script type="text/javascript" src="components/requirejs/require.js" data-main="js/bootstrap.js"></script>

Now I have problem. I have Grunt as build system. I have this task:
grunt.initConfig({
  requirejs: {
    compile: {
      options: {
        baseUrl: "public/js",
        mainConfigFile: "public/js/bootstrap.js",
        name: 'bootstrap',
        out: "build/js/bootstrap.js",
        optimize: 'none'
      }
    }
  },
  // etc

I have no optimisation, so I get ~11k lines of code in output file.
As I said. Main problem is: no AngularJS code and no application code in output file.
Why? I set up mainConfigFile correctly. Problem is in RequireJS config file? But everything is okay, when I am running my app on src.

A: It would be better if you can provide the exactly error output you get. And where you got it (from browser's console or from terminal during build process)
For now I will suggest some adjustments what could possibly help with your case.
angular: {
    exports : 'angular'
}

Here you have already export angular.js into global local variable (inside every require and define block).
And by doing var angular = require('angular'); you are possibly asynchronously override angular variable inside your app.js module.
For 'require' being added into define block, as r.js always reading what module got to be loaded in very first step, and then merged into single file. And this may confuse r.js to merging requireJS into itself.
Suggest this adjustment for your app.js:
define([ // Removed 'require' because no needed , it is already global and usable anywhere
  'angular', 'main/main', 'common/common'
], function () {
  'use strict';
  // var angular = require('angular'); // This is a very common mistake. You are not going to call angular this way, requireJS difference with commonJS.
  var app = angular.module('myApp', ['ngRoute', 'main', 'common']);
  app.init = function () {
    angular.bootstrap(document, ['myApp']);
  };
  app.config(['$routeProvider',
    function ($routeProvider) {
      $routeProvider
        ./* ... some code */

    }
  ]);

  return app;
});

And last but not least data-main="js/bootstrap.js" I think it should be js/main.js or a typo.
EDIT added explanations for 'require' in define block, and angular local variable.


text:
Q: Add collaborator to Alexa-hosted CodeCommit git repository I used ask init --hosted-skill-id=<skill_id> to pull a local copy of my skill. Running git remote -v shows the repository is hosted on AWS CodeCommit at https://git-codecommit.us-east-1.amazonaws.com/v1/repos/<skill_id>.
I can't see the CodeCommit repository in my AWS account (when logged in as root user). I also can't see any IAM roles listed in my AWS account. I considered logging in as the ask_cli_default profile generated by ask configure but it only has an access key and secret; no password.
Which AWS account holds the Alexa-hosted CodeCommit repositories? Is there any way to grant access to another account?

Other potentially relevant tidbits

*

*Context: Yesterday I created a skill in the Alexa developer console based on a Hello World template. Now I want to share it with a friend so we can develop it together. Ideally we would both be able to push to a shared git repository, build, deploy, and test using the simulator in Alexa developer console.

*ask --version = 2.20.0

*I can git clone to another local directory using the (generated) username and password from ask util git-credentials-helper.

*a question in the AWS forums Alexa Hosted sets up a CodeCommit repository -- unanswered

*official AWS docs for setting up cross-account access to CodeCommit -- Requires access to the CodeCommit repository from AWS console. This is where I want to get to.

A: Alexa Hosted is hosted in Alexa's AWS account, so it won't show up in your AWS account. Instead, it provides you with a unique (and highly constrained) AWS IAM role within the Alexa Hosted account that is tied to your skill and your Amazon developer account.
What you need to do if you want to bring in other developers is assign them Developer roles on your account so they can access the skill and its resources using their own account.
This is the documentation for adding people to your org's developer account: https://developer.amazon.com/docs/app-submission/manage-account-and-permissions.html#add_other_users


text:
Q: setState is too laggy in React I use pdf-lib(JS library) in my React project. I am doing heavy work with the library with async/await and would like to update progress bar by updating state. Even though I call setState in setTimeout, the state is updated after the heavy work ends. So the progress bar shows only 0% and 100%. Could you kindly figure it out? I can't share my code, but if you want, I will show a little.

A: Remember that "asynchronous" does not mean it runs "in parallel". It just means that code gets to run "out of order" in a controlled fashion.
Your page thread is just a single thread, so if you have a long-running function, you can mark that function as async or run it with setTimeout as much as you like but while your function code runs, nothing else gets to run (although in the case of async: only until the code hits an await, which I'm assuming pdf-kit does not use).
If you need to do heavy lifting, use a service worker, which is a special API for exactly this thing, running heavy workloads in a separate thread so that you don't block the main page thread.


text:
Q: Display a nested object in a dynamic material table template I want to display weight.name in the table. I was able to do it with transforming the data. However, I do not want to manipulate the data in any shape. I tried changing weightto weight.name in the row template ( displayedColumns ) but got back no data at all.
App.component.html

  <ng-container *ngFor="let col of displayedColumns" [matColumnDef]="col">
     {{col}}
     {{element[col]}}
  </ng-container>

App.component.ts
import { Component } from '@angular/core';

export interface PeriodicElement {
  name: string;
  position: number;
  weight: any;
  symbol: string;
}

const ELEMENT_DATA: PeriodicElement[] = [
  {position: 1, name: 'Hydrogen', weight: {name: 5.55}, symbol: 'H'},
  {position: 2, name: 'Helium', weight: {name: 5.55}, symbol: 'He'},
  {position: 3, name: 'Lithium', weight: {name: 5.55}, symbol: 'Li'},
  {position: 4, name: 'Beryllium', weight: {name: 5.55}, symbol: 'Be'},
  {position: 5, name: 'Boron', weight: {name: 5.55}, symbol: 'B'},
  {position: 6, name: 'Carbon', weight: {name: 5.55}, symbol: 'C'},
  {position: 7, name: 'Nitrogen', weight: {name: 5.55}, symbol: 'N'},
  {position: 8, name: 'Oxygen', weight: {name: 5.55}, symbol: 'O'},
  {position: 9, name: 'Fluorine', weight: {name: 5.55}, symbol: 'F'},
  {position: 10, name: 'Neon', weight: {name: 5.55}, symbol: 'Ne'},
];

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  dataSource = ELEMENT_DATA;
}

This is the stackblitz link for reference. https://stackblitz.com/edit/angular-mat-table-dynamic-columns-x36dvr?file=src%2Fapp%2Fapp.component.ts

A: Your issue is that you are displaying the weight column as row[col] or rowInstance['weight'] which displays the toString() of the weight object resulting in [object object].

*

*modify your table template to something like:

     <ng-container matColumnDef="position">
         <mat-header-cell *matHeaderCellDef> Position </mat-header-cell>
         <mat-cell *matCellDef="let row">{{row.position}}</mat-cell>
     </ng-container>
     <ng-container matColumnDef="name">
         <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
         <mat-cell *matCellDef="let row">{{row.name}}</mat-cell>
     </ng-container>
     <ng-container matColumnDef="weightName">
         <mat-header-cell *matHeaderCellDef> Weight </mat-header-cell>
         <mat-cell *matCellDef="let row">{{row.weight.name}}</mat-cell>
     </ng-container>
     <ng-container matColumnDef="symbol">
         <mat-header-cell *matHeaderCellDef> Symbol </mat-header-cell>
         <mat-cell *matCellDef="let row">{{row.symbol}}</mat-cell>
     </ng-container>

     <mat-header-row *matHeaderRowDef="displayedColumns">
     </mat-header-row>
     <mat-row *matRowDef="let row; columns: displayedColumns;">
     </mat-row>

and in your ts file, modify the display columns to:
  `displayedColumns: string[] = ['position', 'name', 'weightName', 'symbol'];`

https://stackblitz.com/edit/angular-mat-table-dynamic-columns-w7do4c?file=src/app/app.component.html

*transform/flatten your data model upstream to be something like the following and leave your template unchanged.
[{position: 1, name: 'Hydrogen', weightName: 5.55, symbol: 'H'},...]

A: I had faced the similar issue, and I solved it as follows.

*

*Update displayedColumns: string[] = ['position', 'name', 'weight.name', 'symbol'];

*Write a method in app.component.ts as follows

findColumnValue = (element:unknown, column:string):string => <string>column.split('.').reduce((acc, cur) => acc[cur], element);

*Update html file as follows

<ng-container [matColumnDef]="column" *ngFor="let column of displayedColumns">
     {{column.split('.')[0]}}
     {{findColumnValue(element, column)}}
</ng-container>

*If you are OK with eval method, you could use it as follows

findColumnValue = (element:unknown, column:string):string => eval(`element.${column}`);

A: You can access nested objects using dot notation in your displayedColumns array
Example:
  displayedColumns: string[] = ['position', 'name', 'weight.name', 'symbol'];

In the table HTML you need to reference the dot notation weight.name in your matColDef
Your HTML:
  <ng-container matColumnDef="weight.name">
     <mat-header-cell *matHeaderCellDef> Weight </mat-header-cell>
     <mat-cell *matCellDef="let row">{{row.weight.name}}</mat-cell>
  </ng-container>


text:
Q: Jackson: Convert JSON to object: ArrayList of objects with arraylist of objects with arraylist of objects I have an android app which makes a call do rest api.
It returns a list of restaurants. Each restaurant has list of categories. Each category can have multiple dishes.
When I deserialize this list, I have nice ArrayList of Restaurants, each Restaurant also has an ArrayList of Categories, but in Category class, ArrayList of Dishes is null.
Does anyone has any idea how to solve this?
JSON response: (it's actually a object of type ServiceResponse)
{
 "requestToken" : 0,
  "responseCode" : 2,
  "objectType" : "com.test.Restaurant",
  "error" : null,
 "data" : [ {
    "id" : 1,
    "name" : "Name",
    "addressCity" : "Warszawa",
    "addressStreet" : "Kopernika",
    "addressStreetNumber" : "4",
    "addressApartmentNumber" : "17",
    "categories" : [ {
      "id" : 1,
      "restaurantId" : 1,
      "name" : "Breakfast",
      "description" : "Description",
      "dishes" : [ {
        "id" : 11,
        "categoryId" : 1,
        "name" : "Dish 1",
        "description" : "Descr",
        "price" : 8.99,
        "photoId" : 51
      }, {
        "id" : 21,
        "categoryId" : 1,
        "name" : "Dish 2",
        "description" : "Descr",
        "price" : 6.99,
        "photoId" : 41
      }, {
        "id" : 31,
        "categoryId" : 1,
        "name" : "Dish 3",
        "description" : "Descr",
        "price" : 14.99,
        "photoId" : 61
      } ]
    }, {
      "id" : 2,
      "restaurantId" : 1,
      "name" : "Obiady",
      "description" : "Opis kategorii",
      "dishes" : [ {
        "id" : 41,
        "categoryId" : 2,
        "name" : "Danie 4",
        "description" : "Descr",
        "price" : 6.99,
        "photoId" : 0
      }, {
        "id" : 61,
        "categoryId" : 2,
        "name" : "Danie 5",
        "description" : "Descr",
        "price" : 8.0,
        "photoId" : 0
      }, {
        "id" : 101,
        "categoryId" : 2,
        "name" : "Nowy obiad",
        "description" : "",
        "price" : 111.0,
        "photoId" : 0
      } ]
    }, {
      "id" : 3,
      "restaurantId" : 1,
      "name" : "Pasta",
      "description" : "Opis kategorii",
      "dishes" : [ ]
    }, {
      "id" : 4,
      "restaurantId" : 1,
      "name" : "Przystawki",
      "description" : "Opis kategorii",
     "dishes" : [ ]
    }, {
      "id" : 11,
      "restaurantId" : 1,
      "name" : "Some category",
      "description" : "test",
      "dishes" : [ ]
    }, {
      "id" : 51,
      "restaurantId" : 1,
      "name" : "Sushi",
      "description" : "",
      "dishes" : [ ]
    } ]
  }]
  }

Parsing result with Jackson:
ServiceResponse response = getServiceOutput(params, httpMethod);

if(response.getData() != null && response.getData().size() > 0) {
    try {
        // convert data array from object to class defined in objectType (in JSON)
        ObjectMapper mapper = new ObjectMapper();
        Class clazz = Class.forName( response.getObjectType() );
        ArrayList list = (mapper.convertValue(response.getData(),
            TypeFactory.defaultInstance().constructCollectionType(
                    ArrayList.class, clazz)));

        broadcastIntent.putExtra("result", list);
        broadcastIntent.putExtra("response_code", ServiceResponse.OK);
    } catch (Exception e) {
        broadcastIntent.putExtra("response_code", ServiceResponse.ERROR);
        e.printStackTrace();
    }
}

A: This works for me. The reason I'm declaring the classes (Response, Restaurant etc) as static is because Jackson cannot deserialize non-static inner classes.
 public class Test {

static String jsonString = "{ \"requestToken\":0, \"responseCode\":2, \"objectType\":\"com.test.Restaurant\", \"error\":null, \"data\":[ { \"id\":1, \"name\":\"Name\", \"addressCity\":\"Warszawa\", \"addressStreet\":\"Kopernika\", \"addressStreetNumber\":\"4\", \"addressApartmentNumber\":\"17\", \"categories\":[ { \"id\":1, \"restaurantId\":1, \"name\":\"Breakfast\", \"description\":\"Description\", \"dishes\":[ { \"id\":11, \"categoryId\":1, \"name\":\"Dish 1\", \"description\":\"Descr\", \"price\":8.99, \"photoId\":51 }, { \"id\":21, \"categoryId\":1, \"name\":\"Dish 2\", \"description\":\"Descr\", \"price\":6.99, \"photoId\":41 }, { \"id\":31, \"categoryId\":1, \"name\":\"Dish 3\", \"description\":\"Descr\", \"price\":14.99, \"photoId\":61 } ] }, { \"id\":2, \"restaurantId\":1, \"name\":\"Obiady\", \"description\":\"Opis kategorii\", \"dishes\":[ { \"id\":41, \"categoryId\":2, \"name\":\"Danie 4\", \"description\":\"Descr\", \"price\":6.99, \"photoId\":0 }, { \"id\":61, \"categoryId\":2, \"name\":\"Danie 5\", \"description\":\"Descr\", \"price\":8.0, \"photoId\":0 }, { \"id\":101, \"categoryId\":2, \"name\":\"Nowy obiad\", \"description\":\"\", \"price\":111.0, \"photoId\":0 } ] }, { \"id\":3, \"restaurantId\":1, \"name\":\"Pasta\", \"description\":\"Opis kategorii\", \"dishes\":[ ] }, { \"id\":4, \"restaurantId\":1, \"name\":\"Przystawki\", \"description\":\"Opis kategorii\", \"dishes\":[ ] }, { \"id\":11, \"restaurantId\":1, \"name\":\"Some category\", \"description\":\"test\", \"dishes\":[ ] }, { \"id\":51, \"restaurantId\":1, \"name\":\"Sushi\", \"description\":\"\", \"dishes\":[ ] } ] } ] }";

public static void main(String[] args) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    Response res = mapper.readValue(jsonString, Response.class);
}

public static class Response {
    public String requestToken;
    public List<Restaurant> data;

    public Response(){}

    public String getRequestToken() {
        return requestToken;
    }

    public void setRequestToken(String requestToken) {
        this.requestToken = requestToken;
    }

    public List<Restaurant> getData() {
        return data;
    }

    public void setData(List<Restaurant> data) {
        this.data = data;
    }
}

public static class Restaurant {
    public List<Category> categories;

    public List<Category> getCat() {
        return categories;
    }

    public void setCat(List<Category> categories) {
        this.categories = categories;
    }

    public Restaurant(){}
}

public static class Category {
    public List<Dish> dishes;

    public Category(){}

    public List<Dish> getDishes() {
        return dishes;
    }

    public void setDishes(List<Dish> dishes) {
        this.dishes = dishes;
    }
}

public static class Dish {

    public String id, categoryId, name, description;
    public float price;
    public int photoId;

    public Dish(){}

}
}


text:
Q: Install from source in Docker I need to install graph-tool from source, so I add in my Dockerfile this:
FROM ubuntu:18.04

RUN git clone https://git.skewed.de/count0/graph-tool.git
RUN cd graph-tool && ./configure && make && make install

as it written here.
When I try to build my Docker-compose I catch a error:
/bin/sh: 1: ./configure: not found

What am I doing wrong? Thanks!
ADDED Full Dockerfile:
FROM ubuntu:16.04

ENV LANG C.UTF-8
ENV PYTHONUNBUFFERED 1
ENV C_FORCE_ROOT true

# Install dependencies
RUN apt-get update \
    && apt-get install -y git \
    && apt-get install -y python3-pip python3-dev \
    && apt-get install -y binutils libproj-dev gdal-bin \
    && cd /usr/local/bin \
    && ln -s /usr/bin/python3 python \
    && pip3 install --upgrade pip

RUN git clone https://git.skewed.de/count0/graph-tool.git

RUN apt-get update && apt-get install -y gcc
RUN apt-get update && apt-get install -y libboost-all-dev

RUN apt update && apt install -y --no-install-recommends \
    make \
    build-essential \
    g++

RUN cd graph-tool && ./configure && make && make install

# Project specific setups
RUN mkdir /code
WORKDIR /code
ADD . /code
RUN pip3 install -r requirements.txt

A: You need to run autogen.sh first, it will generate configure file
P.S. Make sure you install libtool
apt-get install libtool

A: You have to install the prerequisites first.
RUN apt update && apt install -y --no-install-recommends \
    make \
    build-essential \
    g++ \
    ....

Don't forget to clean up and remove temp/unnecessary files!


text:
Q: Jenkins: run the job when the project was released( by performing a maven release) I have defined a job, and I use Jenkins. I'm pretty new in it. Is it possible to set the job to run each time when the project was released?
Thank you.

A: There are a couple of ways of doing a Release vs non-release (daily, commit) build.

*

*Check out the functionality of the Release Plugin

*Use two different jobs.  One for "normal" builds, one for Release builds.

For the projects we are running here, we actually use #2 along with the Promoted Builds Plugin.  Normal builds may be promoted to different states (e.g. Integration, Verification).  During the promotion, the built version of the code is tagged indicating the promotion. When it comes time to make a release build, only those source versions that have been promoted (and tagged) may be built into a Release.

A: Since I have svn tags I have decided to use svn tags (where all released versions are stored), so I can run my job for a released version.


text:
Q: What is the sql query in SQLite, to retrieve the records from the database table for the last week, for the last month, and for the last year I created a data base table using SQLite in my project, I want to retrieve records from the database for  the last week,  for the last month,  for the last year, when user click on the specified Buttons.                                                                                But I don't know how to retrieve the records. Is there any function exist to get these records accordingly ?

A: You'll need to construct a "where" clause like so:
ContentResolver cr = getContentResolver();
        Cursor groupCur = cr.query(
                Groups.CONTENT_URI, // what table/content
                new String [] {Groups._ID, Groups.NAME},    // what columns
                "Groups.NAME NOT LIKE + 'System Group:%'", // where clause(s)
                null, // ???
                Groups.NAME + " ASC" // sort order
        );

I spaced this out so it's easier to explain, but this is what you typically see as:
Cursor groupCur = cr.query(Groups.CONTENT_URI, null, null, null, null);

A: I found the query
SELECT * FROM DATABASE_TABLE
    WHERE strftime('%Y-%m-%d',DATE) >= date('now','-6 days') AND
    strftime('%Y-%m-%d',DATE)<=date('now') order by DATE


text:
Q: $me = $facebook->api('/me') does not return any value I am developing a facebook iframe application with the New Graph API php sdk. I am using the basic code to just display my name. But it does not return any value. Some one please help me with this.
<?php

  include_once 'facebook.php';
  include_once 'config.php';

  $facebook = new Facebook(array('appId'  => FACEBOOK_APP_ID,
                                 'secret' => FACEBOOK_SECRET_KEY,
                                 'cookie' => true,));

  $session = $facebook->getSession();
  $me = null;

  if ($session) {
    try {
        $uid = $facebook->getUser();
        echo "Hello " . $uid . "
";   // This is displayed with my User Id

        $me = $facebook->api('/me');
       echo "Hello " . $me['name'] . "
";  // This is not displayed.

    } catch (FacebookApiException $e) {
        error_log($e);
    }
  }

if ($me) {
    $logoutUrl = $facebook->getLogoutUrl();
} else {
    $loginUrl = $facebook->getLoginUrl();
}

Why is my name not displayed?
Edit 1
If I use the example code that comes with the New Graph API facebook sdk zip folder, I get the following error:
 Fatal error: Uncaught CurlException: 6:
 Could not resolve host: graph.facebook.com;
 No data record of requested type thrown in
 C:\xampplite\htdocs\newtest\facebook.php on line 513

where line no 513 is:
 $e = new FacebookApiException(array(
    'error_code' => curl_errno($ch),
    'error'      => array(
      'message' => curl_error($ch),
      'type'    => 'CurlException',
    ),
  ));

Please explain me what is wrong. I searched for the error explanation in google,but i couldn't get much information. What is the error I have made?

A: try writing the following code in the try block where you have called the this($me = $facebook->api('/me');) api.
Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYPEER] = false;
  Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYHOST] = 2;

A: let us tack a look at the error by the following script:
try {
    $uid = $facebook->getUser();
    $fbme = $facebook->api('/me');
} catch (FacebookApiException $e) {
    print_r($e);
}

Error:
[error] => Array
(
    [message] => Failed to connect to 66.220.147.27: Permission denied
    [type] => CurlException
)

outgoing connections are filtered by the server firewall. Refer to your hosting support for additional information how to allow the connection to external host.
Note that you can also disable the firewall, and everything will work well.


text:
Q: System.InvalidOperationException within Process checking Sub I have a Sub checking if a process name is listed in a listbox and if it exists it does some things, so i am checking the list of open processes looking for ones that have a window title.
Dim ProcCheck() As Process
    Dim MyProcCheck As Process

    ProcCheck = Process.GetProcesses

    For ProcIndex = 0 To ProcCheck.Length - 1

        MyProcCheck = ProcCheck(ProcIndex)

        If MyProcCheck.MainWindowTitle = "" Then Continue For

If I stop the code and read MyProcCheck variable at any point there is some errors for every process contained in this variable. Below is a picture of some of the errors that are shown.

there are some other errors higher up in the list.
ExitCode = 'MyProcCheck.ExitCode' threw an exception of type 'System.InvalidOperationException'
ExitTime = 'MyProcCheck.ExitTime' threw an exception of type 'System.InvalidOperationException'

These errors are not causing any breaking of the code, they only show inside the dropdown that is in the picture. I tried googling the errors but all i can find is posts pertaining to starting processes. I am only reading the processes that are open already. Should I be worried about this ?
thanks for any help you can give
Edit:
The Answer this question is linked with doesn't answer this question, it only explains a little more what the error being received is about. It is in no way a duplicate of the question I asked.


text:
Q: Why does a horizontal scroll-bar appear when adding small div below HTML Canvas? I have a simple HTML canvas that covers the entire page which displays fine by itself.

const canvas = document.getElementById("mainCanvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
window.addEventListener("resize",
  function() {
    canvas.width = innerWidth;
    canvas.height = innerHeight;
  }
);
body {
  background-color: red;
  margin: 0;
  padding: 0;
}

#mainCanvas {
  display: block;
  background-color: blue;
}
<canvas id = "mainCanvas"></canvas>

However, when I try to add a div element below it, immediately a horizontal scroll bar appears even though all of the elements are less than the total width (and therefore there shouldn't be any horizontal overflow). For example:

const canvas = document.getElementById("mainCanvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
window.addEventListener("resize",
  function() {
    canvas.width = innerWidth;
    canvas.height = innerHeight;
  }
);
body {
  background-color: red;
  margin: 0;
  padding: 0;
}

#mainCanvas {
  display: block;
  background-color: blue;
}

#info {
  width: 50px;
  height: 50px;
  background-color: green;
}
<canvas id = "mainCanvas"></canvas>

I know I can fix the problem of the horizontal scrollbar showing up by using overflow-x: hidden but I want to understand why it appears in the first place.

A: This is unrelated to <canvas> and the behavior is the same with any other block element such as a
.
If you set the lone element in the 's dimensions to innerWidth/innerHeight and the parent  has no padding or margin, then you've used up exactly all of the space on the page and no scrollbars are necessary.
If you add a
 below your full-page element, a vertical scrollbar becomes necessary to allow the user to move the viewport down to see it. But this new vertical scrollbar now takes up some horizontal space that is ignored by innerWidth, as the docs state:

innerWidth returns the interior width of the window in pixels. This includes the width of the vertical scroll bar, if one is present.

The original element set to exactly innerWidth pixels now overflows the screen horizontally by the width of the vertical scrollbar. Therefore, a horizontal scrollbar becomes necessary.
An option you can try is document.documentElement.clientWidth. As the docs state:

clientWidth [...] includes padding but excludes borders, margins, and vertical scrollbars (if present).

(you might need to click 'full page' after running the snippet to see the difference):

const canvas = document.getElementById("main-canvas");
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
window.addEventListener("resize", // TODO debounce
  function () {
    canvas.width = document.documentElement.clientWidth;
    canvas.height = document.documentElement.clientHeight;
  }
);
body {
  background-color: red;
  margin: 0;
  padding: 0;
}

#main-canvas {
  display: block;
  background-color: blue;
}

#info {
  width: 50px;
  height: 50px;
  background-color: green;
}
<canvas id="main-canvas"></canvas>

See also How to get the browser viewport dimensions?


text:
Q: cp: ./public.generic-pc.icns: Operation not permitted On my MacOS Mojave:
I'm trying to change the icon of an SMB Windows File server from the old CRT-BSOD icon to something newer like e.g. the NAS icons.
I'm fine with just using the NAS icon (the com.apple.xserve.icns) but I'm not allowed to replace the public.generic-pc.icns file in /System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/
I get an "Operation not permitted" error, even if I sudo cp ....


text:
Q: Getting lookup which contains fields from multiple tables I have 3 tables Ram , Sam , Dun
Ram Table has fields
RAMItemCode  RamItemDescription RamItemStatus(Active/Inactive)   Recid
R1             Rest1              Active                         RRec1
R2             Rest2              Inactive                       RRec2
R3             Rest3              Active                         RRec3
Sam Table has fields
SamItem       SamStatus        Recid
s1            Active           srec1
s2            Active           srec2
S3            Inactive         srec3
Dun Table has 3 fields
Sam          Ram          Status
Srec1        RRec1        Active    -(As both s1 and r1 are active this is active)
Srec1        RRec2        Inactive   (As s1 is active and r2 is inactive this is inactiv)
Srec2        RRec1        Active      (As both S2, R1 are active)
Srec2        RRec3        Active      (As both S2 and R3 are active)
If both are active in Sam field and Ram field in Table Dun then only status will be active in Dun table status field. Else it will always be inactive if atleeast one of Sam or Ram is inactive .  -- Rule
If i change status either in Ram table or SAm table the corresponding fields status will also be changed as per Rule in Dun Table.
Now i have two fields
Sam -
Ram -
in a form which is a unbound control.
I am getting lookup for Sam field from SAM Table. Now i selected Sam field from lookup of Sam master.
Now in the second field ram i need to get lookup of RamItemCode which is related to the sam selected in first field and status from DUN Table.
Dun Table has 3 fields
Sam          Ram          Status
Srec1        RRec1        Active      -(As both s1 and r1 are active this is active)
Srec1        RRec2        Inactive    (As s1 is active and r2 is inactive this is inactiv)
Srec2        RRec1        Active      (As both S2, R1 are active)
Srec2        RRec3        Active      (As both S2 and R3 are active)
For Example :  If i select S1 in first field on form. The Ram lookup should contain R1,R2 as shown in above table Srec1 has RRec1,RRec2 related with status as Active and Inactive. So i need to show in lookup RAMItemCOde for RRec1,RRec2 along with status(Status from DUn table)  Like as shown below.
Sam: S1
Ram:   R1  Active
   R2  Inactive.

Thats my scenario. Can you please help me. Thanks in advance. Hope this is clear enough. Let me know if any more info needed. Thanks.

A: Let me first rephrase your question to make sure I understood: Tables Ram and Sam have a n:m relationship defined by table Dun. In your first lookup you select a value from table Sam. Your second lookup should now show all possible values from table Ram as well as the Status field from table Dun. So basically you want to do a lookup on one table (Dun) but the return value should come from another table (Ram).
You can achieve this with the following code in the lookup method of the form control of your second lookup field. But first you need to download and Import an xpo by Ivan Kashperuk that will give you the new class SysMultiTableLookup. You also should set the property AutoDeclaration of your first lookup control (named SamLookup in my code) to "Yes". Now you can now write the following code:
public void lookup()
{
    Sam                  sam;
    Query                query = new Query();
    QueryBuildDataSource qbds;
    QueryBuildRange      queryBuildRange;
    SysTableLookup       sysTableLookup;
    SysMultiTableLookup  sysMultiTableLookup;

    // retrieve the RecId of the Ram record selected in the first lookup
    select firstOnly RecId from sam where sam.ItemCode == samLookup.valueStr();

    // build the query on the relation table Dun joined to the Sam table and filtered
    // to the records available for the selected Ram record
    qbds = query.addDataSource(tableNum(Dun));
    qbds.addRange(fieldNum(Dun, Sam)).value(queryValue(sam.RecId));
    qbds = qbds.addDataSource(tableNum(Ram));
    qbds.relations(true);

    // Build the lookup
    sysMultiTableLookup = SysMultiTableLookup::newParameters(this, query);
    sysMultiTableLookup.addLookupfield(fieldNum(Dun, Status));
    sysMultiTableLookup.addLookupField(fieldNum(Ram, ItemCode), 2, true); // 2 for second data source of query, true to use this field as return value of lookup

    sysMultiTableLookup.performFormLookup();
}

Example xpo


text:
Q: Как в Netbeans ставить комментарий вида /*… */ горячие клавиши? Либо я туплю, либо еще что, но не могу разобраться как в Netbeans поставить комментарий типа /*… */ . Вроде и и-нет пролистал, ничего не нашел и пользователи особо о такой проблеме не пишут, хотя как мне кажется важный момент.

A: NetBeans может комментировать несколько строк, только с помощью //, не с /*...*/, используйте комбинацию Ctrl+Shift+C или комбинацию Ctrl+/. Убирает комментарии на такую же комбинацию.
Вот список всех горячих клавиш, и не только - тынц!.


text:
Q: php json_encode bug patch i have data in text file which i load to array rows wise , but recently i have noticed that when "µ" come in data then json_encode retrun blank response ,and when i remove "µ" from data then json_encode function work
i have php version 5.5.3
$dat = array("0"=>"hello","1"=>"world");
echo json_encode($dat);   // work

$data = array("0"=>"hello","1"=>"180.00 10µH");
echo json_encode($data);  // blank response ..

i searched for json_enocde function on github php page , but its all in C ,
so any idea how to patch this function

A: Use the following code:
function utf8_converter($array) {
    array_walk_recursive($array, function(&$item, $key) {
        if (!mb_detect_encoding($item, 'utf-8', true)) {
            $item = utf8_encode($item);
        }
    });

    return $array;
}

$data = array("0"=>"hello","1"=>"180.00 10µH");
$data = utf8_converter($data);
echo json_encode($data, JSON_PARTIAL_OUTPUT_ON_ERROR);

A: Try this:
$dat = array("0"=>"hello","1"=>"world");
echo json_encode($dat);   // work

$data = array("0"=>"hello","1"=>"180.00 10µH");
echo json_encode($data, JSON_UNESCAPED_UNICODE);

Example: https://ideone.com/cYDf8Y