text:
Q: Time difference issue in two different countries There are two clients with same window application. One is in India and other one is in Belgium. Sql server and web service application is hosted at Belgium. In sql I am storing UTC date time.
Now issue is a time difference for this two clients.  I want to show UTC time in history form that mean what is stored in Database I have to bind that data to gird. No any extra code because I suppose to bind UTC date-time. Event then I get time difference for this two client.

Blue header screen is of a Indian client and other one is of a Belgium client. In Belgium time is showing exactly as in Database but difference is for India. Am I missing anything in configuration or what?

A: Ditch System.DateTime and use Noda Time!
Getting Started with Noda Time
System.DateTime uses the system culture and time zone at unpredictable moments, where Noda Time works without any defaults.  Takes a bit of work to understand, but you'll never look back.
Use Noda time on the client, and store all the values in UTC in the database.  You may also wish to store the original time zone that the date time was entered in.

A: You have to convert both time zone in standard UTC and save it. Used dateadd() function to manipulate datetime. such as
declare @IST_date datetime
declare @BE_date datetime
declare @UTC_date datetime

--Indian standard time is (GMT + 5:30 hrs)
-- Belgium standard time is ( GMT + 1 hour)

select @UTC_date = DATEADD(hh,5.30, @IST_date)
select @UTC_date = DATEADD(hh,1, @BE_date)

A: why not simply convert the value at display ?
DateTime MyDate = Data["ChangedDate"];
DateTime MyDateUTC = MyDate.ToUniversalTime();

tadaaaaa


text:
Q: Developer Package missing in .NET SDK5 docker image I am trying to publish a c# project via docker image mcr.microsoft.com/dotnet/sdk:5.0 (https://hub.docker.com/_/microsoft-dotnet-sdk/).
In one of the *.csproj files is a definition like <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
I am getting the following error
/usr/share/dotnet/sdk/5.0.301/Microsoft.Common.CurrentVersion.targets(1216,5): error MSB3644:
The reference assemblies for .NETFramework,Version=v4.6.1 were not found.
To resolve this, install the Developer Pack (SDK/Targeting Pack) for this framework version or retarget your application.
You can download .NET Framework Developer Packs at https://aka.ms/msbuild/developerpacks

I have tried to install some dependencies from https://hub.docker.com/_/microsoft-dotnet-runtime-deps/ but this doesnt help me out.
I have searched hours to find a tutorial to install Developer Packs in linux distributions but found nothing.
Any ideas?

A: I think you are confusing Net Core with Net Framework.
To use Net Core:
In .csproj file Change <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion> to <TargetFrameworkVersion>net5.0</TargetFrameworkVersion> and fix the dependencies to work with Net Core
To use Net Framework: Change the docker image to mcr.microsoft.com/dotnet/framework/sdk:4.6

redpajama_set_name: RedPajamaStackExchange


text:
Q: Indentation based color coded background in sublime text I'm making heavy use of languages with syntactic whitespace (LiveScript, Emblem, Stylus, YAML)
Is there a way to configure the backgrounds of indentation?
I read that I could color these tiny indentation lines, but this isn't enough.
Here a mock-up of what I'm thinking about:

A: I'm looking for this too, and I was thinking that simply changing the background color of the indented area based on how many lines there are would be great. I'm not sure how to do that, but I did find a similar solution here:
https://github.com/buymeasoda/soda-theme/issues/153
That will get you lines that look like this:
Specifically, that page says:
Just add these settings to Monokai Soda.tmTheme file in settings dictionary, displayed in screenshot

<key>guide</key>
<string>#92003b</string>
<key>activeGuide</key>
<string>#7fb11b</string>
<key>stackGuide</key>
<string>#635f2d</string>

Another user at the above page says the following:
Just wanted to point out to others, that you'll need to enable "draw_active", in user prefs, like so:

"indent_guide_options":
[
    "draw_normal",
    "draw_active"
],

They also reference this page in the above link:
http://wesbos.com/sublime-text-indentation-guide-lines/
These options look like they will help somewhat, but they aren't an exact answer to your question. I would definitely like to see something like what you mention.


text:
Q: Problem with Event Handling via YUI When users click "search" input element, the search text inside the input will disappear and since I have several controls like that, I thought I could make the code reusable. Here is my code formerly done and working with jQuery but now in YUI I cannot make it work.
var subscriptionBoxTarget = "div.main div.main-content div.side-right div.subscription-box input";
var ssbNode = YAHOO.util.Selector.query(subscriptionBoxTarget);
var ssbValue = YAHOO.util.DOM.getAttribute(ssbNode,"value");
var subscriptionBox = new RemovableText(ssbNode,ssbValue,null);
subscriptionBox.bind();
////////////////////////////////

//target : the target of the element which dispatches the event
// defaultText : the default for input[type=text] elements
// callBack : is a function which is run after everthing is completed
function RemovableText(target,defaultText,callBack)
{
    var target = target; //private members
    var defaultText = defaultText;
    var callBack = callBack;

    //instance method
    this.bind = function()
    {
        mouseClick(target,defaultText);
        mouseOff(target,defaultText);
        if(callBack != null)
            callBack();
    }

    //private methods
    var mouseClick = function(eventTarget,defaultValue)
    {
        var _eventTarget = eventTarget;
        var _defaultValue = defaultValue;
        /*$(eventTarget).bind("click",function(){
            var currentValue = $(this).val();
            if(currentValue == defaultValue)
                $(this).val("");
        });*/
         YAHOO.util.Event.addListener(_eventTarget,"click",function(e){
            alert(e);
         });
    }

    var mouseOff = function(eventTarget,defaultValue)
    {
        var _eventTarget = eventTarget;
        var _defaultValue = defaultValue;
        /*$(eventTarget).bind("blur",function(){
            var currentValue = $(this).val();
            if(currentValue == "")
                $(this).val(_defaultValue);
        });*/
         YAHOO.util.Event.addListener(_eventTarget,"blur",function(e){
            alert(e);
         });
    }
}

A: You have a lot of unnecessary code here.
The input parameters passed to the RemovableText constructor are available by closure to all the methods defined inside.  You don't need to, and shouldn't redefine named params as vars.
function RemovableText(target, defaultText, callback) {
    this.bind = function () {
        YAHOO.util.Event.on(target, 'click', function (e) {
            /* You can reference target, defaultText, and callback in here as well */
        });

        YAHOO.util.Event.on(target, 'blur', function (e) { /* and here */ });

        if (callback) {
            callback();
        }
    };
}

The definition of an instance method from within the constructor seems dubious, as is the requirement that the values passed to the constructor must be kept private.  Just assign them to instance properties (this._target = target; etc) and add instance methods to the prototype.  If the functionality you're after is just this simple, then why bother with methods at all?
Using the click event does not support keyboard navigation.  You should use the focus event.
I'm not sure why you would have a callback passed at construction that fires immediately after attaching the event subscribers.


text:
Q: POST jQuery method working but not returning JSON response I'm trying to save JSON response as a variable from my POST request. The front-end script sends POST to API which then passes it to Trello to create a new board. The board is successfully created and I get the JSON response in from Trello to API. When I try to pass the very same response to the front-end it does not seem to work. I don't know much about javascript and front-end in general so I think I'm doing something wrong with the jQuery here but I'm not sure.
Here's the jQuery request:
function submit(boardname){
  $.ajax({
    type: 'POST',
    url: `/trello/${boardname}`,
    dataType: "json",
    success: function(data){
      console.log('Success', data)
      $('#response').html(data)
  }
});
}

$("#submit").click(function(){
  let name = document.getElementById("board-name-input").value
  submit(name)
});

And here is my API post function to trello (using Flask-restful):
class TrelloBoard(Resource):
    @check_token
    # create public board with default list
    def post(self, name):
        try:
            url = f'https://api.trello.com/1/boards/'
            query = {
                'key':'mykey',
                'token':'mytoken',
                'name':f'{name}',
                'defaultLists':'true',
                'prefs_permissionLevel':'public'
            }
            response = requests.post(url, params=query)
            print(f'Response: {response.json()}')
            return response.json()
        except:
            return {"message": "Unexpected error ocurred."}, 500

Edit, this is the response on the server:
127.0.0.1 - - [10/Dec/2020 00:02:10] "GET /trello HTTP/1.1" 200 -
Response: {'id': '5fd1658238fc9278a577c913', 'name': 'test', 'desc': '', 'descData': None, 'closed': False, 'idOrganization': '5fcbfac3eb5f7a81b67c3570', 'idEnterprise': None, 'pinned': False, 'url': 'https://trello.com/b/bPvx3oGp/test', 'shortUrl':
'https://trello.com/b/bPvx3oGp', 'prefs': {'permissionLevel': 'public', 'hideVotes': False, 'voting': 'disabled', 'comments': 'members', 'invitations': 'members', 'selfJoin': True, 'cardCovers': True, 'isTemplate': False, 'cardAging': 'regular', 'calendarFeedEnabled': False, 'background': 'blue', 'backgroundImage': None, 'backgroundImageScaled': None, 'backgroundTile': False, 'backgroundBrightness': 'dark', 'backgroundColor': '#0079BF', 'backgroundBottomColor': '#0079BF', 'backgroundTopColor': '#0079BF', 'canBePublic': True, 'canBeEnterprise': True, 'canBeOrg': True, 'canBePrivate': True, 'canInvite': True}, 'labelNames': {'green': '', 'yellow': '', 'orange': '', 'red': '', 'purple': '', 'blue': '', 'sky': '', 'lime': '', 'pink': '', 'black': ''}, 'limits': {}}

I would like to save this data in a variable so I can display a link to the board when it's created like this


text:
Q: how show QRCode info inside webpage and fill some text input after scan I have created some QRCode with these info such as address,tell,id,website,name . I want scan QRCode with scanner then these info fill my text input like :
 <input name='tell' value='' />
 <input name='address' value='' />
 <input name='id' value='' />
 <input name='website' value='' />
 <input name='name' value='' />

and then i can submit form .
and some time i want show QRCode info in content of page . How can i scan and use QRCode info in website ?

A: Most QR scanners emulate keyboards so you can listen for keypresses and process the results as they come in.
This example uses jQuery and was written to handle RFID codes (which also have readers which emulate keyboards).
You'll need to adjust it to handle the different structure of the data in your QR code. e.g. this treats Enter as "End of data", but your QR code might have structured it on multiple lines so you may have to use some other method to identify the End of Data.
Then change the send method to do what you want with the data. Here I'm using Socket.IO to send the results to a server. You can change that to split the data up according to your data format and then use DOM manipulation to populate the text inputs.
  var keybuffer = [];

  function press(event) {
    if (event.which === 13) {
      return send();
    }
    var number = event.which - 48;
    if (number < 0 || number > 9) {
      return;
    }
    keybuffer.push(number);
  }

  $(document).on("keypress", press);

  function send() {
    socket.emit('scan', keybuffer.join(""));
    keybuffer.length = 0;
  }


text:
Q: A way to draw a lab apparatus Are there any packages that would make a simple lab apparatus easy to draw?
e.g. a spectrometer connected to a computer and has a wire before a light emitting tube, the wire also being connected to said spectrometer.

A: The following are PSTricks packages for drawing lab apparatus:

*

*pst-labo to draw lab apparatus related to chemistry.

*pst-pulley to draw pulley.

*Various Physics diagrams and laboratory equipments that have not been bundled into packages. The site was very very cool! Unfortunately, its contents are written in French so we might have difficulties to understand even with the Google translator.
Particle Deflector:

Gear:


text:
Q: log cloud foundry syslog to s3 using the syslog protocol I want to send my syslog entries to an S3 bucket.  Security restrictions have meant that this is the only ways that I can do this.
With cloud foundry, you can create a user provided server where I specify a syslog url:
cf create-user-provided-service DRAIN-NAME -l SYSLOG-URL
Can I configure an s3 bucket to receive syslog messages using the syslog protocol?


text:
Q: STM32F7x6 - Setting readout protection from code without power cycle I am working on a custom battery powered board with a STM32F746 on which I would like to set the RDP option byte to level 1 from code. Basically, while booting the software checks if the option bytes are set correctly and if not it will reprogram the option bytes to the correct values. This means that any unit shipped to customers is ensured to have the read-out protection set and we don't have to worry about the assembly house forgetting to set it and thus exposing the firmware.
To do this, I follow the procedure in the reference manual:

*

*unlock the option bytes by writing the correct keys to FLASH_OPTKEYR and clearing OPTLOCK

*set the desired option values in FLASH_OPTCR

*set OPTSTRT in FLASH_OPTCR
This works fine for all option bytes except RDP, which locks the MCU after setting OPTSTRT. As far as I can tell, this is intended behaviour, and requires a reset of the device through a power cycle after which the option byte is set correctly. But since our board is battery powered (soldered connection) this is a bit cumbersome and so my first question is if there exists another way of doing this.
A bit of googling revealed that some STMs can also activate the altered option bytes by transitioning from the STBY state, here is a specific example by ST: https://www.youtube.com/watch?v=f7vs0NwZPFo&ab_channel=STMicroelectronics.
So far I have no luck with this method: when returning from STBY the RDP is not set. The example deals with an STM32L4, does anyone know if this method is supported on the F7?


text:
Q: Syntax error with "gdalwarp" I want to project a raster from Sinusoidal to UTM. I used the following command in Python:
gdalwarp -overwrite -t_srs EPSG:32643 -of GTiff D:/IMAGE.tif D:/IMAGE2.tif

I'm getting the following error:
SyntaxError: invalid syntax

Anyone who can help?

A: In Python you should use os module and an adequate string combination, for gdalwarp parameters, to get a good performance. For example, I use next adapted code in my QGIS plugin and it works perfectly. In this case, it is employed for transforming UTM 12 N projection (EPSG:32612) in my raster to UTM Utah North projection (EPSG: 32142).
import os

layer = iface.activeLayer()

provider = layer.dataProvider()

source_path = " -of GTiff " + provider.dataSourceUri()
target_path = "/home/zeito/pyqgis_data/utah_dem_UtmNorth2.tif"

CRS = layer.crs()
source_epsg = CRS.postgisSrid()
new_espg = 32142
target_epsg = " -t_srs EPSG:" + str(new_espg)

cmd = "gdalwarp -overwrite -s_srs EPSG:" + \
                        str(source_epsg) + \
                        target_epsg + \
                        source_path + \
                        " " + \
                        target_path

print cmd

os.system(cmd)

To test the adequate command execution, comment last line:
os.system(cmd)

and observe and correct gdalwarp syntax until you can get expected result.
Editing Note:
In your case, I think that next code could work:
import os

source_path = " -of GTiff D:/IMAGE.tif "
target_path = "D:/IMAGE2.tif "

source_epsg = 6974  #Sinusoidal Projection
new_espg = 32643
target_epsg = " -t_srs EPSG:" + str(new_espg)

cmd = "gdalwarp -overwrite -s_srs EPSG:" + \
                        str(source_epsg) + \
                        target_epsg + \
                        source_path + \
                        " " + \
                        target_path

print cmd

os.system(cmd)


text:
Q: Kubernetes : use node labels in yaml deployment I have a quick question regarding kubernetes yaml files :
can I reference a node label value in a pvc, using a node label as variable?
Something like :
  volumes:
    - name: data-storage
      persistentVolumeClaim:
        claimName: main-dev-pvc-${node.failure-domain.beta.kubernetes.io/zone}

Is it possible?

A: Is the idea to force the use of PV created in a specific zone? StorageClass can help with that.
Custom StorageClass:
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: ssd-usc1a
provisioner: kubernetes.io/gce-pd
parameters:
  type: pd-ssd
  zones: us-central1-a

PVC that refers to the custom storage class:
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: main-dev-pvc-ssd-usc1a
  namespace: dev-project
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
  storageClassName: ssd-usc1a

Assuming the same namespace as for the PVC:
  volumes:
    - name: data-storage
      persistentVolumeClaim:
        claimName: main-dev-pvc-ssd-usc1a

Kubernetes will try to schedule the pod on a node in the same zone where the PV is (us-central1-a in the example above). Quote from the docs: "...The scheduler (via the VolumeZonePredicate predicate) will also ensure that pods that claim a given volume are only placed into the same zone as that volume, as volumes cannot be attached across zones". Therefore, the scheduling will fail if there isn't a such suitable node.

A: You cannot use variables in Kubernetes yaml files by default.
But there are some tools which have such functionality, helm, for example. Or you can use automation tool like Ansible for creating Kubernetes resources with some parameters according to some rules.


text:
Q: MySQL 5.5 vs 5.6,5.7 above same database same query but different output, limit have duplicated ID I am using Running same source code and same database for WordPress, only the mysql version is different. It make my pagination post have duplication.
Here is what I found out. Any idea how to solve it in higher version?
This is for Page 2, and Page 3 query output. Left-Hand side is MySql 5.5, Right-Hand side is MySql 5.6.  up_posts.ID is unique.
SQL Statement:-
SELECT SQL_CALC_FOUND_ROWS up_posts.ID FROM up_posts  WHERE 1=1  AND up_posts.post_type = 'post' AND (up_posts.post_status = 'publish' OR up_posts.post_status = 'closed' OR up_posts.post_status = 'private' OR up_posts.post_status = 'hidden')  ORDER BY up_posts.post_date DESC LIMIT 10, 10

SELECT SQL_CALC_FOUND_ROWS up_posts.ID FROM up_posts  WHERE 1=1  AND up_posts.post_type = 'post' AND (up_posts.post_status = 'publish' OR up_posts.post_status = 'closed' OR up_posts.post_status = 'private' OR up_posts.post_status = 'hidden')  ORDER BY up_posts.post_date DESC LIMIT 20, 10

Page 2:- different is LIMIT 10,10

Page 3:- different is LIMIT 20,10

Seem like MySQL 5.5 will sort by the ID, but 5.6 above does not have this ability.

A: Added ORDER BY up_posts.post_date DESC, up_posts.ID DESC no more duplicate result. Seem like we need to manually add this to avoid an unnecessary problem.
FYI. It applied to MySQL 5.6 and 5.7.
See 8.2.1.16 LIMIT Query Optimization
If you want to order by primary key, you have to say so explicitly.


text:
Q: operation on post++ and --pre operator I am wondering with post and pre increment and decrement operation.
what I know in Java precedence of post operator is high and associativity is left-to-right.while associativity of pre operator is right-to-left

Oracle Java Tutorial
but my code showing me undesired result-
public class Bunnies {
    static int count = 3;
    public static void main(String[] args) {

        System.out.println(--count*count++*count++);//out put is 12 expected 48
        //associativity of post is higher so should be evaluated like this-

        //--count*3**count++  count is 4 now
        //--count*3*4         count is 5 now
        //4*3*4=48

        count = 3;
        System.out.println(--count*++count*++count); //out put is 24 expected 120
        //associativity of pre  is right to left so should be evaluated like this-

        //--count*++count*4      count is 4 now
        //--count*5*4            count is 5 now
        //4*5*4=120

        count = 3;
        System.out.println(-- count*count++);// out put is 4 expected 9

        //--count*3      count is 4 now
        //3*3=9
         }
}

A:
Order of evaluation of subexpressions is independent of both associativity and precedence.

The subexpression of the multiplication are evaluated from left to right, so when doing --count*count++*count++, you evaluate --count then count++ and finally count++.
And as the pre operator is evaluated first, --count will be decremented before its evaluation. In the same way, as the post operator is evaluated lately, count++ will be incremented after its evaluation.
The precedence only help the compiler to create a correct abstract syntactic tree.
For example, when doing ++count*2, the compiler use the precedence to know the expression is (++count)*2 and not ++(count*2). In the same way, when doing ++count*count--, the expression is (++count)*(count--) and not (++(count * count))-- or whatever. But then, during the evaluation of the multiplication ++count is evaluated before count--.
Hope this help you :)
I just found a great answer about expression evaluation in C# and Java here, enjoy :)

A: System.out.println(--count*count++*count++);

= 2 * 2 * 3 = 12
count = 3;
System.out.println(--count*++count*++count)

= 2*3*4 = 24
count = 3;
System.out.println(-- count*count++);

= 2 * 2 = 4
Pre increment/decrement
++/-- X first increments/decrements then does the operation.
Post increment/decrement
X ++/-- first the operation is done, then increment / decrement.

A: I take the first one.
System.out.println(--count*count++*count++);//out put is 12 expected 48
                    2     *    2  * 3 = 12
                    pre   * post  * post

A: count = 3:
Example 1:
--count*count++*count++ equals (--count)*(count++)*(count++)
(--count) = 2
(count++) = 2 (you increment it AFTER you do something with it)
(count++) = 3 ... count was incremented from before
2*2*3 = 12

Example 2:
--count*++count*++count equals (--count)*(++count)*(++count)
--count = 2
++count = 3
2 * 3 * 3 = 24

Example 3:
(--count)*(count++)
--count = 2
2 * 2 (the count++ gets changed afterwards)

Keep in mind that you have to watch the multiplicaton operator


text:
Q: Pandas: how to collapse a categorical column returning aggregate values I'm trying to do something slightly counter-intuitive. The issue, which should be clear in the reproducible example below, is that I'm trying to collapse a column of categorical values whilst returning aggregate values for the other columns.
raw_data = {
        'id': ['4', '5', '6', '7'],
        'score1': ['1', '2', '4', '0'],
        'score2': ['3', '4', '11', '0'],
        'time1': ['7.3', '2.4', '0.0', '0.3'],
        'time2': ['4.3', '5.4', '1.0', '0.0']}
df = pd.DataFrame(raw_data, columns = ['id', 'score1', 'score2', 'time1', 'time2'])
df

    id  score1  score2   time1  time2
0   4       1       3    7.3    4.3
1   5       2       4    2.4    5.4
2   6       4       11   0.0    1.0
3   7       0       0    0.3    0.0

From this dataframe I'm trying to return a one line pandas HTML table showing:

*

*The sum of score1

*The sum of score2

*The mean of time1

*The median of time2
Ideally the id column would show something like all. This value can of course easily be changed after the event.
The one line HTML table would look like this:
id    score1  score2   time1  time2
All   7       18       2.5    2.7

Is this even possible?

A: Can do something like:
df = df.astype('float64')
tmp = pd.DataFrame([{"score1": df.score1.sum(), "score2":df.score2.sum(), "time1":df.time1.mean(), "time2":df.time2.median()}])
out = tmp.to_html(index=False)

which gives the table like so

     score1	     score2	      time1	     time2

      7	     18	      2.5	      2.65


text:
Q: Find max value from alphanumeric string on the basis of its numeric value in db2 database Actually I have data in my column like this-- abc1,abc2,..,abc50,pqr1,pqr2,...,pqr120,xyz1,xyz2,...,xyz200.Now i want to get max value for having prefix xyz.So for this purpose i used this query --`
select MAX(fieldName) from table where fieldName like 'xyz%'

This query was returning result as xyz99 as max but Expected result should be xyz200 as max..Now i want to know how to use 'like' query in MAX function to get desired output.OR is there any way to find out max value on the basis of its numeric value.

A: select * from table
where substring(fieldName,3,length(fieldName)-3) =
(select max(substring(fieldName,3,length(fieldName)-3))
from table)

A: Try this
SELECT max(CAST(substring(fieldName,4) AS UNSIGNED)) AS maxVal
FROM `table`
WHERE fieldName LIKE 'xyz%'

A: Use SUBSTR() to separate the xxxnnn values into a character part and an integer part. Cast the integer part of the string to an integer. Order by these two parts separately - descending. Use FETCH FIRST to pick the max value!
select fieldName
from table
where fieldName like 'xyz%'
order by substr(fieldName,1,3) desc,
         cast(substr(fieldName,4) as integer) desc
fetch first 1 row only

A: Try this -
Select concat('XYZ', max(regexp_replace(fieldName, '[^0-9]', '', 'g') ::int)) from table;

If you want to extract only integer value from alphanumeric field, you can simply use -
Select regexp_replace(fieldName, '[^0-9]', '', 'g') ::int) from table;


text:
Q: Create JSON Gist (conflict) I want to create a Gist containing a JSON (valid one, I checked) with curl command as described here.
I tried first this script :
configText=$(cat jsonFile.json)

generate_post_data()
{
cat <<EOF
{
  "description": "the description for this gist",
  "public": true,
  "files": {
    "file1.txt": {
      "content": $configText
    }
  }
}
EOF
}

curlBody="$(generate_post_data)"

curlResponse=$(curl -H "Content-Type: application/json" -X POST -d '$curlBody' https://api.github.com/gists)

Which gave me the error Problems parsing JSON, so I tried passing the file directly in the command:
curl -H "Content-Type:application/json" -data-binary @jsonFile.json https://api.github.com/gists

But I'm getting the same error. I know that this must be a conflict between the JSON body of the POST request and the JSON of my file (quotes, brackets...).
How can I send a clean JSON file to Gist ?

A: For the issues in your script :

*

*in your curl request, you use single quotes around your bash variable in POST -d '$curlBody', use double quote to expand it : POST -d "$curlBody"

*content is a text field : "content": $configText to "content": "$configText"

*configText can have new lines and unescaped double quotes " which break your content JSON data. You could use the following to escape quotes and remove new lines :
configText=$(cat test.json | sed 's/\"/\\\"/g' | tr -d '\n')

The following example build your gist request with  jq JSON parser/builder, not that this example will not preserve new lines in your input :
#!/bin/bash

ACCESS_TOKEN="YOUR_ACCESSS_TOKEN"

description="the description for this gist"
filename="file1.txt"

curlBody=$(jq --arg desc "$description" --arg filename "$filename"  '.|
{ "description": $desc,
  "public": true,
  "files": {
      ($filename) : {
          "content": tostring
       }
   }
}' jsonFile.json)

curl -v -H "Content-Type: application/json" \
        -H "Authorization: Token $ACCESS_TOKEN" \
        -X POST -d "$curlBody" https://api.github.com/gists

The following will preserve new lines in your json input by replacing new lines with \\n :
#!/bin/bash

ACCESS_TOKEN="YOUR_ACCESSS_TOKEN"

description="the description for this gist. There are also some quotes 'here' and \"here\" in that description"
public="true"
filename="file1.txt"

desc=$(echo "$description" | sed 's/"/\\"/g' | sed ':a;N;$!ba;s/\n/\\n/g')
json=$(cat test.json | sed 's/"/\\"/g' | sed ':a;N;$!ba;s/\n/\\n/g')

curl -v -H "Content-Type: text/json; charset=utf-8" \
        -H "Authorization: Token $ACCESS_TOKEN" \
        -X POST https://api.github.com/gists -d @- << EOF
{
  "description": "$desc",
  "public": "$public",
  "files": {
      "$filename" : {
          "content": "$json"
       }
   }
}
EOF

Note that your access token must have the gist scope


text:
Q: Refinerycms did not generate image field I was following RefineryCMS getting started tutorial about generatin an extension.
I put following command in my project directory:
rails generate refinery:engine event title:string date:datetime photo:image blurb:text

And it generated it almost properly. The problem is that it handled photo as a regular input string. According to the guide it should be image picker field

A: Maybe this works for you: Why is there no image after creating a record in Refinery CMS?
I've found it while searching for the solution to the same problem, but have not tried it.


text:
Q: How to define function that uses class type as a parameter in Swift? I simply try to do the following:
func popTo(classType: AnyClass, from context: UINavigationController?) {
    let controller = context?.viewControllers.first { $0 is classType }
    context?.popToViewController(controller, animated: true)
}

I need to use it like this:
popTo(SettingsViewController.self, from: navigationController)

A: As far as the compiler is concerned, classType isn't a type like String or Int. It's just the name of a parameter (which stores a type). But the is operator expects a type (that can be resolved at compile time) on its RHS.
We need a type that is known at compile time. We can pass such a type parameter with generics:
func popTo<T>(classType: T.Type, from context: UINavigationController?) {
    if let controller = context?.viewControllers.first(where: { $0 is T }) {
        context?.popToViewController(controller, animated: true)
    }
}

You can also add the constraint T: AnyObject to more closely reflect the AnyClass (= AnyObject.Type) in your original code, but you don't particularly have to.

A: func popTo<T: UIViewController>(classType: T.Type, from context: UINavigationController?) {
    let controller = context?.viewControllers.first { $0 is T }
    context?.popToViewController(controller!, animated: true)
}


text:
Q: write (add) multiple array in firestore I try to add multiple array in firestore using struct codable in swiftui but when I add, it updates the same array added but i want add more array in my list...
as you can see in the image, every time I add a text, it updates my index "0" but I want to add multiple indexes, for example O, 1, 2... in my array" tags"
ViewModel
class DataManager: ObservableObject {

    @Published var books = Book(tags: [Tag(title: "", color: "")])

    func addBookNew(nom: String, prenom: String){
        //guard let userID = Auth.auth().currentUser?.uid else {return}
        let db = Firestore.firestore()
        let collectionRef = db.collection("Users").document("TEST")

          do {
              let data = Book(tags: [Tag(title: nom, color: prenom)])
              try collectionRef.setData(from: data)

          }
          catch {
            print(error)
          }

    }

STRUCT BOOK
import Foundation
import FirebaseFirestore
import FirebaseFirestoreSwift

struct Book: Codable {

    @DocumentID var id: String?
    let tags: [Tag]

}

STRUCT TAG
import Foundation
import FirebaseFirestoreSwift

struct Tag: Codable, Hashable {
  let title: String
  let color: String
}

LIST VIEW
import SwiftUI
import Firebase

struct ListView: View {

    @StateObject var dataManager = DataManager()
    @State private var showPopUp = false
    @EnvironmentObject var viewModel: AppViewModel
    var books: [Book]

    @State var nomTF = ""
    @State var prenomTF = ""
    @State var dismiss = false

    var body: some View {

        NavigationView{
            VStack{
                TextField("nom", text: $nomTF )
                TextField("prenom", text: $prenomTF)
                Button("save") {
                    dataManager.addBookNew(nom: nomTF, prenom: prenomTF)
                }
                List{
                    ForEach(dataManager.books.tags, id: \.self) { book in
                        HStack{
                            Text("T: \(book.title)")
                            Text("C: \(book.color)")
                        }
                    }
                }
            }.onAppear(){
                dataManager.fetchtest()
            }

A: The problem is here:
let data = Book(tags: [Tag(title: nom, color: prenom)])
try collectionRef.setData(from: data)

This code tells Firestore to set the tags field to the array that you specify in the call.
If you want to add unique items to existing array, you can use FieldValue.arrayUnion([...]).
let data = Book(tags: FieldValue.arrayUnion([Tag(title: nom, color: prenom)]))
try collectionRef.setData(from: data)

Note that this will only add the item if it is not already in the array. If you want to allow for duplicate items, you will have to read the array from the document first, then updates in your application code, and finally write the entire array back to the database.

Update: it seems your Book class can only accept Tag in its tags field, so you can't specify an FieldValue.arrayUnion there. It's probably easiest to then simply perform the union in the database call:
try collectionRef.updateData([
  "tags": FieldValue.arrayUnion([Tag(title: nom, color: prenom)])
])

So instead of writing the entire book here, we're updating a single field in the document, and in there perform the array union.
washingtonRef.updateData([
    "regions": FieldValue.arrayUnion(["greater_virginia"])
])


text:
Q: Using Vagrant, how can I access an apache virtual host from the host OS's web browser After installing Vagrant I've installed the Apache web server.
I've configured it to run both the default host and a virtual host. I've confirmed that the vhost is running.
From the host OS, using a browser I can access to default apache vhost by navigating to http://localhost:4567.
Given that apache vhost is called vhost2, how can I access the site from a browser on the host OS?

A: You can add a line in your host hosts file and have a redirect from localhost to your virtual host.
So if you have a virtualhost configured as something like:
NameVirtualHost *:80

<VirtualHost *:80>
   ServerName vhost2.local
   DocumentRoot "/path/to/virtual_hosts/file"
   <Directory />
      Options Indexes FollowSymLinks
      AllowOverride All
   </Directory>
</VirtualHost>

You can add the following line in your hosts file:
127.0.0.1    vhost2.local

Then you can access your virtual host at http://vhost2.local:4567/


text:
Q: How can I filter between two models? I have two models. One is a Partner. Another is Contact. Partner is the companys information. Contact is a contact for that company. How can I get a list of contacts from a company by comparing the name of the company to the foreign key partner which is who the contact belongs to.
I have tried using querys but the result was not what i expected.
class Partner(TimeStampedModel, StatusModel):

    name = models.CharField(blank=False,
    help_text="Name of the role or function",
    max_length=64,
    verbose_name="Partner Type", )

    parent = models.ForeignKey(
    'self',
    blank=True,
    help_text="Parent Company name (if necessary)",
    null=True,
    on_delete=models.CASCADE,
    max_length=200
    )

class Contact(ContactModel, TimeStampedModel):
        partner = models.ForeignKey(
        Partner,
        blank=True,
        null=True,
        on_delete=models.SET_NULL,
        related_name="contacts",)

Urls.py
from .views import (
    ContactsListView,
    ContactsDetailView,
    ContactsCreateView,
    ContactsUpdateView,
    ContactsDeleteView,
)
from . import views

app_name = 'contacts'

urlpatterns = [
    path('', ContactsListView.as_view(), name='list'),
    path('<int:pk>/', ContactsDetailView.as_view(), name='detail'),
    path('new/', ContactsCreateView.as_view(), name='create'),
    path('<int:pk>/update/', ContactsUpdateView.as_view(), name='update'),
     path('<int:pk>/delete', ContactsDeleteView.as_view(), name='delete'),
    ]

What i want is a list of contacts belonging to that company.
Lets say the company name is Shell.
on The contact i would fill out the partner being shell. and i want to query all the contacts shell has.
Edit: meant contacts not partner.

A: You can get the related contacts for partner instance by using the following line:
related_contacts = partner_instance.contact_set

A: You can get a queryset that contains all the related Contact objects to a specific Partner object like this:
related_contacts = Contact.objects.filter(partner="pk of Partner model you want all the contacts of")


text:
Q: Got "request failed" while trying to post on facebook's wall I'm using facebook connect with SSO to sign in/up users to my app, and want to ask user to post on wall after each login.
But, at the requestListener's onComplete (Post on wall dialog was shown, and user touched on Share), I'm getting a false response. Didn't find out what it means in the FB SDK docs, but anything was posted on my Wall. Response was supposed to return a JSON formated string, so when trying to execute "message = json.getString("message");", I get a FacebookError witch just prints "request failed"...
logcat:
07-27 12:58:09.170: W/FacebookConnect(26086): Activity Started
07-27 12:58:12.300: W/FacebookConnect(26086): User authorized
07-27 12:58:12.300: E/FacebookConnect(26086): onComplete called at facebook.authorize
07-27 12:58:12.300: E/FacebookConnect(26086): Access Token: AAAC1sJLmgzkBAD0M40SQLgluPU...
07-27 12:58:12.860: D/webviewglue(26086): nativeDestroy view: 0x223888
07-27 12:58:13.420: I/SqliteDatabaseCpp(26086): sqlite returned: error code = 14, msg = cannot open file at line 27701 of [8609a15dfa], db=/data/data/androidhive.dashboard/databases/webview.db
07-27 12:58:13.420: I/SqliteDatabaseCpp(26086): sqlite returned: error code = 14, msg = os_unix.c: open() at line 27701 - "" errno=2 path=/CachedGeoposition.db, db=/data/data/androidhive.dashboard/databases/webview.db
07-27 12:58:14.670: D/SampleRequestListener(26086): Response: {"id":"1123123","name"...
07-27 12:58:14.680: E/FacebookConnect(26086): JSON {"work":[{"position"...
07-27 12:58:17.150: E/SampleDialogListener(26086): Dialog Success! post_id=1003157...
07-27 12:58:17.720: E/WallPostRequestListener(26086): Got response: false
07-27 12:58:17.720: E/WallPostRequestListener(26086): Facebook Error: request failed

My code (Error occurs in class WallPostRequestListener):
public class FacebookConnectActivity extends Activity {
private static final String TAG_JSON = "json";
static Facebook facebook = new Facebook("11111111111111");
AsyncFacebookRunner mAsyncRunner;
private SharedPreferences mPrefs;
JSONObject json;
Context ctx = this;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.resgatar_produto_layout);
    Log.w("FacebookConnect", "Activity Started");

    mPrefs = getPreferences(MODE_PRIVATE);
    String access_token = mPrefs.getString("access_token", null);
    long expires = mPrefs.getLong("access_expires", 0);
    if(access_token != null) {
        facebook.setAccessToken(access_token);

    }
    if(expires != 0) {
        facebook.setAccessExpires(expires);
    }

    if(!facebook.isSessionValid()) {

    facebook.authorize(this, new String[] {"email", "user_photos", "user_birthday", "user_hometown", "user_relationships","user_location", "user_work_history", "publish_actions"}, new DialogListener() {
        @Override
        public void onComplete(Bundle values) {
            Log.w("FacebookConnect", "User authorized");
            Log.e("FacebookConnect", "onComplete called at facebook.authorize");
            Log.e("FacebookConnect", "Access Token: "+facebook.getAccessToken().toString());
            mAsyncRunner = new AsyncFacebookRunner(facebook);
            mAsyncRunner.request("me", new SampleRequestListener());
            Bundle params = new Bundle();
            params.putString("link", "www.qranio.com");
            facebook.dialog(ctx, "feed", params, new SampleDialogListener());
        }

        @Override
        public void onFacebookError(FacebookError error) {
            Log.w("FacebookConnect", "Error authorizing: "+error.toString());
        }

        @Override
        public void onError(DialogError e) {}

        @Override
        public void onCancel() {}
    });

    }

}

public static  void logoutFB(){
    if(facebook.isSessionValid()){
        facebook.setAccessToken(null);
    }
}

public void startDataProcess(){

    Intent a = new Intent(FacebookConnectActivity.this, FacebookDataProcess.class);
    a.putExtra(TAG_JSON, json.toString());
    startActivity(a);
    finish();
}

public class SampleDialogListener extends BaseDialogListener {

    public void onComplete(Bundle values) {
        final String postId = values.getString("post_id");
        if (postId != null) {
            Log.e("SampleDialogListener", "Dialog Success! post_id=" + postId);
            mAsyncRunner.request(postId, new WallPostRequestListener());
        } else {
            Log.e("SampleDialogListener", "No wall post made"); //Usuario clicou em Cancelar
            startDataProcess();
        }
    }

    public void onCancel(){ //Usuario clicou no X do dialog
        Log.w("FacebookConnect", "Post to Wall Canceled");
        startDataProcess();
    }
}

public class WallPostRequestListener extends BaseRequestListener {

    public void onComplete(final String response, final Object state) {

        Log.e("WallPostRequestListener", "Got response: " + response);
        String message = "<empty>";
        try {
            JSONObject json = Util.parseJson(response);
            message = json.getString("message");
        } catch (JSONException e) {
            Log.e("WallPostRequestListener", "JSON Error in response");
        } catch (FacebookError e) {
            Log.e("WallPostRequestListener", "Facebook Error: " + e.getMessage());
            //Toast.makeText(ctx, "Erro ao postar no Facebook.", Toast.LENGTH_LONG).show();
        }
        //startDataProcess();
    }
}

public class SampleRequestListener extends BaseRequestListener {

    public void onComplete(final String response, final Object state) {
        try {

            // process the response here: executed in background thread
            Log.d("SampleRequestListener", "Response: " + response.toString());
            json = Util.parseJson(response);
            Log.e("FacebookConnect", "JSON " + json.toString());

            //startDataProcess();

            // then post the processed result back to the UI thread
            // if we do not do this, an runtime exception will be generated
            // e.g. "CalledFromWrongThreadException: Only the original
            // thread that created a view hierarchy can touch its views."

        } catch (JSONException e) {
            Log.w("Facebook-Example", "JSON Error in response");
        } catch (FacebookError e) {
            Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
        }

    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    facebook.authorizeCallback(requestCode, resultCode, data);
    try{
        mAsyncRunner = new AsyncFacebookRunner(facebook);
        mAsyncRunner.request("me", new SampleRequestListener());
        Bundle params = new Bundle();
        params.putString("link", "www.qranio.com");
        //params.putString("display", "touch");
        facebook.dialog(ctx, "feed", params, new SampleDialogListener());
        Log.e("FacebookConnect", "Authentication authorizeCallback called (onActivityResult)");
        Log.e("FacebookConnect", "Access Token: "+facebook.getAccessToken().toString());
        //facebook.
        //if (facebook.isSessionValid()){

        //}else{
            //Log.e("FacebookConnect", "Invalid facebook session while trying to fetch user data");
        //}*/

    }catch(FacebookError fbe){
        Log.e("FacebookConnect", "onActivityResult FacebookError " + fbe.toString());
    }catch (Exception e){
        Log.e("FacebookConnect", "onActivityResult Exception " + e.toString());
    }

}

}


text:
Q: Palm Pre frameworks I have some measure of web development experience (not my main skill, but I am pretty good with the basics)
What I'm sorely lacking is knowledge of and experience with modern JS frameworks (Prototype, jQuery, YUI, whatnot). I'd like to play with them (all eventually but need to start with one).
Here's the problem: I'm very interested in trying out my skills on Palm Pre eventually. To the extent that the main criteria for choosing which JS framework to learn first for me is this:
Which mainstream modern JS framework is the most useful to learn if the main criteria is "knowing this will help me most to develop for Palm Pre"?
I'm assuming it will be one of the 3 I mentioned: jQuery/YUI/Prototype, unless I'm missing some major well known JS/wevdev framework? I intend to try all those 3 eventually so their relative merits outside of helping on PalmPre are not majorly important.
Thanks!

A: The framework that Palm provides in the SDK is called Mojo.
Mojo is built on top of Prototype, therefore you will automatically have access to Prototype when you work on the Pre, and you will have to make use of it for various system calls.
Therefore, you are probably going to get the most benefit from learning Prototype.
That said, it is possible to add other js libraries like jQuery if you prefer to use those for your Pre apps.
Check out the webOSdev API Reference for more information about the Mojo Framework.


text:
Q: How to center an Anchor tag element both vertically and horizontally without any div? So how to vertically and horizontally center an anchor tag link? No div or any parent elements used. i just want to center it as in the following image.
This is how i want it to look like.
And this is my code:

BornExplorer

A: If the width and height of the anchor tag box are fixed, it's pretty trivial. Assuming you want to position the tag relative to the viewport:

html { background: black; color: white; }
.centered {
  /* size */
  width: 10em;
  height: 1em;

  /* positioning */
  margin-left: -5em; /* -(width/2) */
  margin-top: -0.5em; /* -(height/2) */
  position: fixed;    /* relative to viewport */
  left: 50%;
  top: 50%;

  /* just aesthetic styling */
  text-align: center;
  color: white;
  font-weight: bold;
  background: rgba(255,255,255,0.3);
}
Centered

A: If you are going for a full page setup with a a single link you could setup the centering using line-height:100vh which means that the line height is 100% of the page height.

html,body{width:100%;height:100%;margin:0;}
body{
  background:#000;
  line-height:100vh;
}
.link{
  font-size:40px;
  line-height:1;
  display:inline-block;
}
BornExplorer


text:
Q: GatsbyJS file is null - setting relativePath doesn't work I'm attempting to pull an image: /src/images/es.png
And to display it on a gatsby page. Here's the page code:
import React from "react"
import {
  Header,
  Image,
} from 'semantic-ui-react';
import { graphql } from 'gatsby'
import Img from 'gatsby-image'

import Layout from '@/components/layout'
import SEO from '@/components/seo'

export const query = graphql`
  query {
    file(
      relativePath: { eq: "images/es.png" },
      sourceInstanceName: {
        eq: "images"
      }
    ) {
      childImageSharp {
        # Specify the image processing specifications right in the query.
        # Makes it trivial to update as your page's design changes.
        fixed(width: 125, height: 125) {
          ...GatsbyImageSharpFixed
        }
      }
    }
  }
`

export default ({ data }) => (
  <Layout>
    <SEO title="Earthshaker" />

        Earthshaker

      { JSON.stringify(data) }
      {/*  */}

  </Layout>
)

Here's the config code:
plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: path.join(__dirname, `src`, `images`),
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,

Here's my file structure:
- src
 - images
  - es.png
 - components
  - heroes
   - earthshaker <---- (this is the page code HERE)

I'm expecting the image to get pulled out but I always get file: null. What am I doing wrong?

A: Assuming that your query works, I'd change your filesystem paths to:
{
  resolve: `gatsby-source-filesystem`,
  options: {
    name: `images`,
    path: `${__dirname}/src/images/`,
  },
},

In addition, I would check the query to see if it gathers the expected result in the GraphQL playground (localhost:8000/___graphql). The rest of the code looks fine.


text:
Q: What does it mean in java "your data sharing between backend and frontend must be in JSON via REST APIs" I came across a question which says that data sharing between backend and frontend must be done in JSON via Rest Api. Now, I am confused that what should I do?
Should, I make a Java Project with Jax-RS which will provide a set of Api and another Dynamic Web Project which will use the previous project to access the database?
I don't know if I can do both things in the same project.

A: You can have your REST APIs and also data accessing logic in one project. So your front end application will invoke the REST APIs which are nothing but methods and from those methods you can access the DAO classes. You can have a service layer through which you access the DAO classes instead of directly invoking the same.


text:
Q: Failed to Resolve third party libraries after install studio2.3 I have format my system two days back, and installed android studio 2.3, also i have defined proxy in File--> Settings by providing host,port,username and password. But still am facing gradle sync error : Failed to resolve libraries.
Please help me out to resolve this.
Is it necessary to use jdk 1.8 to achieve this?

A: Could be possible that this proxy configuration is only for IJ (AS) itself and not working for Gradle. Try configuring the proxy in ~/.gradle/gradle.properties like described in https://docs.gradle.org/current/userguide/userguide_single.html#sec:accessing_the_web_via_a_proxy.


text:
Q: Protractor E2E : Enable screen capturing and "use fake ui" not working together in chrome I am trying to test an app which uses both camera and screen sharing as part of its functionalities.
The problem I am having right now in chrome is that chrome will not let me test both of these features together.
The flags I am currently using are :
--enable-usermedia-screen-capturing  (to allow screen sharing)
--use-fake-ui-for-media-stream (to tell chrome to use a fake camera so I can test camera streaming)
How can I test both these things in a place where I have no access to a physical camera? (web server somewhere in aws).


text:
Q: Aggregate a data frame in R by equally spaced time intervals I want to aggregate the data by time and create equally spaced time intervals:
date<- c(as.POSIXct("2011-08-08 21:00:00"), as.POSIXct("2011-08-08 21:26:00"))
value<-c(1,2)
dt<-data.frame(date, value)

DT<-aggregate(cbind(dt$value),list(cut(dt$date, breaks="10 min")),sum)

dt:
2011-08-08 21:00:00 1
2011-08-08 21:26:00 2

DT:
2011-08-08 21:00:00 1
2011-08-08 21:20:00 2

What I want:
2011-08-08 21:00:00 1
2011-08-08 21:10:00 NA
2011-08-08 21:20:00 2

Is there anyway to do this without using zoo or xts?

A: I'm assuming by your last line that you are trying to avoid using packages.
Sticking with base R, you can try tapply, but your dates will become the rownames (or names, if you skip the data.frame step):
data.frame(value = tapply(cbind(dt$value),
                          list(cut(dt$date, breaks="10 min")),
                          sum))
#                     value
# 2011-08-08 21:00:00     1
# 2011-08-08 21:10:00    NA
# 2011-08-08 21:20:00     2


text:
Q: How to parse an object obtained through a Axios GET request Node.js Express I'm retrieving a json object through the axios get request and I'. attempting to retrieve the name attribute for every object in the results array. when I'm console logging it, it gives me an undefined error? But if i console log data.results, I see the full list of objects?
Api used - https://rickandmortyapi.com/api/character
module.exports = (app) => {
 app.get("/api/users/london", async (req, res) => {
  axios
   .get("https://rickandmortyapi.com/api/character")
   .then(({ data }) =>
     console.log(
       data.array.forEach((element) => {
         element.name;
       })
     )
    )
  .catch((err) => {
    console.log(err);
   });
 });
};

TypeError: Cannot read property 'forEach' of undefined
    at /Users/user/workspace/morty- demo/routes/userRoutes.js:20:22
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

A: Use map to query each name property
     console.log(
       data.array.map((element) => {
         return element.name;
       })
     )

A: You are trying to access data.array which doesn't seem to be a property of the data object returned. You want to call .forEach on the array itself, data.results.
This modified code should work, though it might need some tweaks.
app.get("/api/users/london", async (req, res) => {
  axios
   .get("https://rickandmortyapi.com/api/character")
   .then(({ data }) =>
     data.results.forEach((element) => {
       console.log(element.name);
     })
    )
  .catch((err) => {
    console.log(err);
   });
 });


text:
Q: laravel relationship associate Call to undefined method I've had this working before in a controller but now can't get it working in a repository set up.
I have two models - books and ticketAudit as below.
I'm trying to associate ticketAudit to books but I get an error Call to undefined method
Here are my models:
Book Model:
class Book extends Eloquent {
    public function ticketAudit() {
    return $this->hasMany('TicketAudit');
}
}

TicketAudit Model:
class TicketAudit extends Eloquent {
    public function book() {
    return $this->belongsTo('Book');
}
}

In book controller I have the following (book is injected):
public function store()

{
    $input = Input::all();

    $result = $this->book->create($input);

    if ($result) {
    //     //if book created then create tickets

         $this->ticket->createTicket($input, $result);

         return Redirect::route('books.index');
    }
}

and in the method createTicket in the repository I have:
public function createTicket($input, $book) {

    $counter = $input['start_number'];

    while($counter <= $input['end_number']) {

        $ticketDetails = array(
            'ticketnumber'=>$counter,
            'status'=>'unused',
            'active'=>1
            );

        $newTicket = $this->ticket->create($ticketDetails);

        $newTicket->associate($book);

        $newTicket->save();

        $counter = $counter+1;

    }
    return $counter;
}

the associate method is causing the error - I've got this working in other models but this change to a repository is causing me headaches!
What error have I made?

A: You can make all of this much shorter:
public function createTicket ($input, $book) {

    $counter = $input['start_number'];
    $end     = $input['end_number'];

    for ( ; $counter <= $end; $counter++ )
    {
        $book->ticketAudit()->save($this->ticket->newInstance(array(
            'ticketnumber' => $counter,
            'status'       => 'unused',
            'active'       => 1
        )));
    }
}


text:
Q: A.M./P.M. localization (AMDesignator, PMDesignator) I am trying to localize A.M. & P.M. in datetime in C#.
How reliable is it to use values returned by C#'s 'PMDesignator' & 'AMDesignator' (as in the code below) ?
How can I handle both the below scenarios using the same code?
                                                                        //Line# Output
                                                                        //----- ------
void Main()                                                             //1
{                                                                       //2
    DateTime dt = DateTime.Now; // it is 5:56 PM now                    //3 it is 5:56 PM now
                                                                        //4
    //Japanese                                                          //5
    var JapaneseCulture = new System.Globalization.CultureInfo("ja");   //6
    Console.WriteLine(JapaneseCulture.DateTimeFormat.PMDesignator);     //7     午後
    Console.WriteLine(JapaneseCulture.DateTimeFormat.AMDesignator);     //8     午前
    Console.WriteLine(dt.ToString("t",JapaneseCulture));                //9     17:56
    Console.WriteLine(dt.ToString("hh:mm tt",JapaneseCulture));         //10    05:56 午後
                                                                        //11
    //German                                                            //12
    var GermanCulture = new System.Globalization.CultureInfo("de");     //13
    Console.WriteLine(GermanCulture.DateTimeFormat.PMDesignator);       //14    (blank)
    Console.WriteLine(GermanCulture.DateTimeFormat.AMDesignator);       //15    (blank)
    Console.WriteLine(dt.ToString("t",GermanCulture));                  //16    17:56
    Console.WriteLine(dt.ToString("hh:mm tt",GermanCulture));           //17    05:56
}

Japanese -
PMDesignator, AMDesignator have values,
but are not shown in Line 9 when using "t".
In this case the format specified in Line 10 ("hh:mm tt") gives more correct output.
German -
PMDesignator, AMDesignator don't have values,
so using "t" as in Line 16 gives the correct output,
while Line 17 which uses "hh:mm tt" gives incorrect output.
[EDIT: After reading comments:]
Does "t" give the "typically" used formats fairly reliably? (I have no prior experience in localization, so I do not have a good idea of how reliable the values are)

A: The Standard Date and Time Format Strings in .NET will do the correct thing for the user's culture. In your case just use:
var culture = new CultureInfo("ja");
var dt = DateTime.Now;
Console.WriteLine(dt.ToString("t", culture)); // t => Short Time format.

Only override the culture-specific format with customizations if really required by a specific business requirement.
Microsoft throws a lot of money at their localization efforts to ensure that formatting, translations, etc. are correct for everyone.


text:
Q: Dual voice output for PS4 I don't have a PS4 (but I am planning on getting one sometime soon). I've been looking for the answer to this for a while but I haven't been able to find a definite answer.
On the Xbox 360 (and probably Xbox One too, unsure about this), there is an option where you can output the audio from voice chat from other players to your headset, TV, or both simultaneously. Is there an option like this on the PS4? I know that the PS3 doesn't have this option at all, but I'm wondering if Sony implemented this feature for this gen.

A: Yes. The DualShock 4 controllers for PS4 have a jack socket to connect your headset to.
When connected, you can choose which sounds are sent to the headset. The options are:

*

*just voice chat,

*all sound (game + voice chat).

Whichever sound gets sent to your headset is no longer being sent to your TV.


text:
Q: It is possible to recover a password (not reset) if you have access to root file system? If you have access to /etc/passwd and /etc/shadow, is it possible to figure out what the password is? I know you can reset it, but is there a way to recover it?

A: In theory, with sufficient time and computational power, yes.  But the entire point is that it's a one-way hash whereby the original password is supposed to be for practical purposes impossible to reverse-engineer from the hash.


text:
Q: What kind of SATA interface is on a Thinkpad X120E? I recently ordered a Thinkpad X120E with an AMD Fusion (Zacate) chipset.
I am eyeballing an SSD for it, however newer SSDs are coming out with 6Gbps SATA interfaces. I doubt such a cheap laptop has 6Gbps SATA, but I'm debating waiting the a bit longer until the Intel 510 series come out, if anything to future proof myself by putting it in this laptop and then later on when I do upgrade to a laptop with 6Gbps SATA I'll be good to go.

*

*The hardware manual mentions that the motherboard is for a "AMD Fusion E-350" but the specifications of each hardware part isn't part of the manual.

Does anyone have any information on the kind of SATA controllers in Fusion laptops so I can make a better purchasing decision?

A: I would count on 6Gbps SATA. All of AMD's chipsets in manufacturing since mid-2010 have 6Gbps SATA.
Also a look at the Fusion platform shows that they work with a new south-bridge - "Hudson FCH" which is an evolution of last year AMD's latest chipset - SB850.
Very similar notebook by HP was reviewed by AnandTech: http://www.anandtech.com/show/4187/hp-dm1z-taking-fusion-on-the-road . It confirms Fusion is coupled with Hudson FCH.
Reference for all AMD chipsets and their comparative features can be found here: https://secure.wikimedia.org/wikipedia/en/wiki/Comparison_of_AMD_chipsets .
That said, I would not rush to get a 6Gbps SATA SSD. Most if not all of them are built with 25nm NAND flash which is known to have drastically lower life than 34nm due to the lower process node and high voltage needed to program the cells. The newer SandForce 2xxx controllers use stronger ECC correction in order to cope with errors introduced by this NAND flash. If I were you I would get a 34nm NAND based SSD with SandForce 1xxx controller. A quick example is OCZ Vertex 2 with model numbers OCZSSD2-2VTX*G where * denotes the capacity. There is another series of the same SSD - the "E" series with model numbers OCZSSD2-2VTXE*G. These series use less space for over-provisioning and some are known to use the newer 25nm NAND flash. Both are available in the retail chain today. Of course these SSDs are also cheaper than the 6Gbps SandForce 2 based ones and only about twice slower. That said they are magnitudes faster than HDD in the dreaded random reads/writes so the speed doubling becomes more of a marginal difference than a ground-breaking must-have feature.
If you need a reference for the performance of these drives I have two Disk Utility benchmark shots of a very similar drive here: http://lightrush.ndoytchev.com/random-1/howtoconfigureext4toenabletrimforssdsonubuntu . One is after a month of use, the other is after several. The drive tested uses virtually the same SandForce controller as the OCZ Vertex 2.
In case you are wondering why am I talking about SandForce based drives only - it is because they are better than anything else in power consumption and equal or better than anything else in performance - http://www.anandtech.com/show/3681/oczs-vertex-2-special-sauce-sf1200-reviewed/3 .
Lastly - there is some problem in eCryptfs that limits the maximum speed of sequential reads/writes which makes SSDs as slow as HDDs in those operations over an encrypted Home directory.

A: Jorge, here is the bug report in launchpad: Writing to ecryptfs partition on SSD drive is many times slower than writing to unencrypted partition on the same drive

A: Here's a review that has a couple of desktop boards using the same chips that will be in the x120e (Zacate CPU/GPU and Hudson M1 controller).  They do testing of the system with a fast spinning disk drive as well as a fast SSD both using the 6 Gbps controller.  I've linked to the first page with SATA benchmarks.
http://techreport.com/articles.x/20516/4


text:
Q: Why is /usr/src/linux-aws-headers* growing? Can someone provide some background?
It seems like this folder is growing even when I'm not updating or installing any packages, but I'm not entirely sure about that.
Context: My AWS instances keep running out of disk space, and i already learned to do this periodically:
apt-get -y autoremove
apt-get -y autoclean

But I don't understand why it grows in the first place.
Also see:

*

*Safe to remove /usr/src/linux-headers after purging older linux images?

*Why so many linux-headers, even for absent images
EDIT: On my very new server i get this:
du -h -d1 /usr/src/ | sort -hr
266M  /usr/src/
115M  /usr/src/linux-aws-headers-4.15.0-1035
115M  /usr/src/linux-aws-headers-4.15.0-1032
19M   /usr/src/linux-headers-4.15.0-1035-aws
19M   /usr/src/linux-headers-4.15.0-1032-aws

A: This is probably due to the automatic updates.
You can disable the automatic updates and even remove the unused kernel images and headers running sudo apt autoremove --purge (as you are already doing)
More info here: https://help.ubuntu.com/lts/serverguide/automatic-updates.html


text:
Q: YandexMaps api возыращает 401 {"statusCode":401,"error":"Unauthorized","message":"Unauthorized"} Проект https://steklovozik.ru/#contact-section
Подключены яндекс карты, для отображения меток, и поиска адреса по клику на карте.Карта то работает то нет.
При клике на карту в форме заявки, на запрос возвращает ошибку
{"statusCode":401,"error":"Unauthorized","message":"Unauthorized"}
Ключ не заблокирован. Карта временами работает: потом перестает, потом снова работает. Бесплатный тариф. В чем может быть проблема?


text:
Q: Write numpy array with special delimiters using jinja2 I am trying to export a numpy array to a text file using jinja2 templating engine. The MWE file called test.txt of the template has the following content:
CUSTOM HEADER

{{ data|join('| ') }}

The desired output is a row ending with | and the delimiter between each element of the row is also | (e.g.: 1.0|2.0|3.0|) for a row with 3 elements.
I have tried the following:
from jinja2 import Template
import numpy as np

with open('./test.txt', 'r') as file_:
    template = Template(file_.read())
msg = template.render(data=np.random.rand(2,3))

print(msg)

However my output is not element delimited, nor have the opening and ending | as seen below:

CUSTOM HEADER
[0.62308496 0.97411965 0.8754648]| [0.78255269 0.33039354 0.24678549]

Any clues on how to go about this?

A: With the join method as shown in the question, only the rows of the numpy matrix will be joined. To get the desired output, the following code can be used:
from jinja2 import Template
import numpy as np

template = Template("{% for d in data %}{{ d|join('|') }}|\n{% endfor %}")
msg = template.render(data=np.round(np.random.rand(2,3)*10, 1))
print(msg)

This will result in an output like:
2.0|0.1|1.3|
4.8|8.7|7.3|


text:
Q: Exclude folders when redirect with htaccess I have a question.
I want to redirect domain.com/var to domain.com/id=var
I can do that, but when users write a var like my folders, the htaccess redirect to the folder first :/
This is my actual htaccess
Options +FollowSymLinks -Indexes
RewriteEngine On
RewriteBase /

RewriteRule ^([a-zA-Z0-9-+/]+)$ index.php?id=$1 [L]
RewriteRule ^([a-zA-Z0-9-+/]+)/$ index.php?id=$1 [L]

But when the user write for example css, the htacces redirecto to domain.com/css/?id=css
And the second problem is if the user put / after the var, example domain.com/var/
How can I change that? Thx 4 all!!

A: You need to skip files/directories from rewriting:
Options +FollowSymLinks -Indexes
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([a-zA-Z0-9+/-]+)/?$ index.php?id=$1 [L,QSA]


text:
Q: WPF Datagrid events DataTriggers vs EventTriggers relatively simple question that I am struggling to find a nice elegant solution to. I have a grid with a column that displays values that update every n seconds. I wish to show an animation when the value changes and flash the cell in different colours based on if the number is negative or positive. Found a whole host of methods that do almost what I want, but nothing that exactly matches my needs.

*

*Using an EventTrigger I can make a cell flash every time an update occurs. Using a relatively simple animation below. But I am unable to make the colour the animation uses conditional as the storyboard freezes the UI elements, so I cannot use binding in the storyboard to define the colour.
        <EventTrigger RoutedEvent="Binding.TargetUpdated">
            <BeginStoryboard HandoffBehavior="Compose" Name="GreenCell">
                <Storyboard TargetProperty="(TextBlock.Background).(SolidColorBrush.Color)">
                    <ColorAnimation Duration="0:0:1.50" From="Green" To="Transparent" AutoReverse="False"/>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>

*Using a DataTrigger I can make the cell colour conditional by creating a Converter that converts the updates to this Value and if the value is negative and then binding a data trigger to this and setting the background colour when this changes. But if the number is already negative, and remains negative (but changes) the trigger is not fired.
        <DataTrigger Binding="{Binding Value, Converter={StaticResource cellBackGroundConverter}}" Value="True">
            <DataTrigger.EnterActions>
                <BeginStoryboard HandoffBehavior="Compose" Name="GreenCell">
                    <Storyboard TargetProperty="(TextBlock.Background).(SolidColorBrush.Color)">
                        <ColorAnimation Duration="0:0:1.50" From="Green" To="Transparent" AutoReverse="False"/>
                    </Storyboard>
                </BeginStoryboard>
            </DataTrigger.EnterActions>
        </DataTrigger>
        <DataTrigger Binding="{Binding Value, Converter={StaticResource cellBackGroundConverter}}" Value="False">
            <DataTrigger.EnterActions>
                <BeginStoryboard HandoffBehavior="Compose" Name="RedCell">
                    <Storyboard TargetProperty="(TextBlock.Background).(SolidColorBrush.Color)">
                        <ColorAnimation Duration="0:0:1.50" From="Red" To="Transparent" AutoReverse="False"/>
                    </Storyboard>
                </BeginStoryboard>
            </DataTrigger.EnterActions>
        </DataTrigger>

What I require seems to be an event trigger, to capture every update and play the animation with the conditional aspect of the data trigger.
Surely I am missing something simple here, would love for someone to set me straight!
Many thanks
Matt


text:
Q: Find the length of latus rectum of the conic $7x^2+12xy-2y^2-2x+4y-7=0$. Find the length of latus rectum of the conic $7x^2+12xy-2y^2-2x+4y-7=0$.

The given conic $7x^2+12xy-2y^2-2x+4y-7=0$ is a hyperbola because when i compare it with $ax^2+2hxy+by^2+2gx+2hy+c=0$ and found $h^2-ab>0$,
Then i tried to change $7x^2+12xy-2y^2-2x+4y-7=0$ into the standard form $\frac{x^2}{a^2}-\frac{y^2}{b^2}=1$ so that length of latus rectum is $\frac{2b^2}{a}$
$7x^2+12xy-2y^2=7x^2-2(-6xy+y^2)=7x^2-2(9x^2-2.3x.y+y^2)+18x^2$
$=25x^2-2(3x-y)^2$
$7x^2+12xy-2y^2-2x+4y-7=25x^2-2(3x-y)^2-2x+4y-7$
Let $x=X,3x-y=Y$ so that $y=3X-Y$
$25x^2-2(3x-y)^2-2x+4y-7=0$ becomes $25X^2-2Y^2-2X+4(3X-Y)-7=0$
$25X^2-2Y^2+10X-4Y-7=0$
$(25X^2+10X+1)-2(Y^2+2Y+1)+2-1-7=0$
$(5X+1)^2-2(Y+1)^2=6$
$\frac{(5X+1)^2}{6}-\frac{(Y+1)^2}{3}=1$
$\frac{(5x+1)^2}{6}-\frac{(3x-y+1)^2}{3}=1$
Now this is in the standard form,So $a^2=6,b^2=3$ and length of latus rectum is $\frac{2b^2}{a}=\frac{6}{\sqrt6}=\sqrt6$
But the answer given is $\sqrt{\frac{48}{5}}$I dont know where i am wrong?

A: All of your algebraic work is correct, but you will want a different approach. The problem is in your conclusion, when you change variables back to $x,y$:

$$\frac{(5x+1)^2}{6}-\frac{(3x-y+1)^2}{3}=1$$
  Now this is in the standard form, so $\ldots$

This is not in standard form because the numerator of the second fraction has both $x$ and $y$ terms. Furthermore, the change of variables will change the foci, coördinates of the latera recta, and so on, and these coördinates do not scale linearly with the variables.
Instead, try a change of variables that consists of a rotation without scaling:
$$x = X\cos\theta - Y\sin\theta,\quad y=X\sin\theta + Y\cos\theta$$
where
$$\cot2\theta = \frac{A-C}B.$$
You can read more details about this transformation in this excerpt from Stewart. Note that you don't actually need to solve for $\theta$ since we only care about $\cos\theta$ and $\sin\theta$; in your case, you should end up with
$$x = 2\sqrt\frac15X - \sqrt\frac15Y, \quad y = \sqrt\frac15X + 2\sqrt\frac15Y.$$
You should be able to take it from here!


text:
Q: Style children from parent using a class In Svelte I can pass a custom class to a children component like that:
Icon.svelte

App.svelte

  <Icon class='custom-icon' />

If I inspect the rendered DOM I see that the class is successfully given to the Icon component:

But if I define some style for .custom-icon in App.svelte they are not applied:

  <Icon class='custom-icon' />

Check the codesandbox.
So has someone an idea how I can style a children component from the parent using a class?

A: I think there's a way to get the best of both worlds.
* :global(.custom-icon) {
   border: solid 2px red;
}

This will output a CSS like this:
.svelte-5z4ccp .custom-icon {
   border: solid 2px red;
}

This will allow you to have scoped CSS for the descendants of your component. It's not possible to scope it only for the immediate child, though, only to all the descendants.

A: try this
:global(.custom-icon) {
    border: solid 2px red;
}

see also https://svelte.dev/docs#style

A: You have two options:

*

*define the styles you'll be using inside the child component where they will be used (see REPL) - these styles will be scoped to the component
or

*

*define the styles with the :global modifier, making them available to all descendants of the component where the styles are defined (see REPL) - these styles will be unscoped


text:
Q: execute linux shell permisson denied,but i have assigned permissions,how can i fix it? I write a shell named test.sh in /run path and execute chmod 777 test.sh  command.
   then I run ./test.sh ,it displays permission denied.
   but I run sh test.sh,it's ok.
   Then I copy test.sh to my home directory and run ./test.sh ,it works.
   can somebody tell me why?
   my problem


text:
Q: Carregar informações nos inputs do modal com base no id enviado pelo clique no link data-id Usando a documentação do bootstrap,
fiz uma mudança de a href para button
<button type="button" class="btn-a" data-toggle="modal" data-target="#EditaFoto"
    data-whatever="<?php echo $row['idfoto']; ?>"
    data-whateverdatavisita="<?php echo $row['datavisita']; ?>"
    data-whateveridvisita="<?php $row['idvisita']; ?>"
    data-whateverpercetandamento="<?php $row['percentandamento']; ?>"
    data-whatevercaminhofoto="<?php $row['caminhofoto']; ?>"
    data-whateverdescricaofoto="<?php $row['descricaofoto']; ?>"
    >
 <i class="fas fa-edit"></i>

Quando clicar no botão ele carrega as informações e manda para o Modal.
No JS:
$('#EditaFoto').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget) // Button that triggered the modal
    var recipient = button.data('whatever') // Extract info from data-* attributes
    var recipientdatavisita = button.data('whateverdatavisita')
    var recipientidvisita = button.data('whateveridvisita')
    var recipientpercetandamento = button.data('whateverpercetandamento')
    var recipientcaminhofoto = button.data('whatevercaminhofoto')
    var recipientdescricaofoto = button.data('whateverdescricaofoto')

    var modal = $(this)
    modal.find('.modal-title').text('ID Foto ' + recipient)
    modal.find('#datavisita').val(recipientdatavisita)
    modal.find('#idvisita').val(recipientidvisita)
    modal.find('#percentandamento').val(recipientpercetandamento)
    modal.find('#caminhofoto').val(recipientcaminhofoto)
    modal.find('#descricaofoto').val(recipientdescricaofoto)

})

Só que no caso ele só está funcionando essas duas partes:
data-whatever="<?php echo $row['idfoto']; ?>"
data-whateverdatavisita="<?php echo $row['datavisita']; ?>"

As demais não são carregadas.
No PHP está tudo certo e os dados estão chegando alimentar as variáveis.


text:
Q: How to Replace a word in a String with a blank in C#? Any algorithm which changes a word from a string to a blank?
I'm having problems with this.
my scenario is replacing a word to a blank but some words are also found inside another word so what happens is it also replaces the certain string in that word.
Ex. Hello Ello llo lo o
if I replace llo with _
output:
He___ E__ ____ lo o

A: I think you should have some luck with Regex.Replace and using the word boundary special character (\b) to indicate word boundaries. I'm no expert, though. But do try that.
Example:
string input = "llo Hello Ello llo lo o llo, and oh hello llo! Look, a yellow llo.";
string output = Regex.Replace(input, @"\bllo\b", "___");
Console.WriteLine(output);

Output:

___ Hello Ello ___ lo o ___, and oh hello ___! Look, a yellow ___.

Note this caught the "llo" at the beginning, as well as those followed by punctuation ("llo,", "llo!", and "llo.") without erroneously stripping out those that were part of other words ("Hello", "Ello", "yellow").

Edit: The following is in response to your comment. My understanding is that you have two TextBoxes, preview and question, and a ListBox, chosenwordlist. I believe this is what you want to do:
// Start by setting preview to the same text as question.
preview.Text = question.Text;

for (int i = 0; i < chosenwordlist.Items.Count; ++i)
{
    string word = chosenwordlist.Items[i].ToString();

    // Notice the verbatim literal (@) for the SECOND "\b" as well.
    string pattern = @"\b"+ word + @"\b";

    // Since the text in your question TextBox isn't changing, you need to base each
    // replacement off of what's in the preview TextBox, which IS (changing).
    preview.Text = Regex.Replace(preview.Text, pattern, "__________");
}

A: You can use regular expressions
http://www.regular-expressions.info/dotnet.html

A: I hope I have understood you correctly. Using Regex you can achieve this:
Regex myRegex = new Regex(@"(?<![a-z])[a-z](?![a-z])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
Debug.WriteLine(myRegex.Replace("test-a-b-c-test", "!"));
Will print: test-!-!-!-test
From the original string: test-a-b-c-test


text:
Q: Distributed secure MinIO in docker-compose I have a quite complex system in Docker. Everything runs in a big docker-compose file. Previously everything runs on one (manager) node in my Docker Swarm so I have generated a CERT for my domain (with certbot) and I have used the below MinIO service in my compose file:
  object_storage:
    image: minio/minio:RELEASE.2020-12-10T01-54-29Z
    ports:
      - 9000:9000
    environment:
      MINIO_ACCESS_KEY_FILE: object_storage_user
      MINIO_SECRET_KEY_FILE: object_storage_password
    command: server /data
    depends_on:
      - fluentd
    volumes:
      - object_storage_data:/data
      - ./certs/domain.crt:/root/.minio/certs/public.crt
      - ./certs/domain.key:/root/.minio/certs/private.key
    networks:
      - object_storage_net
    secrets:
      - object_storage_user
      - object_storage_password
    logging:
      driver: "fluentd"
      options:
        fluentd-address: ${SYSTEM_HOST}:24224
        tag: object-storage

The above implementation works as expected! But now I have 2 separated servers to run the MinIO. These servers are joined to my Docker Swarm as worker nodes. The MinIO shouldn't run on manager node (Only on two separated worker nodes)!
>>> docker node ls
ID                                          HOSTNAME    STATUS      AVAILABILITY   MANAGER STATUS   ENGINE VERSION
mcbkz9m5nzf7oa3fiqk0lf4qo *  manager         Ready           Active                    Leader                    20.10.1
dz4e3k70g8ik2z4bcx8u0ft9ao   minio_1          Ready           Active                                                   20.10.2
r0qpdn2guyy5773vo8vg2trzo    minio_2          Ready           Active                                                   20.10.2

My current MinIO implementation in my docker-compose file:
object_storage_1:
   image: minio/minio:RELEASE.2020-12-10T01-54-29Z
   ports:
     - 9000:9000
   environment:
     MINIO_ACCESS_KEY_FILE: object_storage_user
     MINIO_SECRET_KEY_FILE: object_storage_password
   command: server https://object_storage_{1...2}/data{1...2}
   depends_on:
     - fluentd
   volumes:
     - object_storage_data_1_1:/data1
     - object_storage_data_1_2:/data2
     - ./certs/domain.crt:/root/.minio/certs/public.crt
     - ./certs/domain.key:/root/.minio/certs/private.key
   networks:
     - object_storage_net
   secrets:
     - object_storage_user
     - object_storage_password
   deploy:
     restart_policy:
       condition: on-failure
     placement:
       constraints:
         - node.hostname == minio_1
   logging:
     driver: "fluentd"
     options:
       fluentd-address: ${SYSTEM_HOST}:24224
       tag: object-storage

 object_storage_2:
   image: minio/minio:RELEASE.2020-12-10T01-54-29Z
   ports:
     - 9000
   environment:
     MINIO_ACCESS_KEY_FILE: object_storage_user
     MINIO_SECRET_KEY_FILE: object_storage_password
   command: server https://object_storage_{1...2}/data{1...2}
   depends_on:
     - fluentd
   volumes:
     - object_storage_data_2_1:/data1
     - object_storage_data_2_2:/data2
     - ./certs/domain.crt:/root/.minio/certs/public.crt
     - ./certs/domain.key:/root/.minio/certs/private.key
   networks:
     - object_storage_net
   secrets:
     - object_storage_user
     - object_storage_password
   deploy:
     restart_policy:
       condition: on-failure
     placement:
       constraints:
         - node.hostname == minio_2
   logging:
     driver: "fluentd"
     options:
       fluentd-address: ${SYSTEM_HOST}:24224
       tag: object-storage

If I check the log of an instance of my MinIO service, I got the following error:
Unable to read 'format.json' from https://object_storage_1:9000/data1: Post "https://object_storage_1:9000/minio/storage/data1/v22/readall?disk-id=&file-path=format.json&volume=.minio.sys": x509: certificate is valid for my_domain.app, not object_storage_1
Unable to read 'format.json' from https://object_storage_2:9000/data1: Post "https://object_storage_2:9000/minio/storage/data1/v22/readall?disk-id=&file-path=format.json&volume=.minio.sys": x509: certificate is valid for my_domain.app, not object_storage_2

But I can reach the MinIO on 9000 port, just there is a pop-up error:

I want to access to MinIO only through my domain (my_domain.app:9000). The MinIO in this case doesn't use the real server name however it uses the "virtual" Docker network (Eg.: https://object_storage_2:9000).
My questions:

*

*How can I generate certs for "virtual" Docker networks (Eg.: object_storage_1 or object_storage_2)?

*Where should I put the generated certs?

*Is is possible to solve with only my generate (for my domain) cert?

I am open for every hint and solution!

A: I had to put the (Domain) CERT file to minio/certs/CAs folder instead of /root/.minio/certs folder. Furthermore I had to copy the CERT to the worker nodes (separated servers) if I didn't copy it to nodes the service didn't find it on the worker node.
The correct volumes parameter looks like as below:
volumes:
  - object_storage_data_1_1:/data1
  - object_storage_data_1_2:/data2
  - ./certs/domain.crt:/root/.minio/certs/CAs/public.crt

One working service of my several MinIO services:
  object-storage-1:
    image: minio/minio:RELEASE.2021-08-17T20-53-08Z
    expose:
      - "9000"
      - "9001"
    environment:
      MINIO_ACCESS_KEY_FILE: object_storage_user
      MINIO_SECRET_KEY_FILE: object_storage_password
      MINIO_BROWSER_REDIRECT_URL: https://${SYSTEM_HOST}:9001
      MINIO_SERVER_URL: https://${SYSTEM_HOST}:9000
    command: server --console-address ":9001" http://object-storage-{1...4}/data{1...2}
    hostname: object-storage-1
    depends_on:
      - fluentd
    volumes:
      - object_storage_data_1_1:/data1
      - object_storage_data_1_2:/data2
      - ./certs/domain.crt:/root/.minio/certs/CAs/public.crt
    networks:
      - object_storage_net
    secrets:
      - object_storage_user
      - object_storage_password
    deploy:
      restart_policy:
        condition: on-failure
      placement:
        constraints:
          - node.hostname == minio1
    logging:
      driver: "fluentd"
      options:
        fluentd-address: ${SYSTEM_HOST}:24224
        tag: object-storage

AND I had to create a NgInx config:
upstream minio {
    server object-storage-1:9000;
    server object-storage-2:9000;
    server object-storage-3:9000;
    server object-storage-4:9000;
}

upstream console {
    ip_hash;
    server object-storage-1:9001;
    server object-storage-2:9001;
    server object-storage-3:9001;
    server object-storage-4:9001;
}

server {
    listen              9000 ssl;
    listen              [::]:9000 ssl;
    server_name         my.server.com;
    ssl_certificate     /ssl/domain.crt;
    ssl_certificate_key /ssl/domain.key;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers         HIGH:!aNULL:!MD5;

    # To allow special characters in headers
    ignore_invalid_headers off;
    # Allow any size file to be uploaded.
    # Set to a value such as 1000m; to restrict file size to a specific value
    client_max_body_size 0;
    # To disable buffering
    proxy_buffering off;

    location / {
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        proxy_connect_timeout 300;
        # Default is HTTP/1, keepalive is only enabled in HTTP/1.1
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        chunked_transfer_encoding off;

        proxy_pass http://minio;

    }
}

server {
    listen              9001 ssl;
    listen              [::]:9001 ssl;
    server_name         my.server.com;
    ssl_certificate     /ssl/domain.crt;
    ssl_certificate_key /ssl/domain.key;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers         HIGH:!aNULL:!MD5;

    # To allow special characters in headers
    ignore_invalid_headers off;
    # Allow any size file to be uploaded.
    # Set to a value such as 1000m; to restrict file size to a specific value
    client_max_body_size 0;
    # To disable buffering
    proxy_buffering off;

    location / {
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-NginX-Proxy true;

        # This is necessary to pass the correct IP to be hashed
        real_ip_header X-Real-IP;

        proxy_connect_timeout 300;
        # Default is HTTP/1, keepalive is only enabled in HTTP/1.1
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        chunked_transfer_encoding off;

        proxy_pass http://console;

    }
}


text:
Q: JsonSchemaGenerator Not Setting Fields to required = false I'm using a JsonSchemaGenerator from JSON.NET against a series of models to output the respective JSON schemas into a dictionary like below.
JsonSchemaGenerator generator = new JsonSchemaGenerator()
{
    UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName,
};
List<Type> modelTypes = Assembly.GetExecutingAssembly()
    .GetTypes()
    .ToList()
    .Where(t => t.Namespace == "MyApp.Models")
    .ToList();

foreach (Type type in modelTypes)
{
    JsonSchema schema = generator.Generate(type, jsonSchemaResolver, false);
    schemaDictionary.Add(type, schema);
}

This is working properly with the exception of the vales set for the required attribute. No matter how I decorate the model properties, the fields always are shown to be "required":true as shown below:
"FirstName": {
   "required": true,
   "type": "string"
}

However, in code my model is decorated as such:
[JsonProperty(Required = Required.Default)]
public string FirstName { get; set; }

Looking at the Json.Net documentation, setting to Required.Default should result in the property not being required in the schema:

"Default - 0 - The property is not required. The default state."

Any idea on what I'm doing incorrectly and need to change so that FirstName property is output in the schema as "required": false? I do not want to have to generate and hand massage all of these schemas.

A: The Required enumeration controls which values can the property have: whether null values are allowed or not. To control the  "required" property in the json schema, meaning whether the json string must contain the actual property or not, you need to use the DefaultValueHandling or NullValueHandling enumerations while generating the schema. Lets say that we have the following class:
public class Person
{
        [JsonProperty(Required = Required.Default)]
        public string FirstName { get; set; }
}

Generated schema with JSON.NET for this class looks like this:
{
    "id": "MyApp.Models.Person",
    "type": "object",
    "properties": {
        "FirstName": {
            "required": true,
            "type": [
                "string",
                "null"
            ]
        }
    }
}

This schema indicates that a json string must have the property FirstName and it is allowed for this property to have null values.
By changing the Required attribute from Default to Always we'll get the following schema:
{
    "id": "MyApp.Models.Person",
    "type": "object",
    "properties": {
        "FirstName": {
            "required": true,
            "type": "string"
        }
    }
}

This schema indicates that a json string must have the property FirstName and it is NOT allowed for this property to have null values.
To get what you want, you'll need to include the DefaultValueHandling or NullValueHandling enumerations. Something like this:
public class Person
{
    [JsonProperty(Required = Required.Default, DefaultValueHandling = DefaultValueHandling.Ignore)]
    public string FirstName { get; set; }
}

Generated schema from this class would look like this:
{
    "id": "MyApp.Models.Person",
    "type": "object",
    "properties": {
        "FirstName": {
            "type": [
                "string",
                "null"
            ]
        }
    }
}

This schema indicates that the FirstName property is not required in the json string, but if it is present, it may have null value. The same effect can be achieved if you use DefaultValueHandling.IgnoreAndPopulate enum value or if you switch to the NullValueHandling property instead of DefaultValueHandling property and set its value to NullValueHandling.Ignore.


text:
Q: Linq portability Is there a tool to port linq expressions to regular foreach loops..?
If I were (say) to port existing linq driven code to an iPhone app?
Is this a problem since i use linq heavily?

A: Not specialized in Mono development, but as much as I read it supports a LINQ. So you no need to translate your LINQ queries into the for loops.
What .NET features does MonoTouch support? (LINQ with some limitations)
MonoTouch 4 announcment


text:
Q: Another version of the Chinese Remainder Theorem Let $R$ be a ring, $I,J$ ideals such that $I+J=R$. The Chinese Remainder Theorem claims that if $I\cap J=(0)$, then $R\simeq R/I\times R/J$.
I remember seeing a version of the theorem for the case of principal ideals $I=(p),\ J=(q)$ which assumes instead of the comaximality of $I$ and $J$ (and probably of the condition on the intersection) that $I$ and $J$) that $p$ and $q$ are coprime elements in $R$. (I'm not sure that my statement is precise.) This version is easier to use sometimes, e.g. it looks easier for me to prove that $x-1$ and $x^2+x+1$ are coprime than to prove that $(x-1)+(x^2+x+1)=(1)$ in $\mathbb R[x]$.
So my questions are: whether my statement is precise, and how does it follow from the general Chinese remainder theorem?

A: The problem is what do you mean by the statement: "$x$ and $y$ are coprime elements in a ring $R$". Let's stick to integers for now. There are two different ways you can think about coprime integers. Two integers $x,y\in \mathbb{Z}$ are said to be coprime if one of the two equivalent conditions are satisfied.

*

*The greatest common divisor of $x,y$ is equal to one.

*There exists $a,b\in \mathbb{Z}$ such that $ax+by=1$ (Bezout's identity)

The problem with definition (1) is that there are many rings out there with no such thing as a greatest common divisor. Say $\mathbb{C}[x]/(x^2)$ is not even a domain. Or $\mathbb{Z}[-\sqrt{3}]$ which is a domain but the two elements $x=4=2\times 2=(1+\sqrt{-3})(1-\sqrt{-3})$ and $y=(1+\sqrt{-3})\times 2$ have no gcd. A commutative ring admitting a gcd for any pair of elements is called a GCD domain.
Your example of $\mathbb{R}[x]$ is a GCD domain (actually, more strongly, a principal ideal domain, PID). But even if a ring $R$ is a GCD domain, it does not mean $R$ admits a Bezout identity. An example would be $\mathbb{R}[x,y]$ which is a GCD domain (actually a unique factorization domain, UFD) which does not admit a Bezout identity. A ring that admits a Bezout identity is called a Bezout domain. All Bezout domains are GCD domains. Alternatively, a Bezout domain can be defined as follows:

An integral domain $R$ is called a Bezout domain if given any two elements $x,y$, the sum of ideals $(x)+(y)$ is again principal.

So you can see that in a Bezout domain, $x,y$ are coprime if and only if the ideals $(x), (y)$ are coprime (Two ideals $I,J\subset R$ are called coprime if $I+J=R$). However, one can define coprime ideals for all commutative rings, and coprime elements only for some rings. In a sense then, the way coprime ideals are defined is the natural generalization of how we expect "coprime" to be.
Now the Chinese Reminder theorem says

If the ideals $I,J\subset R$ are comaximal, then $R/I\cap J\simeq R/I\times R/J$.

If we assume $R$ is a Bezout domain, and $x,y\in R$ coprime, then $(x)\cap (y)=(xy)$ (which is not zero y the way). And Chinese remainder theorem, in this case, becomes
$$
R/(xy)\simeq R/(x)\times R/(y)
$$
So sure, if in your ring of interest it makes sense to talk about coprime elements, you can go with your special version of the theorem. But if there is no such thing, well... I hope, this sheds some light on the matter.

A: The abstract Chinese remainder theorem that I know is this (stated for two ideals):

Let $R$ be a (commutative) ring, $I, J$ two coprime ideals in $R$, i.e. satisfying$I+J=R$.  Then $IJ=I\cap J$, and we have an isomorphism
  \begin{align}
R/I\cap J&\xrightarrow{\;\sim\;}R/I\times R/J\\
r+I\cap J&\longmapsto (r+ I, r+ J)
\end{align}


text:
Q: How to rectify Typescript compilation error TS5012 i have typescript installed globally on my machine but when i run "tsc using-ts.ts" iget this error
error TS5012: Cannot read file 'C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\lib.d.ts': error
TS5012: Cannot read file 'C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\lib.d.ts': File could
not be opened.

how do i correct this error?

A: It seems like your installation is not complete. Just use npm i -g typescript@latest to install the latest version of typescript globally on your computer. (By the way: You're using typescript v1 which is really old. The latest version is v4.0)


text:
Q: Accessing raw partition in Android using Java I have a partition in Android that's not mounted because it doesn't have a file system, and I need to write a string into it.  I tried three different methods, and only the first (from adb) works.  I need to do this under program control, which is what the second and third methods do, but both fail.  I tried adding system permissions to my app, but that didn't help.  Do I need root permission to do this from a program?
First Method -
adb shell "echo test > /cache/command"
adb shell dd if=/cache/command of=/dev/block/mmcblk3p3 bs=4096 seek=1

Second Method -
java.lang.Process p = Runtime.getRuntime().exec(
"dd if=/cache/command of=/dev/block/mmcblk3p3 bs=4096 seek=1");

Third Method -
File fileName = new File("/dev/block/mmcblk3p3");
String cmd = "test";
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(cmd.getBytes(), 4096, cmd.length());
fos.flush();

The second method gives no feedback, even though it failed to work.  The third method gives the following output:
W/System.err( 1014): java.io.FileNotFoundException:
/dev/block/mmcblk3p3 (Permission denied)

A: I should warn you about the risks you may have enabling liberal permissions on partitions that should not be accessed by applications. Having said that and assuming you know the risks, what you can do is to change the permissions, if you want to do it permanently you can add
chmod 0666 /dev/block/mmcblk3p3

to init.rc.
There are sections containing other chmod commands where you can put yours.