text:
Q: Is it possible to force a web app in Php to work with a desktop app in Java? A simple socktet app.
There is a server, and multiple clients from all around the world can connect to this server using its IP address and a port number. And right after that, you can send a messenge, and everyone who is connected will be able to see it.

A: You are almost there dude, you willing to have chat application which can be operated from android,IOS, desktop application and web browsers as well, so as you said you done with JAVA socket server program which is primarily desktop based at the moment,  as you said you are making use of RAW socket programming which is good upto mobile & desktop applications , but what about web application? yes not possible in that case.
So in order to make it happen for all possible available gadgets today including smart phones, smart watches, using web browsers, and desktop applications as well you have to make use of WebSockets,

WebSocket is a protocol providing full-duplex communication channels
  over a single TCP connection. The WebSocket protocol was standardized
  by the IETF as RFC 6455 in 2011, and the WebSocket API in Web IDL is
  being standardized by the W3C.

You can understand a bit about WebSockets from here:
websocket.org
socket.io

So here comes a concept of WebSockets, using which you can achieve
  almost what you are supposed to do. So you can do few things out of
  following to achieve this:

*

*You can modify your existing JAVA program to handle WebSocket connection instead of dealing with RAW sockets, which you are doing currently.

*Another possibility you can write your server WS(WebSocket) program in Python or node.JS, which is far easy to develop, and host on any free PaSS cloud services like heroku,openshift or even AWS.

So, in this case once you created/modified your existing server
  program to  WS, all you have to do is create client side
  programs in either or all of the following:

*

*IOS app

*Android APP

*Desktop App(In .NET or JAVA or Python)

*Website in PHP or Python(Using JavaScript WS client libraries)

you can create the client side programs in any or all of above platforms, the WS client libraries are almost available for all of the platform's mentioned above.
So, what once you done with Sever side you can host your server side program on openshift, which is free to use PaSS cloud service far better than rest of the PaSS services available today.


text:
Q: Serializer in patch method does not check fields I am trying to partially update a model and overwriting the patch method. It works fine when I send correct data, but my problem is, that when I send incorrect data the serializer stays True and I still get a 200 status code and nothing gets updated. With incorrect data I mean wrong field names. I could basically send any field name and get a 200 status code. So I think the fields are not checked by the serializer...
class BuildingUpdateAPI(UpdateAPIView):
    serializer_class = BuildingSerializer

    def patch(self, request, *args, **kwargs):
        """Patches building."""

        building = buildings.get(name=self.kwargs['name_building'])
        serializer = BuildingSerializer(building, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(status=200, data=serializer.data)
        return JsonResponse(status=400, data="Wrong data provided")

serializer:

class BuildingSerializer(serializers.ModelSerializer):
    """Serializer for Buildings."""

    class Meta:
        model = Building
        fields = (
            "id",
            "name",
            "...",
            .....

Now I am wondering if this is like this by design or if I am doing something wrong in my view. I thought I could overwrite the validate-method in the serializer but my model has quite a lot of fields... So I would have to check every field single field which is not optimal I think. Or is there a way to do this somehow elegantly?
I am patching like this:
result = requests.request("patch", url=endpoint, json=payload, headers=get_headers())

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to complete different layouts from mobile phones to desktops through flex? I am currently working on a RWD flex typesetting requirement and encounter a problem, I don't know how to implement it?
I hope that the mobile device can display one row of four and a total of four rows, but when it comes to the computer device, I want to display three rows, and the number of each row gradually decreases!
But I really don't know how to achieve such a demand, I hope I can get your help, thank you all.
PS: The width of each element on the mobile phone is 80px and the height is also 80px
, but on the computer, the width of each element must be 150px and the height is also 150px

.content {
  display: flex;
  flex-wrap: wrap;
}

.content .item {
  display: inline-block;
  width: 80px;
  height: 80px;
  background-color: purple;
  color: #fff;
  line-height: 80px;
  text-align: center;
  border: 2px solid #fff;
  flex: 0 0 20%;
}

LOGO

LOGO

LOGO

LOGO

LOGO

LOGO

LOGO

LOGO

LOGO

LOGO

LOGO

LOGO

LOGO

LOGO

LOGO

LOGO


text:
Q: Insert multiple data from input Laravel I'm making a quiz system. I have 3 tables:
tests table
id,
title,
total_question,
time,
status,
id_subject

questions table:
id,
content,
optA,
optB,
optC,
optD,
answer,
unit,
id_subject

questions_of_test table:
id,
id_test,
id_question

When I create a test, after I select subject, base on the number of unit of that subject will show a number of textbox to fill a number of question for each unit.
Example, the subject I selected have 3 unit. It will show 3 textboxes and I fill:
Textbox1: 1
Textbox2: 2
Textbox3: 1
Total is 10 question.
How can I insert this 10 question to questions_of_test table.
This is my some code to show texbox from dropdownlist:
$('select').select();
    function get_units() {
        var id = $('#id_subject').val();
        var list = $('#list_unit');
        list.empty();
        var url = "{{ route('test.getunit', ':id') }}";
        url = url.replace(':id', id);
        var success = function (result) {
            if (result.length <= 0) {
                var item = '

<input type="text" disabled value="This subject have no question" class="form-control" style="color: #26c6da;">

';
                list.append(item);
            } else {
                for (i = 0; i < result.length; i++) {
                    var item = '
Enter number of question of unit ' + result[i].unit+ ' (have' + result[i].Total + ' questions) (*)

<input type="number" min="0" max="' + result[i].Total + '" class="unit_input form-control" onchange="set_sum(' + result[i].Total + ')"  name="unit-' + result[i].unit+ '" id="unit[' + result[i].unit+ '][]" required>

';
                    list.append(item);
                }
            }
        };
        $.get(url, success);
    }

I got an array like this:

I want to Insert random(1) where id_subject = select_id and unit = 1, random(2) where id_subject = select_id and unit = 2... How can I get it?
<input type="number" name="unit['+result[i].chuong+'][]"></input>


text:
Q: Initialization loop Golang Hi I'm trying to make my function unit testable. One of the suggestion was to assign the function into a variable and make it globally accessible. I just did that but now I'm experiencing a Initialization loop below is my code
////////////////////////
// main.go
////////////////////////

func DownloadFile(filename string) {
    // Initialized request variable here
    // ... doing initialization
    // End of initialization

    res = ProcessDownload(request)

    if res == 401 {
       return doRetry(filename)
    }

    // some code here
    return downloadFile(filename)
}

func DoRetry(filename string) {
    // Doing some database insert/updating
   return downloadFile(string)
}

And in my other file I assign this function into variable
//////////////////////
// global.go
//////////////////////

var downloadFile = DownloadFile
var doRetry = DoRetry

The reason I did this in the global.go was to make the DoRetry and DownloadFile unit testable. Meaning with this method I can MOCK the function without creating an interface. Since this is just a standalone function and don't need to be within a certain class. All the rest of the variable is ok but when it comes to a function doing a recursive behavior I get the error below
./global.go:22:5: initialization loop:
/go/src/project/global.go:22:5 downloadFile refers to
/go/src/project/process.go:403:99 DownloadFile refers to
/go/src/project/global.go:23:5 doRetry refers to
/go/src/project/process.go:394:89 DoRetry refers to
/go/src/project/global.go:22:5 downloadFile
FAIL    project [build failed]

I know this maybe a duplicate in here but I can't see how the solution in here solve my problem.
Please help me on this. Thanks
I read about mocking a function in this link
Mock functions in Go
https://husobee.github.io/golang/testing/unit-test/2015/06/08/golang-unit-testing.html

A: The solution is to not assign values when you declare your downloadFile and doRetry function variables, but "defer" the initialization to a package init() function, like this:
var downloadFile func(string) //= DownloadFile
var doRetry func(string)      //= DoRetry

func init() {
    downloadFile = DownloadFile
    doRetry = DoRetry
}

This way the variables first will be initialized with nil (zero value for function types) which means they don't depend on the DownloadFile() and DoRetry() functions, and later when the package init() function runs, that will assign the function values to the variables, so no initialization loop will occur.


text:
Q: How to sendKeys() using/from a python dictionary Something like;
element(by.model('formData.name')).sendKeys('David Cameron');
I am trying to find a way to test my admin side when a user signs up. Somewhere I'll have to use expect (to check whether entry was submitted to backend) but I want to use a python dictionary of about 10 names where the protractor test selects a name at random to sendKeys(). How do I establish the link?

A: Dump your Python dictionary into a JSON file via, for example, json.dump(), then you can import the JSON file and set the browser.params in onPrepare():
onPrepare: function () {
    var fs = require('fs');
    var obj = JSON.parse(fs.readFileSync('file', 'utf8'));

    browser.params.names = obj;
},

Then, you can use browser.params.names in your test. To pick up a random value from an array, see this topic: Getting a random value from a JavaScript array.

A: I figured it out by creating javaScript objects straight away in my testing *spec.js file e.g for 3 random people (objects);
Inside my sell-spec.js file;
var random = function(){
    return Math.floor((Math.random() * 3) + 1);
}

var users = [];
var user1 = {
    name : "Jacob",
    tel : "123",
    email: "1@1.com",
    reg: "1234",
    vin : "2345"
};
var user2 = {
    name : "Jacob2",
    tel : "1232",
    email: "1@12.com",
    reg: "12342",
    vin : "23452"
};
var user3 = {
    name : "Jacob3",
    tel : "1233",
    email: "1@13.com",
    reg: "12343",
    vin : "23453"
};

users.push(user1);
users.push(user2);
users.push(user3);

var selectedUserIndex = random();
selectedUser = users[selectedUserIndex]

element(by.model('formData.name')).sendKeys(selectedUser.name);
element(by.model('formData.cell')).sendKeys(selectedUser.tel);

and in my other (admin) spec admin-spec.js file;
expect(element.all(by.binding('name')).first().getText()).toEqual('Name: ' + seller_details.selectedUser.name );
expect(element.all(by.binding('cell')).first().getText()).toEqual('Cell: ' + seller_details.selectedUser.tel);


text:
Q: Посоветуйте date-time picker для реакта Даже на 5й странице гугла ничего нормального не нашёл(
Требования:

*

*Поле типа input по нажатию на который открывается календарь.

*Можно вводить врем/дату как и на прямую в инпут, так и по выбору
даты в календаре.

*В пикере должна быть возможность выбрать и дату и время(можно инпут
с временем отдельно).

*В либе должен быть range picker(для дат, желательно так же
возможность выбора времени).

*Не должно быть PM/AM , либо возможность их отключить.

*Обязательна возможность локализации, если её нет по дефолту.

Примеры: https://ant.design/components/date-picker . Главные минусы антд - одна коллбек функция на выбор и даты и время, стрёмный дизайн выбора времени(3 скролла).
Если вы пользуетесь или пользовались пикером который подходит под условия пожалуйста дайте ссылку на гитхаб или npm.


text:
Q: Am I allowed to modify the subviews of a default iOS control? Are we allowed to modify the subviews of a default iOS control, like the UIDatePicker? My app has a minimalist/flat UI, and the default Date Picker doesn't match that style. The only way I could find to modify it was to iterate through its subviews and hide the ones that add shadows, etc., like so:
UIView *background = (UIView *)[[self pickerViews].subviews objectAtIndex:0];
background.hidden = YES;

Is this allowed or will it get my app rejected? I'm not actually messing with the control or its function whatsoever, just its appearance.

A: While you may not get rejected right away, you may see unexpected behavior in the future when the control's subviews change. It might be a better idea to work up your own custom control, or find ways in the public API to get close to the appearance you want.

A: It isn't really a "private API" — it's entirely documented in the SDK. However, you are relying on behaviour that is not documented (namely that subview 0 is the one you want to hide), so you need to be careful.
Your code has two potential problems:

*

*It will hide the wrong view if the order changes (checking the view class is commonly used to guard against this somewhat)

*It will crash if the picker has no subviews (this seems unlikely to happen; it's much more of an issue when you access views at e.g. index 6).

There are also two additional things you need to do:

*

*Keep a list of anything you've done that are liable to break in future OS releases.

*Check that things still work in iOS betas, and do so early!

A: Its not recommended to change the things which are not exposed through API. In future apple may remove the subviews at that particular indexes. Its better to avoid this kind of approach. Try to look for other options in-terms of UI or implementation.


text:
Q: Launch Logoff Screen Using Terminal On Lubuntu 13.10 How can I open the logoff screen from my terminal instead of clicking the logoff button? This is on Lubuntu 13.10.
Screenshot of the logoff screen:

A: The command is:
lxsession-logout


text:
Q: How much does opening a TCP socket whenever you want to send a request impacting performance? What I am asking is, how much does opening a TCP socket val socket: Socket("198.51.100.1", 9999) always whenever you are going to send an request socket.outputstream().write("Hello World!".toByteArray()) and then closing it socket.close() impact the performance of a program/an app? I am developing an app, which always opens a new socket using coroutines, however, the problem was at the end device, the ports were starting at 53000 (or something like that), so the ports for every socket would fill up very quickly.
I am asking, how would this impact performance? Thanks.

A: TCP is very slow to initialize, due to the anti-congestion algorithm. Your concern should not be the ports (unless you are making a lot of requests and leaking connections), but the initialization time. If you can use keepalive sockets, that is much preferable.


text:
Q: How can I link my private videos on YouTube to be played on my website? How can I link my private videos on YouTube to be played on my website. The point is to bring more viewers to my site by making videos available on my site, yet private on YouTube.

A:
You should set your videos to "unlisted" instead of "private". That
  way the video does not show up on your channel or on any search
  results but anyone with a link to the video can see it and you can
  embed the video on any site.

I didn't try this workaround yet but theoretically it should work, you need to use YouTube API V 3 and follow the below steps:
Set the video's privacy status to unlisted through API.
Embed the video via API in a hidden div.
Use onPlayerStateChange event to check if the video player is currently playing the video, use the API to pause the video at the first second.
If the state changed to "playing" then send an AJAX request to a server side script to revert the the video's privacy status to be private, once you get a confirmation message display the video and use the API to play it.
This should keep the video private even if the user copy & paste the URL in another tab, s/he should get a message that the video is private.
References:
https://developers.google.com/youtube/iframe_api_reference?hl=en
PHP - How to change privacy status of a youtube video through Youtube API v3?


text:
Q: Module not found: Can't resolve 'react/lib/React' I've been trying to run an existing React project that I found on Github. I've had some issues. First, I needed to update React to v 16.2.0 to get React.Fragment working. Now, having done the update, I'm getting this second issue:
./node_modules/react-dom/lib/ReactCompositeComponent.js
Module not found: Can't resolve 'react/lib/React' in '/Users/sahandzarrinkoub/Documents/Programming/DH2642/Sentify/repo/Sentify/node_modules/react-dom/lib'

from the console:
index.js:2178 ./node_modules/react-dom/lib/instantiateReactComponent.js
Module not found: Can't resolve 'react/lib/getNextDebugID' in '/Users/sahandzarrinkoub/Documents/Programming/DH2642/Sentify/repo/Sentify/node_modules/react-dom/lib'
__stack_frame_overlay_proxy_console__   @   index.js:2178
handleErrors    @   webpackHotDevClient.js:178
./node_modules/react-dev-utils/webpackHotDevClient.js.connection.onmessage  @   webpackHotDevClient.js:211
./node_modules/sockjs-client/lib/event/eventtarget.js.EventTarget.dispatchEvent @   eventtarget.js:51
(anonymous) @   main.js:274
./node_modules/sockjs-client/lib/main.js.SockJS._transportMessage   @   main.js:272
./node_modules/sockjs-client/lib/event/emitter.js.EventEmitter.emit @   emitter.js:50
WebSocketTransport.ws.onmessage @   websocket.js:35

*

*What is the reason for this bug?

*How to fix it?

ADDITIONAL INFO:

Here is the project home folder. Here is the package.json file:
{
  "name": "Sentify",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "ajv": "^5.5.2",
    "cors": "^2.8.4",
    "dom": "0.0.3",
    "jquery": "^3.3.1",
    "jsdom": "^11.7.0",
    "mapbox-gl": "^0.44.1",
    "material-ui": "^0.20.0",
    "react": "^16.2.0",
    "react-d3-basic": "^1.6.11",
    "react-d3-core": "^1.3.9",
    "react-d3-shape": "^0.3.25",
    "react-dom": "^15.6.2",
    "react-router-dom": "^4.3.0-rc.2",
    "react-scripts": "1.1.1",
    "react-simple-pie-chart": "^0.5.0",
    "webpack": "^3.11.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "devDependencies": {}
}

I'm creating the node_modules folder by typing npm install and hosting with npm start.
I removed node_modules and ran npm install; npm start again, and the error changed slightly to:
./node_modules/react-dom/lib/ReactMount.js
Module not found: Can't resolve 'react/lib/React' in '/Users/sahandzarrinkoub/Documents/Programming/DH2642/Sentify/repo/Sentify/node_modules/react-dom/lib'

in console:
index.js:2178 ./node_modules/react-dom/lib/instantiateReactComponent.js
Module not found: Can't resolve 'react/lib/getNextDebugID' in '/Users/sahandzarrinkoub/Documents/Programming/DH2642/Sentify/repo/Sentify/node_modules/react-dom/lib'
__stack_frame_overlay_proxy_console__   @   index.js:2178
handleErrors    @   webpackHotDevClient.js:178
./node_modules/react-dev-utils/webpackHotDevClient.js.connection.onmessage  @   webpackHotDevClient.js:211
./node_modules/sockjs-client/lib/event/eventtarget.js.EventTarget.dispatchEvent @   eventtarget.js:51
(anonymous) @   main.js:274
./node_modules/sockjs-client/lib/main.js.SockJS._transportMessage   @   main.js:272
./node_modules/sockjs-client/lib/event/emitter.js.EventEmitter.emit @   emitter.js:50
WebSocketTransport.ws.onmessage @   websocket.js:35

Additional stack trace from console:
ReactDebugTool.js:14 Uncaught Error: Cannot find module "react/lib/ReactComponentTreeHook"
    at webpackMissingModule (ReactDebugTool.js:14)
    at Object../node_modules/react-dom/lib/ReactDebugTool.js (ReactDebugTool.js:14)
    at __webpack_require__ (bootstrap f031d93a2683340d518f:678)
    at fn (bootstrap f031d93a2683340d518f:88)
    at Object../node_modules/react-dom/lib/ReactInstrumentation.js (ReactInstrumentation.js:17)
    at __webpack_require__ (bootstrap f031d93a2683340d518f:678)
    at fn (bootstrap f031d93a2683340d518f:88)
    at Object../node_modules/react-dom/lib/ReactReconciler.js (ReactReconciler.js:12)
    at __webpack_require__ (bootstrap f031d93a2683340d518f:678)
    at fn (bootstrap f031d93a2683340d518f:88)
    at Object../node_modules/react-dom/lib/ReactUpdates.js (ReactUpdates.js:17)
    at __webpack_require__ (bootstrap f031d93a2683340d518f:678)
    at fn (bootstrap f031d93a2683340d518f:88)
    at Object../node_modules/react-dom/lib/ChangeEventPlugin.js (ChangeEventPlugin.js:15)
    at __webpack_require__ (bootstrap f031d93a2683340d518f:678)
    at fn (bootstrap f031d93a2683340d518f:88)
    at Object../node_modules/react-dom/lib/ReactDefaultInjection.js (ReactDefaultInjection.js:13)
    at __webpack_require__ (bootstrap f031d93a2683340d518f:678)
    at fn (bootstrap f031d93a2683340d518f:88)
    at Object../node_modules/react-dom/lib/ReactDOM.js (ReactDOM.js:14)
    at __webpack_require__ (bootstrap f031d93a2683340d518f:678)
    at fn (bootstrap f031d93a2683340d518f:88)
    at Object../node_modules/react-dom/index.js (index.js:3)
    at __webpack_require__ (bootstrap f031d93a2683340d518f:678)
    at fn (bootstrap f031d93a2683340d518f:88)
    at Object../src/index.js (discover.js:19)
    at __webpack_require__ (bootstrap f031d93a2683340d518f:678)
    at fn (bootstrap f031d93a2683340d518f:88)
    at Object.0 (welcome.js:22)
    at __webpack_require__ (bootstrap f031d93a2683340d518f:678)
    at ./node_modules/ansi-regex/index.js.module.exports (bootstrap f031d93a2683340d518f:724)
    at bootstrap f031d93a2683340d518f:724

A: Your case it is clearly react and react-dom packages incompatibility.
Make sure that your react and react-dom packages have the same version to avoid incompatibility.
package.json now:
...

"react": "^16.2.0",
"react-dom": "^15.6.2",

...

package.json with compatible react-dom and react packages:
...

"react": "^16.2.0",
"react-dom": "^16.2.0",

...

Since react-v0.14-beta-1 react and react-dom are separate libraries and you are supposed to use the same version.

For now, please use the same version of react and react-dom in your
  apps to avoid versioning problems — but we plan to remove this
  requirement later. (This release includes the old methods in the react
  package with a deprecation warning, but they'll be removed completely
  in 0.15.).

A: This can also happen if you do not specify that .js is a resolvable extension in your Webpack configuration.
When Webpack looks for ./lib/React, it won't look for the ./lib/React.js file if, for example, you only specify .ts as a resolvable extension.
Source

A: This sometimes happens when you update yours react version but not react-dom version.
So, always make sure react and react-dom version should be the same in package.json

A: In one of my projects, I was using lerna for mono-repo and had alias entries for react, react-dom. I removed the aliased and it worked out for me.


text:
Q: Visual studio SQL default value not showing on windows form when adding new record I have created a SQL table in Visual studio and set a default value on a field.

The table is connected to my C# project (in the same solution) and pulls through fine, however the default values are not appearing when a new row is created via a windows form.

Info from comment questions:

*

*It doesn't appear on the form when I click the + for a new row.

*When a row is added from the database the defaults are there.

*Added a new row via the form, left the fields with default values blank, saved, re opened and no default values.

A: Based on this W3Schools Tutorials

The default value will be added to all new records IF no other value is specified.

So the Default value will not show until you save the row to the database, you can add it programatically, but the Default value constraint is used to assign a value if there is no values provided in this column
You can save these default values in the application Settings and use it when new row is added
textBox1.Text = Properties.Settings.Default.TextBoxDefaultValue;

If you are facing an issue when defining default value in Visual Studio try adding a Default Constraint using SQL query:
ALTER TABLE XXX
ADD CONSTRAINT def_Retired
DEFAULT 'N' FOR Retired;

UPDATE 1
On the form designer, click on the BindingNavigator, In the Properties window  set the AddNewItem property to (none)
Try adding the following code to the bindingNavigatorAddNewItem_Click event
private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e) {

 vehiclesBindingSource.AddNew();
 Textbox1.Text = Properties.Settings.Default.Text1default;

};

A:
It doesn't appear on the form when I click the + for a new row.

The DataGridView does not know anything about default values in the database table. Accordingly, you must specify the default values in the DataGridView.
Or if you are using data binding, you can specify default values in the DataTable.

When a row is added from the database the defaults are there.

It's right, because in the database they are set.

Added a new row via the form, left the fields with default values blank, saved, re opened and no default values.

If you insert data into the database in the following way:
insert into SomeTable ('Retired') values ('');

then no default value will be used. With high probability I can assume that at the moment you passes empty values from DataGridView, if they are not set. This is wrong!
If you insert data into the database in the following way:
insert into SomeTable ('Last Mileage') values (0);

then the default value for Retired column will be used. It should be so.
Therefore, you must correctly design the Insert statement, completely omitting those columns for which should be used the default value in the database itself.

Summing up. You either have to fill the default values in the DataGridView/DataTable or dynamically construct the Insert statement, completely omitting the not specified values.

A: You are assigning default values in forms that are dynamically generated.  You may need to evaluate whether the components of your client side/server side scripting were also made to accommodate this dynamic behavior in parallel.

A: Default Constraint Works only if you are not specifying the Column in the Insert List.
Suppose I have a Table Like This
CREATE TABLE MyInfo
(
    Id INT IDENTITY(1,1),
    Nm VARCHAR(50),
    MyDate DATE DEFAULT(GETDATE())
)

I'm specifying the Values Like this
INSERT INTO MyInfo
(
    Nm,
    MyDate
)
SELECT
    Nm = 'A',
    MyDate = '02/23/93'
UNION
SELECT
    Nm = 'B',
    MyDate = NULL

And The Result will be Like this

Now I insert a row without specifying MyDate Column
INSERT INTO MyInfo
(
    Nm
)
VALUES('C')

And the MyDate was populated bu Default values

Default Constraint is meant to assign the value if the column is not specified in the insert list. If what you need is to set a Default value if The Inserted value IS NULL or empty, Try using triggers


text:
Q: Getting weird output when trying to print StringBuilder type: "com.jeanlucthumm.poem.Word@7852e922" My program aims to create a random poem by repeatedly printing a randomly generated line.
I have a class called Line which has a field line that it operates on:
private StringBuilder line = new StringBuilder();

The constructor looks like this:
public Line(int length, String pathOfWordList) throws IOException {
    this.length = length;
    populateLine(length, pathOfWordList);
}

The word list has three types of words : nouns verbs and adjectives, each with a probability of being selected.
populateLine selects and prepares a word to add to the StringBuilder line. Words are objects of the class Word and have two fields:
private Type wordType;
private String word;

Where Type is an enum that has the three word types.
Populate line then adds the word by calling a method that calls a method.
The first method has this signature:
// currentWord is the word that we have to insert after.
// wordList is the word bank we draw from.
// line is the line we are working with.
// The last two doubles are the probabilities of the three types of words.
// The third one can be inferred
private void getNextWord(Word currentWord, WordList wordList,
        StringBuilder line, double nounProb, double verbProb)

That method has a bunch of loops that call this method:
// Adds a word to the line and updates its type
// Used by getNextWord
private void loopHelper(Word currentWord, Type type, WordList wordList,
        StringBuilder line) {
    currentWord.setType(type);
    currentWord.setWord(wordList.getWord(type));
    line.append(" " + currentWord);
}

Finally for testing purposes I have made a method that prints out the line:
public void printPoemLine() {
    System.out.println(this.line.toString());
}

But when I instantiate and call that method i get this weird output as the line:
com.jeanlucthumm.poem.Word@7852e922 com.jeanlucthumm.poem.Word@7852e922 com.jeanlucthumm.poem.Word@7852e922 com.jeanlucthumm.poem.Word@7852e922 com.jeanlucthumm.poem.Word@7852e922 com.jeanlucthumm.poem.Word@7852e922

Can someone tell me what that is? I have only found one other article on the internet that had this type of output and it was dealing with Type Erasure, but I am not sure that applies here.

A: By doing:
line.append(" " + currentWord);

you're implicitly calling currentWord.toString() which returns, by default, a string that looks like: com.jeanlucthumm.poem.Word@7852e922
which is <the name of the class>@<hash-code of the object>


text:
Q: jquery $.function() How can I write a plugin/function and then be able to call it like this(no selector required)?
$.function()

now I'm writing my plugins something like this:
(function($){
     $.fn.extend({
          //function name
          myFunction : function(){
           //...........
          }
     });
})(jQuery);

A: Simply like this:
(function($){
     $.myFunction = function(){
           //...........
          }
})(jQuery);

Or just:
jQuery.myFunction = function() { ... };

A: While the "extend" jquery function is the correct way to extend the library, it has two forms.
$.fn.extend which is what you are using in your example is used to add additional functions to actual DOM objects. So for example your "myFunction" function could be used like this if you wanted to take an action on the "document" object in the dom.
    $(document).myFunction()
To extend the static namespace of jQuery, you need to use the $.extend function instead (note the lack of fn)
(function($){
 $.extend({
      //function name
      myFunction : function(){
       //...........
      }
 });
})(jQuery);

should be what you are looking for.


text:
Q: Does using macros instead of functions make the binary bigger? Will using macros result in having more machine instructions (and hence, the binary size) than using functions? I am asking because one of my macros that I use a lot became quite large so I started worrying. I have an impression that macros are copy-pasted as many times as I use them. Is that true?
I could test that myself, but it's a bit troublesome, also I wanted to hear what informed people would say. I am an absolute layman when it comes to assembly language, machine instructions and the like, so sorry if I wrote something stupid.

A: Probably yes, using macros instead of functions may make the binary bigger. But it depends on how your specific case compiles.
Macros are expanded before the compilation proceeds, so the result is like if you copied the code into every function where the macro is used. It is unlikely that the compiler can extract those pieces of code to some common place.
Functions usually exist only in one place and calling them jumps into that place. However, functions may get expanded (inlined) the same way as macros. But that happens only if the compiler decides that it is beneficial, or if you annotate the function with #[inline(always)].
In general if you can achieve what you need with both function and macro, use function. Macros are useful for special cases that can not be achieved by functions. (Like creating custom syntax, or getting the line number of the call site...)


text:
Q: How can I pass host IP address to Docker Compose file? I am building an application using docker-compose (file 1) and I was wondering how I could communicate the host IP address to the docker-compose file. The application is composed of a db, a frontend and a backend. The aim of it is that I want to access my application from other computers on the local network. It works fine for the front but when I want to communicate with the backend, it does not work anymore. I suspect it's due to the fact that the front is trying to send data to localhost (which is not the correct one for another computer on the local network). Thus, I would like to communicate to the front application the IP address of the host directly in the docker-compose file, so it can communicate with the backend ! Any idea ?
File 1
    version: "3.7"

    services:
      db:
        build:
          context: ./database
        command: --default-authentication-plugin=mysql_native_password  --sql_mode=""
        restart: always
        cap_add:
          - SYS_NICE  # CAP_SYS_NICE
        volumes:
          - db_data:/var/lib/mysql
        ports:
          - ${MYSQL_PORT}:${MYSQL_PORT}
        environment:
          MYSQL_DATABASE: ${MYSQL_DATABASE}
          MYSQL_PASSWORD: ${MYSQL_PASSWORD}
          MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
          MYSQL_TCP_PORT: ${MYSQL_PORT}
        env_file: ./.env

      back:
        depends_on:
          - db
        build:
          context: ./backend
          target: development
        volumes:
          - ./backend:/app
          - /app/node_modules
        restart: "no"
        ports:
          - ${BACKEND_PORT}:${BACKEND_PORT}
        env_file: ./.env

      front:
        depends_on:
          - back
          - db
        build:
          context: ./frontend
          target: development
        stdin_open: true
        volumes:
          - ./frontend:/app
          - /app/node_modules
        restart: "no"
        ports:
          - ${FRONTEND_PORT}:${FRONTEND_PORT}
        env_file: ./.env

    volumes:
      db_data: {}

Here is the api url I am using on the frontend env to communicate with the backend, which I would to be replaced with the host IP dynamically.
File 2
const dev = {
    ...env,
    apiUrl: "http://localhost:3000/api",
};

Thank you so much for you help!
Best

A: Environment variables are an easy way to pass small bits of configuration like this in.
For this particular case I'd probably configure a URL and not the host's IP address.  You could very reasonably want to deploy this application behind a load balancer; that load balancer might do TLS termination, so you can advertise an https: URL; your local IP address might not be directly reachable from your clients; you'd prefer to advertise a DNS name than an IP address if you have one.
In the Node code you can find environment variables in process.env:
const dev = {
  ...env,
  apiUrl: process.env.API_URL || 'http://localhost:3000/api'
};

Then in your docker-compose.yml you can directly set that URL:
services:
  front:
    environment:
      API_URL: http://10.20.30.40/api
      # API_URL: https://example.com/myapp/api

A: What you want is called shell command substitution.
Something like: MYVAR=$(ip route get 1 | awk '{print $NF;exit}')
Unfortunately, command substitution is NOT supported in compose.
Compose supports only "static" shell variables aka shell variable expansion.
Your best bet would be to declare mandatory variable with an appropriate error message.
# requires for the var to be pre-declared in shell
environment:
  API_URL: ${API_URL:?"Variable API_URL must present in shell."}

# alternatively you could provide some default value
environment:
  API_URL: ${API_URL:-192.0.2.2}

Another solution may be to play with envsubst to edit your compose file in-place.
Check this answer for examples.

Also note that there is no such thing as "host's ip address" :)
It's kinda conventional and a pretty vague term.

"Primary IP" is an alias for "whatever your system uses when it
originates traffic to the default route". In the absence of source
phrases on that route, that's the first address of the interface used
(more or less).

Thus, you need to be careful when writing your command to define "host's IP".
In simple network configurations this one is likely to work more or less fine.
ip route get 1 | awk '{print $NF;exit}'
But better check this discussion and make sure your eventual command returns what you expect.

A: By adding HOST_IP=http://host.docker.internal:PORT in environment variable of particular services like this
environment:
  - HOST_IP=http://host.docker.internal:4001/

You can access the host ip inside the docker by accessing the environment variable in node js code like
var host_url=process.env.HOST_IP

NOTE: As you can access host ip only you need to add port manually at the end of url and it only works for the development server NOT for production.

A: You should add an environment variable to your frontend configuration which specifies the URL to the api endpoint and use the hostname of the backend container in the URL. The documentation for Networking in Compose details default hostname and networks used for containers.
Modify your docker compose file as follows:
services:
  front:
    environment:
      API_URL: http://back:${BACKEND_PORT}/api

Modify your javascript file as follows:
const dev = {
  ...env,
  apiUrl: process.env.API_URL || 'http://localhost:3000/api'
};


text:
Q: How to translate the Json in to POJO I have the following JSON I need to be able to present in POJO, how could I
do this ?
The JSON has one key per day and the value for each key is two separate logical arrays, I am using Jackson library.
{
  "2014/01/02": [
    {"ABC": 2.25, "XYZ": 4.05},
    {"amazon.com": 3}
  ],
  "2014/01/03": [
    {"ABC": 13.02},
    {"amazon.com": 3}
  ]
}

A: You don't have much option. That's an ugly looking JSON. There is no consistent format, where you can create POJO.
Things you need to consider. This {} is a JSON object. Im Java mapping terms, it can either map to a POJO, or a Map. In order to map to a POJO, you need to common property names and formatting, of which it doesn't seem like you have. It all seems to be varying. So you may need to use a Map. Here's how I look at it
{  // Start Map
  "2014/01/02": [ // Map key: start Array ( List<Map> )
    {"ABC": 2.25, "XYZ": 4.05},  // Start another Map
    {"amazon.com": 3}  // another Map

You can use @JsonAnySetter to simplify, using a POJO wrapper, but you will still have, in the end a Map<String, List<Map<String, Object>> as I pointed out in my comment. If you want POJOs, there needs to be some common formatting.
Here's an example of one way to make it work
POJO
public class Dynamic {
    private Map<String, Object> map = new HashMap<>();

    public Object get(String key) {
        return map.get(key);
    }

    public Map<String, Object> getMap() {
        return map;
    }

    @JsonAnySetter
    public void set(String name, Object value) {
        map.put(name, value);
    }
}

Test (using your exact JSON in simple.json file)
public class Test {

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        Dynamic dynamic = mapper.readValue(new File("simple.json"), Dynamic.class);
        for (String key : dynamic.getMap().keySet()) {
            System.out.println("key: " + key);
            System.out.println("--------");
            List<Map<String, Object>> list = (List<Map<String, Object>>) dynamic.get(key);
            for (Map<String, Object> map : list) {
                for (Map.Entry<String, Object> entry: map.entrySet()) {
                    System.out.println("key: " + entry.getKey() + ", value: " + entry.getValue());
                }
            }
            System.out.println("========");
        }
    }
}

Result
key: 2014/01/03
--------
key: ABC, value: 13.02
key: amazon.com, value: 3
========
key: 2014/01/02
--------
key: ABC, value: 2.25
key: XYZ, value: 4.05
key: amazon.com, value: 3
========

A:     {
  "2014/01/02": [
    {"ABC": 2.25, "XYZ": 4.05},
    {}
  ],
  "2014/01/03": [
    {"ABC": 13.02},
    {"amazon.com": 3}
  ]
}
This is even JSON, but not useful. I would make JSON for this like below.
{
  [
     {date: '2014/01/01',data:[{abc: 13.02, "amazonCom": 3},{abc: 13.02, "amazonCom": 3}},
     {date: '2014/01/02',data:[{abc: 13.02, "amazonCom": 3},{abc: 13.02, "amazonCom": 3}},
   ]
}

Java
public jsonObj {

    private String date;
    private List<DateData> data;

   .... setter//getter

}

public class DateData {
   private double abc;
   private int amazoneCom;
    //constructor and getter/setter
}

You can use JSON libraries like below.

1. Jackson - http://jackson.codehaus.org/
2. Gson  - https://code.google.com/p/google-gson/

Those libraries helps you to convert json into Java Object and vise versa as well.

Hope it can help you with solving your problem.

A: There are many ways to transform json to pojo. Here I am sharing few URL to achieve the same

*

*Google Gson Tutorial : Convert Java Object to / from JSON http://howtodoinjava.com/2014/06/17/google-gson-tutorial-convert-java-object-to-from-json/

*Generate Plain Old Java Objects from JSON or JSON-Schema. http://www.jsonschema2pojo.org/


text:
Q: Trying to submit form values where only part of the form binds to a model (with ASP.Net MVC3) I apologize in advance for a wall of text below. I hope to provide all the info at once that may be needed to understand what I'm doing.
I've got a page where I'm collecting some basic user info (name, email, etc). In another portion of the page I have a multiple choice quiz form (using radio inputs for each question). My goal is to collect the contact info, process the quiz answers, and store a score with the contact info in a QuizResults table.
This may be a case of over thinking, or over engineering.. so feel free to tell me I'm going about this all wrong.
Here's my Quiz related models:
public class QuizType {

    public QuizType() {
        this.QuizQuestions = new HashSet<QuizQuestion>();
        this.QuizResults = new HashSet<QuizResult>();
    }

    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<QuizQuestion> QuizQuestions { get; set; }
    public virtual ICollection<QuizResult> QuizResults { get; set; }
}

public class QuizQuestion {

    public QuizQuestion() {
        this.QuizAnswers = new HashSet<QuizAnswer>();
    }

    public int Id { get; set; }
    public string Question { get; set; }
    public int Order { get; set; }
    public int QuizTypeId { get; set; }

    public virtual ICollection<QuizAnswer> QuizAnswers { get; set; }
    public virtual QuizType QuizType { get; set; }
}

public class QuizResult {
    public int Id { get; set; }
    public string TesterName { get; set; }
    public string TesterEmail { get; set; }
    public string TesterCompany { get; set; }
    public string TesterPhone { get; set; }
    public string ApproverName { get; set; }
    public string ApproverEmail { get; set; }
    public bool HasCompanyIssuedIdBadge { get; set; }
    public int Score { get; set; }

    public virtual QuizType QuizType { get; set; }
}

public class QuizAnswer {

    public QuizAnswer() {
    }

    public int Id { get; set; }
    public bool isCorrectAnswer { get; set; }
    public string Answer { get; set; }
    public int QuizQuestionId { get; set; }

    public virtual QuizQuestion QuizQuestion { get; set; }
}

So basically I can create a Quiz Type, then for each type I can create multiple questions, each question can have multiple answers. I'm not trying to post back any data for QuizType, QuizQuestion, or QuizAnswer. Those are just there to help build my page[s].
This is where I start scratching my head. I need to be able to iterate through QuizQuestions and QuizAnswers to create the multiple choice form. But I also need to bind part of that form to QuizResults for posting back....  here's what I've got now in order to display the form (but not work correctly).
First, I've created a ViewModel:
public class QuizViewModel {
    public IQueryable<QuizQuestion> QuizQuestions { get; set; }
    public QuizResult QuizResults { get; set; }
}

Then in my controller:
    public ViewResult Index() {

        var questions =
            from q in unitOfWork.QuizQuestionRepository.Get()
            where q.QuizType.Name.Equals("QuizTypeOne")
            select q;

        var qvm = new QuizViewModel {
            QuizQuestions = questions
        };

        return View(qvm);
    }

I won't post my entire razor view, but I think these are the pertinent parts:
@model QuizViewModel

@* *** MISC STYLE, JS, ETC LEFT OUT FOR BREVITY *** *@

@using (Html.BeginForm()) {

    @Html.LabelFor(model => model.QuizResults.TesterName)

    @Html.EditorFor(model => model.QuizResults.TesterName)

    @* *** OTHER FORM FIELDS LEFT OUT FOR BREVITY *** *@

    foreach (var item in Model.QuizQuestions) {

@item.Question

            @{
                // I've been tinkering with this trying to find a way to get it
                // so that the input would have the right id to be picked up and
                // dropped into my post object correctly
                var inputId = "SelectedAnsers[" + item.Id + "]";
            }
            @foreach (var answer in item.QuizAnswers) {
                <input type="radio" id="@inputId" name="@inputId" value="@answer.Id" /> @answer.Answer @:(@answer.isCorrectAnswer)

            }

    }

}

Back in my controller I have a method setup to handle the post, but it's not doing anything at the moment. I'm just running in debug and looking at the values posted when I submit the form.
[HttpPost]
public ViewResult DukeDrive(QuizViewModel quizViewModel) {
    // I have a breakpoint set so that I can inspect quizViewModel
    return View();
}

In my head I want to be able to process the quiz form values, calculate the score, then create a new QuizResult object based on the contact info filled out and the newly calc'd score. I'll be darned if I can find the right way to do it though.
Any pointers?

A: You could add another parameter of type FormCollection which contains all posted values.
[HttpPost]
public ViewResult DukeDrive(QuizViewModel quizViewModel, FormCollection formData) {
    // I have a breakpoint set so that I can inspect quizViewModel
    return View();
}


text:
Q: Accelerometer not working on Android-wear emulator sensor set acceleration 9.77621:0:0

is not working for Android wear emulator..
I have register event for sensor value change, but not getting any call back.
is it suppose to work differently then phone? (using mac)


text:
Q: Read channel recent actions with telegram bot My bot is admin in a channel and I want to read channel's recent actions(like who joined the channel and etc) using python-telegram-bot. How can I achive this?

A: There have no method to get recently actions by bot. And bots won't get notified when users joined channel.
If you want to know whether user in your channel, there have getChatMember method.


text:
Q: Is imklaunchagent virus or Apple system file? My client suspects the imklaunchagent damages his computer. I did some research but found two explanations. One is Apple's system file and the other is virus. Which one is true?
Apple System File?
claim 1

man imklaunchagent" in Terminal.app says:
imklaunchagent is automatically invoked to launch input methods that
are selected via direct user inter- action. It is not intended to be
invoked via other means and must not be terminated. imklaunchagent
monitors abnormal behavior and will disallow an input method from
launching if it repeatedly terminates unexpect- edly within a short
timespan.

(Reference: https://discussions.apple.com/thread/251183015)
claim 2

Do you happen to write in, say, Chinese or Japanese? I think the
process you are mentioning is part of Apple's Input Method Kit
framework (
http://developer.apple.com/releasenotes/Cocoa/RN-InputMethodKit/index.html),
which is used to support languages that use complex scripts.
The program itself is located in: /System/Library/Frameworks/InputMethodKit.framework/Versions/A/Resources/imklaun
chagent
(Reference: https://discussions.apple.com/thread/1463920)

claim 3 (see answer, not the question)

It's a standard macOS process. If you ever google a process name & all
you get are 'malware removal sites trying to sell you something'…
think twice about why. If the threat was real, the make-a-quick-buck
sites would be far far down the list, well below real issues faced by
real people.
The process is inside a protected area, in the System folder on the
System partition. You'd have to try very, very hard to overwrite it
with a malicious component - including rebooting to Recovery &
manually disabling SIP. macOS simply will not let a random process
anywhere near that area, even with admin permission.

(Reference: https://superuser.com/questions/1578763/how-do-i-remove-the-imklaunchagent-malware)
Virus?
(Reference: https://sensorstechforum.com/imklaunchagent-mac-remove/)

A: I think my research already answers the question. Just to let my client feel safe and make sure the result is correct. I will keep this thread for other users.


text:
Q: Find the order of the differential equation governing a system Consider a system where we are given the step response $$y(t) = 1-(1+t)e^{-t}$$
And are then asked to find the order of the differential equation which governs the system.
I have started by finding that the impulse response to the system is given by $$g(t) = te^{-t}$$
I have then found the derivative of the impulse response as $$\frac{dg}{dt}=e^{-t}-te^{-t}$$
At $t = 0$, $g(t)$ is continuous however $g'(t)$ is not (we are assuming that both are zero before $t=0$). I think this means that the system is second order but I am not sure how to reason that from the above information.

A: Without some knowledge of the initial conditions we can have different differential equation that are satisfied by  your equation.
The one proposed in the answer of gt6989b   is one, that has  solutions of the form
$$
1-(c_1+t)e^{-t}
$$
that has one integration constant that can be determined by the initial condition. But we can have also the equation
$$
y''+2y'+y-1=0
$$
that has solutions of the form
$$
y=1-(c_1+c_2t)e^{-t}
$$
with two integration constants, so, at least, we must know how many initial conditions you have.

A: Not sure what exactly you are after, but note that $$y(t) = 1 - e^{-t} - te^{-t}$$ hence $$y'(t) = te^{-t}$$and so you have the obvious differential equation $$y' +y = 1-e^{-t}.$$
Can you determine the order?


text:
Q: Beanstalkd/Pheanstalk for PHPMailer on Amazon EC2 I would like to implement a queuing mechanism for sending out email via PHPMailer on Amazon EC2. I have set up Beanstalkd correctly on the server and can access it via a console. The mail doesn't seem to go through (trying the various combinations of sample code). In addition do I need to set up a cron job also that would call one of the producer or consumer files?
Does anyone have working code for sending out email via phpmailer/pheanstalk please for Amazon EC2?
Thanks.

A: Beanstalkd is great, and I use it myself, however, don't use it for this; It's reinventing the wheel in a bad way. Instead, install a local mail server such as postfix and get that to do your queuing for you. This is also much, much simpler, faster, and easier to control. Email servers are built for managing queues, and they are extremely good at it.
Before you do so, get your mail sending script working – there's no point in even attempting to get something more complex working until you've done that. Also be aware that sending email from EC2 is difficult – Amazon wants you to use their SES service rather than sending directly – you may find sending is blocked altogether. Read the PHPMailer troubleshooting guide to see how to diagnose that.


text:
Q: Unity - coroutines got inaccurate with timing, want to get around I wish to move an object over time using coroutines. I wanted to get an object from point A to point B over say 2 seconds. To achieve this I used the following code:
IEnumerator _MoveObjectBySpeed()
{
    while (TheCoroutine_CanRun)
    {
        if(myObject.transform.position.y <= UpperBoundary.position.y)
        {
            myObject.transform.position = new Vector3(myObject.transform.position.x,
                myObject.transform.position.y + Step, myObject.transform.position.z);

        }
        yield return new WaitForSeconds(_smoothness);
    }
    TheCoroutine_CanRun = true;
    moveAlreadyStarted = false;
}

and the Step is calculated like
    private void CalculateSpeed()
{
    Step = _smoothness * allDistance / timeToReachTop;
}

where allDistance is the distance between the bottom and the top boundary.
_smoothness is a fix value. The thing is, the bigger I get this value, the more accurate the time gets to get from bottom to up. Note that a small value here means smoother movement. This smoothness is the time the coroutine waits in between moving the myObject.
The time is measured like this:
    void FixedUpdate()
{
    DEBUG_TIMER();
}

#region DEBUG TIME

public float timer = 0.0f;
bool allowed = false;
public void DEBUG_TIMER()
{

    if (Input.GetButtonDown("Jump"))
    {
        StartTimer();
    }
    if (myObject.transform.position.y >= UpperBoundary.position.y)
    {
        StopTimer();
        Debug.Log(timer.ToString());
        //timer = 0.0f;
    }
    if (allowed)
    {
        timer += Time.fixedDeltaTime;
    }
}
void StartTimer()
{
    timer = 0;
    allowed = true;
}
void StopTimer()
{
    allowed = false;
}
#endregion

The results were:
When I wanted the object to reach the top under 1 second and set the _smoothness to 0.01, the time the myObject took to get to the top was 1.67 seconds. When _smoothness was 0.2s, the time to actually reach the top was 1.04s.
So why is this so inaccurate and how to make it work fine?

A:
This smoothness is the time the coroutine waits in between moving the myObject

The mistake you're making is assuming that a co-routine waits the perfect time before executing.  Rather, it probably executes on the next frame after the timeout has finished.
Assuming you want smooth motion, you want to move the object every frame (e.g. in Update or co-routine that uses 'yield return null').
Note:  Each frame may take a different duration (consider 144fps vs 15fps), and you can discover this in Time.deltaTime . https://docs.unity3d.com/520/Documentation/ScriptReference/Time-deltaTime.html


text:
Q: Docker Desktop remains stopped on Ubuntu Desktop 20.04 through VirtualBox For two different laptops using Windows 7 and 10 - with VirtualBox 6.1.36 - the guest is Ubuntu Desktop 20.04 as follows
lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.4 LTS
Release:    20.04
Codename:   focal

To install Docker I watched and followed the instructions according with:

*

*Docker Desktop installation on Ubuntu 22.04
The video covers the installation for Docker Engine and Docker Desktop respectively
The sudo docker run hello-world commands works as expected, so the Docker Engine is installed and works fine as expected, just in case more info:
docker compose version
Docker Compose version v2.7.0

docker --version
Docker version 20.10.17, build 100c701

sudo docker version
Client: Docker Engine - Community
 Cloud integration: v1.0.28
 Version:           20.10.17
 API version:       1.41
 Go version:        go1.17.11
 Git commit:        100c701
 Built:             Mon Jun  6 23:02:57 2022
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          20.10.17
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.17.11
  Git commit:       a89b842
  Built:            Mon Jun  6 23:01:03 2022
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.6.6
  GitCommit:        10c12954828e7c7c9b6e0ea9b0c02b01407d3ae1
 runc:
  Version:          1.1.2
  GitCommit:        v1.1.2-0-ga916309
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0

The installation of the Docker Desktop is fine, but when is started through either Applications or Command, the GUI is loaded but it remains with the following message:

*

*Docker Desktop stopped...
It remains in that state for many minutes
how resolve this issue?

A: The solution is enable KVM Virtualization for VirtualBox, it through the Enable Nested VT-x/AMD-V checkbox.
Having VirtualBox closed, execute:
VBoxManage modifyvm <VirtualMachineName> --nested-hw-virt on

For more details about why is used the command, read the following resources:

*

*VirtualBox 6.1x: How enable 'Enable Nested VT-x/AMD-V' to enable 'KVM virtualization'?

*Virtualbox enable nested vtx/amd-v greyed out

A: Enable Virtualization for your system. This is not docker desktop issue.


text:
Q: What microcontroller should I use? I'm trying to find the best micro controller package for my computer programs to communicate with the real world. I am hoping for a large number of I/O pins (so far 64 digital is all i need, nothing fancy like analog and PWM) which an I can read and write directly by calling functions from my program running on my CPU.
I don't want to download programs onto the micro controller itself to run, rather i would like something that simply plugs into my USB and gives me a bunch of CPU controlled I/O pins that i can control from my C++ programs.
What would be the best micro controller package for me? I hope for something that is fairly inexpensive but future proof, as in it runs off USB and has 64-bit drivers for modern OS like Windows 7. Being able to interface more than one of these micro controllers with the same computer program would be a great bonus as well (future expansion).
Edit: I don't need high sampling rates (maybe 10 Hz for reading inputs, 1 kHz for output signals) and most of the pins are used for output only. I am working with brand new computers (core i7 860) so even if the sampling is a bit inefficient or slow, it should still be ok (just have one thread dedicated to I/O and have the main program communicate with it).
I also don't need all 64 I/O pins on a single micro controller package. If i can interface many micro controller packages at the same time, that would work too (actually it would be ideal to be able to interface many smaller micro controller packages, that means it's easy to expand).
I've looked at this: http://www.schmalzhaus.com/UBW32/index.html
Has anyone had any experience with something like this? Any idea if it will work or not? The main concern is that it is the micro controller that is running the program, not my CPU.

A: I recommend a Teensy++ 2.0 (or any other AT90USB1286 development board)
128KB Flash, 8KB RAM, 46 I/O pins, 8 analogue inputs
$24
The Teensy boards are USB powered and can provide a virtual COM port (USB Communications Device Class). You could make use of this serial link for your pin control protocol.
This works without any custom drivers on Windows, OSX and Linux.
To create the pin control firmware, there's TeensyDuino or plain old C.
When bit banging, the bottleneck is going to be the microcontroller's USB interface. So you may want to shift protocols such as I2C and SPI down to the microcontroller. For this you could use my Bus Ninja.
Adding additional Teensies to your setup is simple, you just need one USB port per device, presenting one virtual COM port per device.
(Note. This approach will work equally well with a whole range of ARM processors and others, I just don't know of any cheap development boards with available software).
Another way could be to use an Arduino and a Caterpillar Shield to expand the I/O. On a custom board I built around the same I/O expander I was able to update 256 outputs at over 1KHz.

A: I think what you want is not a microcontroller, but something like a National Instruments PCI-6509 I/O card. You can get USB versions as well, but they have many fewer I/O than the PCI-6509. National Instruments will sell you C++ drivers as well.
If that looks too expensive, you could try something like the Labjack U3.

A: The solution you describe does not exist for lower prices. The problem is that you want to run the control software on a system that's not designed for it. Serializing 64 ports and pushing it through USB at high sampling rates slows down the host computer immensely.
There are solutions that work for low performance applications like the labjack mentioned. But the real solution you need to handle high IO rates will involve a programmed system. The question is what programming you have to use to implement the system.
LabView is highly expensive software (which works great, don't get me wrong). It uses a graphical language to design software and compiles to code running on an FPGA or ARM system. All components are too expensive for a high volume embedded app, but absolutely wonderful in a testing environment because of the quick development, high performance offered.
A less expensive solution is to find a system that runs linux with many I/O. EmbeddedARM.com is a site that offers many types of products for this. The code you can write may be in shell scripts, java, C, etc.
The Arduino systems provide microcontrollers that can be developed with a simpler development environment. Their open source nature means there are already many projects to learn from.

A: Faken,
The UBW32 is a very good way to go, from what I can tell of your requirements. It will support exactly what you need, as long as you're OK with 3.3V I/O (some are 5V tolerant, but not all.) It is inexpensive ($40) and is very easy to talk to using any language that can support serial ports (which is pretty much all of them - Basic, C, C#, Processing, etc.)
You can use any of the 76 I/O pins as inputs or outputs. The stock firmware as shipped will allow you to do what you want to do, no programming required on the embedded side. Getting that data up to the PC over USB (at only 10Hz) will be no problem. Getting outputs to go at 1KHz will probably work just fine as well.
If you have any questions, please let me know. I'm happy to help you out.
*Brian Schmalz
UBW32 creator

A: i don't know of any with 64 GPIO pins, thats a lot, you may have to build that yourself.
I use this for bench testing serial interfaces but it also has 23 GPIO pins.
If you just google for 'USB to GPIO' there a bunch of projects out there that have done this, i didn't see any in the first couple pages with 64 GPIOs this is the closest i found, with 32 pins.
Building one wouldn't be very hard, i'd probably just use a 100pin pic18 with built in USB PHY (depending on your speed requirements a more powerful cpu may be in order)
you wouldn't have to do too much coding to get it working as long as your uC vendor offers a USB driver skeleton.
You would have to build a PCB for it most likely as chips that are large enough to have 64 GPIO pins generally do not come in through-hole packages.  You could also use a smaller microcontroller and use external port expander IC's for your GPIO's but that would be a more complex design and more complex to program.
You could also look at dev boards that route all I/O pins to headers and have USB.  These will likely be a lot more expensive as they will likely have a bunch of stuff you don't need.
One final tip, if you find a board with RS232 but with 64 GPIO pins available, you can use an RS232 to USB adapter, i have a few of these that have worked well for me.  This does limit you to the speed of the RS232 interface however.

A: The NI Labview environment is expensive, but it will do what you need (Over USB, Ethernet, or PCI depending on what you get.)
The Arduino Mega has 54 pins, which gets you close, for $60.  However, it's not a logic analyzer out of the box; you'd have to write or find a sketch to do this. There may be one available, I don't know.  This should be fairly simple at low bus rates.  Each instruction on the Mega happens at 16MHz, so you'll have a fairly slow baud rate, you'll be lucky or very clever if you can get a 115200 baud signal.
In the end, this is a very different project if you're sampling at 9600 baud or at 50MHz.  Remember, USB runs at 480 MHz (In theory; your actual data rate will be lower due to latencies and overhead) so you can't do any better than 480/64 = 7.5MHz without buffering.  With buffering and obscene amounts of money (More than your car), logic analyzers can get you 68, 102, or 136 channels at gigahertz data rates.
I would suggest that you very seriously try to figure out if you can use a tool that gives you 8 channels or so, and try to analyze them separately.
EDIT:  Aargh, what was I thinking? If you're going at slow rates like that, then working over a serial link is definitely the way to go. I  use the ADAM 4000 module system from Advantech  all the time at work; they're robust, easy to use (easily interfaced with an ASCII protocol over a COM port, or use the included GUI software), expandable, and well supported.  Get yourself a 4500 (RS-232, use a USB converter or COM port on your computer (if it's still got one)) or 4501 (Ethernet with embedded webserver) controller, link in a bunch of 4053, 4055, and 4056 modules, and you're good to go.

A: This thing's got 70 GPIOs and a USB interface for $50.

A: Yes, it looks like the UBW32 would work fine for you, and the default firmware lets you control the I/O pins from your software on your PC.
According to
"how to bit bang SPI and parallel interfaces on an FT232R", you can apparently bit-bang 8 digital pins (possibly more?) on the FT232R controlled by software on your PC.
$15 Breakout Board for FT232RL
It sounds like what you really want is a digital I/O interface; you neither need nor want a programmable microcontroller.
If you only wanted 16 bits, I would go with a couple of FT232RL boards.
However, it looks like a single $40 UBW32 looks like it will give you the 64 I/O you want for less cost than 8 of the FT232RL boards it would require to get 64 I/O.
I'm finding that's becoming increasingly common -- it sometimes costs less to throw an entire microcontroller at a problem, even though it has a million "extra" transistors I'll never use on it, than to use a hard-wired solution.


text:
Q: "sync" content via filename Okay, well I've uploaded 5 gigs of images to Dropbox, and those are directly off the camera.
In another country, my friend with rubbish internet (whom retrieved a CD containing the images) copied the images to a folder on his desktop and began sorting out the images; that is- deleting bad/unneeded images. I can't ask him to upload 5gigs to MY personal dropbox account, when it took me a week to upload with my faster internet.
Is there a piece of software that I can run on his Windows 8 PC to take a list of filenames (directory recursive, since I gave it to him sorted in individual folders for each event); which when then run again on my Snow Leopard MacBook would be able to see which images were deleted on my friend's computer; and then delete them on my side.
If such a program doesn't exist, what framework can I use to programme this (I'm developing on a Mac)? And what tips would you give me?

A: This answer borrows liberally from a couple of the comments.  Have your friend run
dir /b/s/a-d > dir.out

You run
find . -print > find.out

Normalize dir.out and find.out:

*

*Make the line endings uniform (e.g., NL or CRLF),

*Remove common prefixes (C:\Users\… and ./),

*Change backslashes (\) to slashes (/) in dir.out, and

*Sort both files.

Now do
comm dir.out find.out

(You may want to pipe that into a pager such as more or less.)
The output will consist of three columns:

*

*Entries (filenames) present only in the first file (dir.out).  There shouldn't be any; if there are, your friend included a file that he didn't get from you, or else you didn't completely normalize the files.  (OK, depending on exactly how your friend did his dir command, the dir.out file itself might show up in column 1.)

*Entries present only in the second file (find.out).  These are the names of the files that you have on your system but your friend didn't list.  In other words, these are the files you want to delete.

*Entries present in both files.  This should be the same as dir.out.

If there are false negatives because of case mismatches ('A' ≠ 'a'),
try the comm command again with a -f option.
You'll probably to repeat the sort with a -f option, too.
Now, type comm -13 dir.out find.out.  This incredibly brain-damaged syntax means
"give me all the normal output except for columns 1 and 3," in other words, output column 2 only.  As indicated above, this is the list of files you want to delete,
so pipe it into xargs rm or something like that.

I'm assuming that you don't have any wild and crazy characters
(such as space, quotes, '*', '?', '<', '|', etc.) in your filenames.
(This shouldn't be a problem; cameras tend to use filenames like "DSCN1234.JPG".)

A: You could pull that off with GoodSync Connect (not affiliated). It costs to use this feature, but there is a 30-day trial during which it works in the free version.

*

*You install GoodSync on both sides (there are Mac, Windows and Linux
versions).

*You set up GoodSync Connect which establishes a direct-ish link where info about the     directories are transferred via mediator, though not the files themselves.

*On your side, you set up a Sync job.

*Select the  Dropbox folder with the pictures.

*Your friend copies the files from the DVD to a directory. Select this folder through GoodSync Connect.

*You select the Analyze option in the sync job. GS now establishes that both folders are the same. This creates a reference comparison file on both sides. (Important!)

*Then your friend deletes the pictures he does not want. (Or, if he has already done so, he deletes the content of the folder where he stored all pictures - except for the _gsdata folder. He puts the modified folders there.)

*Perform analyze, which will show you a preview.

*If your OK, sync. GoodSync will do its magic.

Notes:

*

*GoodSync will detect file and folder moves and renames and should work without a hiccup. So it will not attempt to move files. (Unless the file contents have been modified. But that's why you analyse first!)

*GoodSync will delete those files your friend has deleted. They'll be in the Recycle bin.

*Oh, and do make a backup before this. Yes, seriously. Or try it locally.

*And if you don't trust your friend, disable the GoodSync Connect server after you're done. Otherwise your friend will see all your files. (There is probably a way around this, but I haven't found it yet.)


text:
Q: Downloading File using AFHTTPRequest Operating isn't working? This is the code I'm using (from this Stack Overflow question, although it's slightly modified):
NSLog(@"Saving File...");

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[detailDataSourceDict valueForKey:@"filepath"]]];
NSLog(@"This is the link you are downloading: %@",request);
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Successfully downloaded file to %@", path);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

[operation start];

I get the NSLog "Successfully downloaded file to /Users/xxxx/Library/Application Support/iPhone Simulator/6.0/Applications/F29C1E99-A277-41DC-8205-6556B6123A85/Documents" but when I open up that folder in Finder, I don't see the file.  Is there anything that I am doing wrong?  I am not getting errors in my code.  Any help would be appreciated, thanks.

Update
I am using the AFNetwork library...

A: You're setting the download location to the actual Documents Directory, rather than a file in the directory. Update your code to use a specific file within the directory.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0]; //filepath to documents directory!
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:[path stringByAppendingPathComponent:@"filename.extension"] append:NO];

Also, I think you may want to be setting the inputStream property rather than the outputStream because you are downloading a file rather that uploading one.


text:
Q: Sharing a struct across header files I'm not sure how to correctly do this. I need to access a struct from another header file. I currently have 5 files. foo.h foo.c bar.h bar.c main.c.
foo.h
#ifndef FOO_H_   /* include guard */
#define FOO_H_

typedef struct foostruct{
  int data;
} foostruct;

#endif

foo.c
#include "foo.h"
// empty

bar.h
#ifndef BAR_H_   /* include guard */
#define BAR_H_

typedef struct barstruct{
  int data;
  foostruct* foodata;
} barstruct;

#endif

bar.c
#include "bar.h"
#include "foo.h" // <-- thought i had to do it like this
// empty

main.c
#include <stdio.h>
#include "foo.h"
#include "bar.h"

int main () {
  printf("main\n");

  return 0;
}

compile error
gcc -Wall -std=c11 -c main.c foo.c bar.c
In file included from bar.c:1:0:
bar.h:6:3: error: unknown type name 'foostruct'
   foostruct* foodata;
   ^
make: *** [Makefile:22: main.o] Error 1

A: Change bar.h to:
typedef struct barstruct{
  int data;
  struct  foostruct* foodata;
} barstruct;

Note struct foostruct *
With this change, you dont need the dependancy of foo.h by bar.h.


text:
Q: MongoDB : Parse each child and set flag recursively I would like to recursively parse each child's sub-child and set the flag to the child. Is it possible to do that using the mongo query with aggregate functions like "$graphLookup"
I am new to MongoDB, but I heard about the use of aggregate functions but not sure whether it can be achieved using mongo query itself?

My Collections Structure :

  Parent
  |
  |---Child1  // Depth 1
      |
      |---Sub child   // Depth 2
          |
          |---Sub Sub Child  // Depth 3
          ...
          ...
          |--- nth Child     // Depth n

  |---Child 2  // Depth 1
      |
      |---Sub child   // Depth 2
          |
          |---Sub Sub Child  // Depth 3
          ...
          ...
          |--- nth Child     // Depth n


text:
Q: unknown directive "geoip_country" on nginx/1.10.1 I have  a nginx/1.10.1 on my CentOS 7 installed via nginx repo. I just install geoip module
[root@www nginx]# nginx -V
nginx version: nginx/1.10.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-4) (GCC)
built with OpenSSL 1.0.1e-fips 11 Feb 2013
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-http_ssl_module --with-http_realip_module --with-http_addition_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_stub_status_module --with-http_auth_request_module --with-http_xslt_module=dynamic --with-http_image_filter_module=dynamic **--with-http_geoip_module=dynamic** --with-http_perl_module=dynamic --add-dynamic-module=njs-1c50334fbea6/nginx --with-threads --with-stream --with-stream_ssl_module --with-http_slice_module --with-mail --with-mail_ssl_module --with-file-aio --with-ipv6 --with-http_v2_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic'

Added geoip_country GeoIP.dat; to http section on nginx.conf, but when I am doung configtest
[root@www nginx]# nginx -t
nginx: [emerg] unknown directive "geoip_country" in /etc/nginx/nginx.conf:40
nginx: configuration file /etc/nginx/nginx.conf test failed

Can anybody help me? Thanks beforehand.

A: Dynamic modules must be explicitly loaded from the main section of the nginx configuration.
 load_module "modules/ngx_http_geoip_module.so";

A: Although the solution Michael proposed works the underlying problem is that nginx does not properly (sufficiently) load the modules from the /etc/nginx/modules-enabled/. Likely due to the wrong scope where these modules are loaded from.
Much better, permanent solution is to add this line to nginx.conf:
include /etc/nginx/modules-enabled/*;

A: file /usr/share/nginx/modules-available/mod-http-geoip.conf

when ASCII text file is exist
ln -s /usr/share/nginx/modules-available/mod-http-geoip.conf /etc/nginx/modules-enabled/mod-http-geoip.conf

and then service nginx start
done


text:
Q: Are nonmeasurable sets whose sections are null always contained in a null measurable set? Equip $\mathbb R_{\geq 0} \times \Omega$ with the product measure structure of Borel measure for $\mathbb R_{\geq 0}$ and a probability measure for $\Omega$.
Suppose we have a set $S=\cup_{t \geq 0}(t,E_t)$ all of whose sections $E_t$ are measurable and have probability zero.
Unfortunately, $S$ is potentially nonmeasurable. Can we at least prove that it is contained in a measurable set of zero product measure?
The usual example of a nonmeasurable set on the diagonal of the Borel unit-square fails to form a counterexample since the diagonal is measurable and null.

A: No.  For instance, let us consider Lebesgue measure on $\mathbb{R}^2$.  It can be shown that if $A\subseteq\mathbb{R}^2$ is measurable with positive measure, then there are $2^{\aleph_0}$ different values of $x$ such that $A$ contains a point of the form $(x,y)$.  Also, there are only $2^{\aleph_0}$ different Borel subsets of $\mathbb{R}^2$, and any measurable set of positive measure contains a Borel set of positive measure.  Using this, by a transfinite recursion of length $2^{\aleph_0}$, you can construct a set $S\subseteq\mathbb{R}^2$ such that $S$ intersects every Borel set of positive measure (and thus every measurable set of positive measure), but for each $x\in\mathbb{R}$, $S$ contains at most one point of the form $(x,y)$ (just one by one choose points to put in $S$ to make it intersect each Borel set of positive measure, avoiding any $x$-values you have already chosen).  Then every section of $S$ is measurable with measure $0$.  However, $S$ is not contained in any measurable set of measure $0$, or indeed in any measurable set which does not have full measure, since $S$ intersects every measurable set of positive measure.


text:
Q: Keycloak authorization service for REST application without keycloak adapter I was checking keycloak authorization service to implement authorization service for few of the REST endpoints which do not have keycloak adapter implemented.
From keycloak quick starts example it looks like authorization service only supported for end points which has keycloak adapter implemented.
Has any one tried to perform keycloak authentication to a REST request before request actually goes to that server.
The REST endpoints are written in Node.JS and i can't implement the adapter in Node.JS because it is not maintained by us. :)


text:
Q: Is it possible to re-arrange widgets based on the project in Sonarqube? I noticed that existence and placements of widgets are global across all projects in Sonar. Is it possible to customize based on project? For example, if I want project A to have only 1 widget and 1-frame layout, while project B is divided into a 3-column layout with 10 different widgets, is it possible to do so?
The reason I ask is because from an overview perspective we use the "measure filter as treemap" widget in the home dashboard to give a visual overview of all projects based on a certain metric. However, if we don't want to include a certain project even though it has the metric (It is a branch of another project), we can't do so.
From a customization POV, some widgets are simply not needed in certain projects even if they show anything.
I've tried going through the documentation and of course google/SO search but have not found anything related to this.

A: What you try to achieve is not possible currently. The dashboards are always displayed the same way, whatever the project.


text:
Q: SQLite C API equivalent to typeof(col) I want to detect column data types of any SELECT query in SQLite.
In the C API, there is const char *sqlite3_column_decltype(sqlite3_stmt*,int) for this purpose. But that only works for columns in a real table. Expressions, such as LOWER('ABC'), or columns from queries like PRAGMA foreign_key_list("mytable"), always return null here.
I know there is also typeof(col), but I don't have control over the fired SQL, so I need a way to extract the data type out of the prepared statement.

A: You're looking for sqlite3_column_type():

The sqlite3_column_type() routine returns the datatype code for the initial data type of the result column. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. The return value of sqlite3_column_type() can be used to decide which of the first six interface should be used to extract the column value.

And remember that in sqlite, type is for the most part associated with value, not column - different rows can have different types stored in the same column.


text:
Q: DivideByZeroException not working and giving out random integers (such as 8)     {
            **result4 = num1 / num2;**
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write(name + " this is the final result of Divsion = " + result4);
            Console.ReadKey();
            Environment.Exit(0);
    }
    else if (op == "^")
    {
            result5 = Math.Pow(num1, num2);
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write(name + " this is the final result of exponential calculations = " + result5);
            Console.ReadKey();
            Environment.Exit(0);
    }
    else
    {
            Console.ForegroundColor = ConsoleColor.Red;
           Console.WriteLine(name + " this operant does not match the listed operant...this terminal will be cleared and closed after any key is pressed");
           Console.ReadKey();
           Environment.Exit(0);
    }
}
**catch(DivideByZeroException)**
{
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(name + " you can not divide by zero; math error");
}

This is part of the script...but this is the main part of the error. If need be I will post the full script. The two asterisks on top of the word result 4, and catch, is to indicate the two-piece of codes.

A: As far as I know double 0 can actually be something like 0,000000001. Meaning that is not dividing by zero, but dividing with a very small number, leading to close to infinity as a result, which you are getting.
In this very example you can simply test if your num2 is close enough to zero, and if so, throw an exception.
If(Math.Abs(num2) < 0,00001)
    Throw DivideByZeroException


text:
Q: Redirect Human User, but not Facebook Crawler I have a simple Django site, with 2 pages. It is kind of like those stupid buzzfeed quizzes.  There is a questions page (www.mypage.com), and a results page (www.mysite.com/results/myResults).  I am trying to use the facebook share button to drive social sharing.  I want people to share the results page (e.g. "I got this result, what about you?"), but I need incoming users clicking these shared links to be redirected to the main questions page.
I have tried adding a URL parameter www.mysite.com/results/myResults?fromShare = T and using a view to redirect these to the main page. However, the facebook crawler also gets redirected, so the shared content ends up being the main page, rather than the individualized results page.
tl;dr: how do I redirect incoming human users, while not redirecting the facebook crawler? I would ideally like to do this in a django view, rather than .htaccess.

A: Facebook user agent will be one of these:
facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)
facebookexternalhit/1.0 (+http://www.facebook.com/externalhit_uatext.php)
facebookexternalhit/1.1 (+https://www.facebook.com/externalhit_uatext.php)
facebookexternalhit/1.0 (+https://www.facebook.com/externalhit_uatext.php)
Look for these in request.META['HTTP_USER_AGENT'] and redirect.

A: In your view, look at request.META['HTTP_USER_AGENT'], compare it to Facebook crawler's, and redirect if it doesn't match.  If it does match, serve your page template.


text:
Q: Soft keybord Del key doesn't work on Android I am using edit text for my application for which soft keyboard is used.
I'm using a text watcher, as suggested in the posts on how to detect soft keyboard key press events, but I'm unable to delete the data which I've entered in the edit text. This means that the del key is not called in the text watcher.
I have set the ime options to "action done", but it's still not working, here's what I've done to invoke the soft keyboard:
((CustomEditText)v).setImeOptions(EditorInfo.IME_ACTION_DONE);
InputMethodManager imm = (InputMethodManager) BookModel.getInstance()
                            .get_mActivity()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInputFromWindow(v.getWindowToken(),
                              InputMethodManager.SHOW_FORCED,
                              InputMethodManager.HIDE_IMPLICIT_ONLY);


text:
Q: How do I do "SELECT something IN (...)" with jooq? I'm trying to do the following with Jooq and can't for the life of me figure out how to do it properly:
select name, id in (
  select capability_id
   from a.capabilities_users
   where user_id = ?)
from a.capabilities;

Basically I want to get all items (capabilities) and know whether each one applies to a particular user.  It seems that all the condition type operators (like greater than or in) can only be used in the where and not the select.  And I can't think of how else to express this.
Worst case, I can do a select count and then do the boolean logic in Java, but I was hoping to use fetchMap.

A: Depending on your database and schema meta data, a LEFT JOIN might be a better choice than a predicate in the projection. You should of course verify this in the execution plan.
Solving this with a LEFT JOIN:
-- NVL2 is Oracle syntax.
-- jOOQ will emulate NVL2 using CASE, if it's not available in your database
SELECT c.name, NVL2(cu.capability_id, 1, 0)
FROM a.capabilities c
LEFT OUTER JOIN a.capabilities_users cu
  ON (c.id = cu.capability_id
  AND cu.user_id = ?)

The above assumes, of course, that there is a unqiue constraint on cu(user_id, capability_id). This would then translate into jOOQ as such:
Capabilities c = CAPABILITIES.as("c");
CapabilitiesUsers cu = CAPABILITIES_USERS.as("cu");

Field<String> key = c.NAME.as("key");
Field<Boolean> value = nvl2(
  CAPABILITIES_USER.CAPABILITY_ID, true, false
).as("value");

Map<String, Boolean> map =
DSL.using(configuration)
   .select(key, value)
   .from(c)
   .leftOuterJoin(cu)
   .on(c.ID.eq(cu.CAPABILITY_ID))
   .and(cu.USER_ID.eq(...))
   .fetchMap(key, value);

Solving this with a predicate in the projection:
If you really prefer a predicate in the projection, you might try DSL.field(Condition), which allows for precisely this:
Field<String> key = CAPABILITIES.NAME.as("key");
Field<Boolean> value = field(
  CAPABILITIES.ID.in(
    select(CAPABILITY_ID)
   .from(CAPABILITIES_USERS)
   .where(CAPABILITIES_USERS.USER_ID.eq(...))
  )
).as("value");

Map<String, Boolean> map =
DSL.using(configuration)
   .select(key, value)
   .from(CAPABILITIES)
   .fetchMap(key, value);

Note that if you're using a standards-compliant database, which doesn't allow for predicates to be treated as columns, DSL.field(Condition) will render an equivalent CASE statement for you.


text:
Q: Android disable multi send request from Fragmemt I'm using NodeJs on server to send and request response, my service and send request and get response work fine when i send request from activity, but when i try to send request from Fragment request is duplicate and twice at moment and i cant fix this problem
My Service:
public class SignalChatServiceProvider extends Service {
    private SignalApplication signalApplication;
    private Realm             realm;
    private String            marketUUid;

    public static SignalChatServiceProvider instance = null;

    public static boolean isInstanceCreated() {
        return instance == null ? false : true;
    }

    private final IBinder myBinder = new LocalBinder();

    public class LocalBinder extends Binder {
        public SignalChatServiceProvider getService() {
            return SignalChatServiceProvider.this;
        }
    }

    public void IsBendable() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return myBinder;
    }

    @Override
    public void onCreate() {
        if (isInstanceCreated()) {
            return;
        }
        super.onCreate();
        new Handler(getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                Utils.toast("onCreate",getBaseContext());

            }
        });
        realm = Realm.getDefaultInstance();

        signalApplication = (SignalApplication) getApplication();

        if (signalApplication.getSocket() == null)
            signalApplication.CHAT_SOCKET = signalApplication.getSocket();

        signalApplication.getSocket().on(Socket.EVENT_CONNECT_ERROR, onConnectError);
        signalApplication.getSocket().on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
        signalApplication.getSocket().on(Socket.EVENT_CONNECT, onConnect);

        //@formatter:off
            signalApplication.getSocket().on("getMarketBanners"                , getMarketBanners);
            signalApplication.getSocket().on("getMarketProducts"               , getMarketProducts);
            signalApplication.getSocket().on("getProductImages"                , getProductImages);
            signalApplication.getSocket().on("getMarketRandomProductImages"    , getMarketRandomProductImages);
            signalApplication.getSocket().on("getRandomMarketLists"            , getRandomMarketLists);
        //@formatter:on

        EventBus.getDefault().register(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (isInstanceCreated()) {
            return 0;
        }
        super.onStartCommand(intent, flags, startId);
        connectConnection();
        return START_STICKY;
    }

    private Emitter.Listener onConnect = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
    };

    private Emitter.Listener onDisconnect = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
    };

    private Emitter.Listener onConnectError = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
    };

    private Emitter.Listener getMarketBanners = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
    };

    private Emitter.Listener getMarketRandomProductImages = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
    };

    private Emitter.Listener getProductImages = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
    };

    private Emitter.Listener getRandomMarketLists = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
    };

    private Emitter.Listener getMarketProducts = new Emitter.Listener() {
        @Override
        public void call(final Object... args) {
    };

    private void connectConnection() {
        instance = this;
        signalApplication.getSocket().connect();
    }

    private void disconnectConnection() {
        instance = null;
        signalApplication.getSocket().disconnect();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (!realm.isClosed())
            realm.close();

        signalApplication.getSocket().off(Socket.EVENT_CONNECT, onConnect);
        signalApplication.getSocket().off(Socket.EVENT_DISCONNECT, onDisconnect);
        signalApplication.getSocket().off(Socket.EVENT_CONNECT_ERROR, onConnectError);
        signalApplication.getSocket().off(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);

        //@formatter:off
            signalApplication.getSocket().off("getMarketBanners"                , getMarketBanners);
            signalApplication.getSocket().off("getMarketProducts"               , getMarketProducts);
            signalApplication.getSocket().off("getProductImages"                , getProductImages);
            signalApplication.getSocket().off("getMarketRandomProductImages"    , getMarketRandomProductImages);
            signalApplication.getSocket().off("getRandomMarketLists"            , getRandomMarketLists);
        //@formatter:on

        disconnectConnection();
    }

    @Subscribe
    public void onEvent(EventChangeChatServerStateEvent event) {
        switch (event.getState()) {
            case connected:
                instance = this;
                connectConnection();
                break;
            case disconnected:
                instance = null;
                disconnectConnection();
                break;
        }

    }
}

My Activity to disable multi running service:
if (SignalApplication.signalApplication.getSocket() != null && !SignalChatServiceProvider.isInstanceCreated()) {
    startService(new Intent(getBaseContext(), SignalChatServiceProvider.class));
    doBindService();
}

now when i try to send request with this code from activity:
SignalApplication.signalApplication.getSocket().emit("getRandomMarketLists");

request count is one
My Fragment is into ViewPager :
@Override
public Fragment getItem(int position) {
    switch (position) {
        case 0:
            return FragmentMainMarkets.newInstance();
        ...
    }
}

when i try to send request from FragmentMainMarkets Fragment, request is twice a moment


text:
Q: Populate Form Based on dropdown value in Codeigniter I have about 30 different forms that will be displayed in a wizard, a form will be displayed based on the value from the dropdown selected, if all forms are created in a view file it doesn't seem effective, I try to save each form in the database and it will Called based on the dropdown value but not as expected, please help with this problem.
this is the code example that I saved into the database:
Yang Bertandatangan Dibawah ini:

                                    Nama

                      <select name="pemberi" class="form-control select-search" required data-fouc>
                        <option value="">--pilih--</option>
                        <?php
                          if(is_array($pegawai)){
                            foreach($pegawai as $row){
                            ?>
                              <option value="<?php echo $row->nip;?>"><?php echo $row->nama;?></option>
                            <?php
                            }
                          }
                         ?>
                      </select>

                  MEMERINTAHKAN:

                                    Kepada:

                                    Nama:

                      <select name="penerima" class="form-control select-search" required data-fouc>
                        <option value="">--pilih--</option>
                        <?php
                          if(is_array($pegawai)){
                            foreach($pegawai as $row){
                            ?>
                              <option value="<?=$row->nip;?>"><?=$row->nama;?></option>
                            <?php
                            }
                          }
                         ?>
                      </select>

                                    Jabatan:

                      <select name="jabatan_penerima" class="form-control select-search" required data-fouc>
                        <option value="">--pilih--</option>
                        <?php
                          if(is_array($pembuat)){
                            foreach($pembuat as $row){
                            ?>
                              <option value="<?=$row->id;?>"><?=$row->nama_jabatan;?></option>
                            <?php
                            }
                          }
                         ?>
                      </select>

                Untuk:

                        <textarea rows="10" cols="4" class="form-control" placeholder="Isi Perintah" name="isisurat" id="isisurat" required></textarea>

The code runs well if it is directly written in source code, but different if called from the database
as expected if I write the code in page directly:
If I save the code in database and call based on value of dropdown,it will show error:

A: Why don't you use normal load views based on a condition like in your index you would do this:
<a href="<?= site_url('your_controller/your_method/your_desired_view_one'); ?>">VIEW ONE
<a href="<?= site_url('your_controller/your_method/your_desired_view_two'); ?>">VIEW TWO
// and so on ...

Then in your controller:
public function your_method($your_view)
{
    $data['view'] = $this->load->view($your_view, null, TRUE);
    // Setting third param as true will return the view as a string
    $this->load->view('main_view', $data);
}

Now in your main view you have a variable called view of your requested view just echo it in your main content area.