text:
Q: copying data (packet payload) received over a network I have an application that receives packets over a network. I am able to interpret all the field value except the payload (data) section.
consider a packet structure:
src addr | src port | dest addr | dest port | data | checksum
the packet itself is stored as a char* and i can get all the values src/des addr, port. But the payload section confuses me. I am able to print it in hex format but printing it in char gives non-ascii value. When i copy the payload section to a new string and print the new string i get nothing i.e. it dost print anything and its length is 0. I don get any error or warning. Could some one pls tell where i am going wrong? I think im missing something here.
Here is the section of code:
  typedef struct pcap_802_15_4_s{
   guint16 fcf;
   unsigned char seqno;
   guint16 dpan;
   guint16 daddr;
   guint16 saddr;
   char *payload_data;
  } pcap_802_15_4_t;

char *packet = read_serial_packet(src, &len);

      if (!packet)
    exit(0);
      else if (packet[0] != TOS_SERIAL_802_15_4_ID) {
    printf("bad packet (serial type is %02x, not %02x)\n", packet[0], TOS_SERIAL_802_15_4_ID);
      }

      plen = packet[1];
      printf("Received packet of length %i: \n", plen);
      if (plen != len) {
    printf("Packet format error: read packet length (%hhx) is different than expected from frame (%hhx).\n", plen, len);
      }

      struct timeval tv;
      gettimeofday(&tv, NULL);

      i = 2;
      // Read in FCF and i+=2
      fcf = packet[i+1] << 8 | packet[i];
      packet_802_15_4.fcf = fcf;
      i += 2;

      {
    if ((fcf & 0x7) == 0x01) {
      printf("  Frame type: data\n");
    }
    else if ((fcf & 0x7) == 0x02) {
      printf("  Frame type: acknowledgement\n");
    }
    else {
      printf("  Frame type: other\n");
    }

    printf("  Security: %s\n", (fcf & (1 << 3)) ? "enabled":"disabled");
    printf("  Frame pending: %s\n", (fcf & (1 << 4)) ? "yes":"no");
    printf("  Ack request: %s\n", (fcf & (1 << 5)) ? "yes":"no");
    printf("  Intra-PAN: %s\n", (fcf & (1 << 6)) ? "yes":"no");
    intraPan = (fcf & (1 << 6));
      }

      {
    unsigned char seqno = packet[i++];
    packet_802_15_4.seqno = seqno;
    printf("  Sequence number: 0x%hhx\n", seqno);
    printf("  Sequence number(dump): 0x%hhx\n", packet_802_15_4.seqno);

      }

      {
    char addrLen = (fcf >> 10) & 0x3;
    short saddr = 0;
    long long laddr = 0;

    // 16- and 64-bit destinations have a PAN ID
    if (addrLen == 2 || addrLen == 3) {
      short destPan = packet[i++] << 8 | packet[i++];
      packet_802_15_4.dpan = destPan;
      printf("  Destination PAN: 0x%02hx\n", destPan);
      printf("  Destination PAN (dump): 0x%02hx\n", packet_802_15_4.dpan);
    }

    switch (addrLen) {
    case 0:
      printf("  Destination address: none\n");
      break;
    case 1:
      printf("  Destination address: invalid? (0x01)\n");
      break;
    case 2:
      saddr =  (packet[i] << 8 | packet[i+1]);
      i += 2;
      packet_802_15_4.daddr = saddr;
      printf("  Destination address: 0x%04hx\n", saddr);
      printf("  case 2: Destination address(dump): 0x%04hx\n", packet_802_15_4.daddr);
      break;
    case 3: {
      int j;
      for (j = 0; j < 8; j++) {
        laddr = laddr << 8;
        laddr |= packet[i++];
      }
      packet_802_15_4.daddr = saddr;
      printf("  Destination address: 0x%016llx\n", laddr);
      printf("  case 3: Destination address(dump): 0x%016llx\n", (long long unsigned int)packet_802_15_4.daddr);
      break;
    }
    default:
      printf("  Destination address: parse serror\n");
    }
      }

      {
    char addrLen = (fcf >> 14) & 0x3;
    short saddr = 0;
    long long laddr = 0;

    if (!intraPan) { // Intra-PAN packet
      short srcPan = packet[i] << 8 | packet[i+1];
      //packet_802_15_4.span = srcPan;
      i += 2;
      printf("  Source PAN: 0x%02hx\n", srcPan);
    }

    switch (addrLen) {
    case 0:
      printf("  Source address: none\n");
      break;
    case 1:
      printf("  Source address: invalid? (0x01)\n");
      break;
    case 2:
      saddr =  (packet[i] << 8 | packet[i + 1]);
      packet_802_15_4.saddr = saddr;
      i += 2;
      printf("  case(2): Source address: 0x%04hx\n", saddr);
      break;
    case 3: {
      int j;
      for (j = 0; j < 8; j++) {
        laddr = laddr << 8;
        laddr |= packet[i++];
      }
      printf("  case(3): Source address: 0x%016llx\n", laddr);
      packet_802_15_4.saddr = saddr;
      break;
    }
    default:
      printf("  Source address: parse serror\n");
    }
      }

      if (iframes) {
    printf("  I-Frame: %s\n", (packet[i++] == 0x3f)? "yes":"no");
      }

      printf("  AM type: 0x%02hhx\n", packet[i++]);

      if (i >= plen) {
    printf("Packet format error: read packet is shorter than expected.\n");
      }
      else {
        int j=0;
    packet_802_15_4.payload_data = (char *)malloc(sizeof(char) * (plen - i));
    for (; i < plen; i++) {
      printf("Payload byte %d: 0x%02hhx \n",i,packet[i]);
      printf("Payload byte %d: %c \n",i,packet[i]);
      packet_802_15_4.payload_data[j] = (char) packet[i];
      j++;
    }

The Hex output of payload:
0x00
0x01
0x10
0xdd

A: 1) If you have a Wireshark, capture several packets and check the payload representation there. If Wireshark displays your payload right, then receiver part of the code must be problematic.
2) Are you sure you don't have any IP header or TCP header? Are you transferring raw ethernet?
3) Are you sure the payload is nothing but the characters?


text:
Q: Dynamic group by list data indexes I want to group by dynamically according to more than one index in a list.
Model
public class MyModel
{
    public string baseTableName { get; set; }

    public List<object> columns { get; set; }

    public List<List<object>> rows { get; set; }
}

I need to find the indexes of the pk  columns list in this model.
Then I want to group the data in the rows list by pk columns.
Sample Request
{
    "tableName": "fooTable",
    "columns": [
        "c1",
        "c2",
        "c3"
    ],
    "rows": [
        [
            "1",
            "a",
            "kobe"
        ],
        [
            "2",
            "a",
            "lebron"
        ]
    ]
}

In this sample request, columns c1 and c2 are pk.
Codes
// Returns indexes of pk columns.
var pkColumnIndexes = GetPkIndexes(columns);

var gp = requestObject.rows.GroupBy(gp => new { indx1 = gp[pkColumnIndexes[0]], indx2 = gp[pkColumnIndexes[1]] });
var groupData = gp.Select(s => s.LastOrDefault()).ToList();

--
(gp => new { indx1 = gp[pkColumnIndexes[0]], indx2 = gp[pkColumnIndexes[1]] })
I want to group this part according to indexes.
Can group by keys dynamically created with a for loop?

A: Using an IEqualityComparer for sequences, you can create sequence keys and group by them:
public static class Make {
    public static IEqualityComparer<IEnumerable<T>> IESequenceEqual<T>() => new IEnumerableSequenceEqualityComparer<T>();
    public static IEqualityComparer<IEnumerable<T>> IESequenceEqual<T>(T _) => new IEnumerableSequenceEqualityComparer<T>();

    private class IEnumerableSequenceEqualityComparer<T> : IEqualityComparer<IEnumerable<T>> {
        public bool Equals(IEnumerable<T> x, IEnumerable<T> y) =>
            Object.ReferenceEquals(x, y) || (x != null && y != null && (x.SequenceEqual(y)));

        public int GetHashCode(IEnumerable<T> items) {
            // Will not throw an OverflowException
            //unchecked {
            //    return items.Where(e => e != null).Select(e => e.GetHashCode()).Aggregate(17, (a, b) => 23 * a + b);
            //}
            var hc = new HashCode();
            foreach (var item in items)
                hc.Add(item);
            return hc.ToHashCode();
        }
    }
}

var IEObjSeqEq = Make.IESequenceEqual<string>();
var ans = requestObject.rows.GroupBy(r => pkColumnIndexes.Select(idx => r[idx].ToString()), IEObjSeqEq);

Note you must explicitly convert to string to avoid the default reference equality of object.

redpajama_set_name: RedPajamaStackExchange


text:
Q: phonegap command line build errors I am trying to compile the project using phonegap commandline using phonegap build ios, but got error saying:

execvp(): Permission denied.

Then I changed all files in project with chmod 777, still doesn't work.
I then tried sudo phonegap build ios, and with following errors:

clang: error: no such file or directory: '/Users/admin/CurvelurveNative/platforms/ios/CordovaLib/CordovaLib_Prefix.pch'
  clang: error: no input files
  Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1
** BUILD FAILED **
The following build commands failed:
      ProcessPCH /var/folders/zz/zyxvpxvq6csfxvn_n0000000000000/C/com.apple.DeveloperTools/5.1-5B130a/Xcode/SharedPrecompiledHeaders/CordovaLib_Prefix-gvmoqaqteektjvafgqfbaiggmjge/CordovaLib_Prefix.pch.pch  CordovaLib_Prefix.pch normal i386 objective-c  com.apple.compilers.llvm.clang.1_0.compiler
  (1 failure)
  { [Error: /Users/admin/testproject/platforms/ios/cordova/build: Command failed with exit code 65] code: 65 }
     [error] /Users/admin/testproject/platforms/ios/cordova/build: Command failed with exit code 65


text:
Q: Create a custom html extension that will work like a ListBoxFor but output checkboxes instead? I am trying to create (or even better find) a custom html extension method that works in a similar manor to the ListBoxFor but renders a group of checkboxes instead of a select multiple.
What is the best way of going about this?  I am curious how the ListBoxFor method works, when it is only passed an expression and an enumerable of SelectListItems, which only have the default items selected.  It is not passed the model, so how does it know when to select the correct items (somehow it seems able to do that)?  Also, how does it write html attributes based on an anonymous object?

A: You haven't provided any details and specific example of what you are trying to achieve. You haven't provided any source code you have tried so far in order to solve the problem you are having. Next time you ask a question on StackOverflow please do so in order to make your question more meaningful and focused on a specific problem.
Anyway, here's an example. Let's suppose that you have defined a view model:
public class MyViewModel
{
    public IEnumerable<string> SelectedValues { get; set; }
    public IEnumerable<SelectListItem> Values { get; set; }
}

and a controller that will populate this view model with values and hopefully in the POST action obtain the selected values in the view:
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            SelectedValues = new[] { "1", "3" },
            Values = new[]
            {
                new SelectListItem { Value = "1", Text = "item 1" },
                new SelectListItem { Value = "2", Text = "item 2" },
                new SelectListItem { Value = "3", Text = "item 3" },
            }
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        // model.SelectedValues will contain the ids of items that were checked
        // in the checkbox list
    }
}

and then a view:
@model MyViewModel

@using (Html.BeginForm())
{
    @Html.CheckBoxListFor(x => x.SelectedValues, Model.Values, null)
    <button type="submit">OK</button>
}

OK, so far so good. The last part is to try to implement this CheckBoxListFor helper. Obviously depending on your specific requirements and context there could be many possible ways to do this (see my remark in the beginning of the answer). So here's just some sample implementation that could get you started:
public static class HtmlExtnsions
{
    public static IHtmlString CheckBoxListFor<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression,
        IEnumerable<SelectListItem> selectList,
        object htmlAttributes
    )
    {
        var name = ExpressionHelper.GetExpressionText(expression);
        string fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
        var values = GetModelStateValue(htmlHelper.ViewData, fullHtmlFieldName, typeof(string[]));
        if (values == null)
        {
            values = htmlHelper.ViewData.Eval(fullHtmlFieldName);
        }

        if (values != null)
        {
            var collection =
                from object value in values as IEnumerable
                select Convert.ToString(value, CultureInfo.CurrentCulture);
            var hashSet = new HashSet<string>(collection, StringComparer.OrdinalIgnoreCase);
            var list = new List<SelectListItem>();
            foreach (var item in selectList)
            {
                item.Selected = ((item.Value != null) ? hashSet.Contains(item.Value) : hashSet.Contains(item.Text));
                list.Add(item);
            }
            selectList = list;
        }

        var sb = new StringBuilder();
        foreach (var item in selectList)
        {
            var checkbox = new TagBuilder("input");
            checkbox.Attributes["type"] = "checkbox";
            checkbox.Attributes["name"] = fullHtmlFieldName;
            checkbox.Attributes["value"] = item.Value;
            checkbox.GenerateId(fullHtmlFieldName);
            if (item.Selected)
            {
                checkbox.Attributes["checked"] = "checked";
            }
            sb.Append(checkbox.ToString(TagRenderMode.SelfClosing));
            sb.Append(item.Value);
        }

        return new HtmlString(sb.ToString());
    }

    private static object GetModelStateValue(ViewDataDictionary viewData, string key, Type destinationType)
    {
        ModelState modelState;
        if (viewData.ModelState.TryGetValue(key, out modelState) && modelState.Value != null)
        {
            return modelState.Value.ConvertTo(destinationType, null);
        }
        return null;
    }
}


text:
Q: Visual Studio 2017 - Can't turn off "Live Testing" Help - I made the mistake of turning on live testing, and now I can't turn it off or disable it.
Specs
Visual Studio 2017 version 15.5.7
NUnit v3.9.0
NUnit3TestAdapter v3.9.0
Symptoms.
Once I do a "Test | Run | All Tests" I can no longer run my tests.  I'm assuming that it's because "they're already running."
This is frustrating because I have 4 integration tests that I have "Ignored" out, but once I have run all tests one time, I can't just comment out the Ignore line and run the test on its own.
By commenting it out and hitting F6 to rebuild, it will run ALL of my tests again.
Nice feature, but I don't like it.  I want to turn it off.
In theory I should be able to turn it off by clicking
"Test | Live Testing | Stop"
but that doesn't change the behavior much.
The difference between Start and Stop is the following:
Start - I comment or uncomment the ignore and the tests runs immediately.
Stop - I comment or uncomment the ignore and the tests run when I build.
Apparently I'm the only one having issues, because searching for:
Visual Studio Disable "Live Testing"
gets me a whole lot of response on how to turn it on and make it work and nothing on how to disable it.

A: I think the answer is in your original post.
In the Visual Studio 2017 menu bar, go Test >> Live Unit Testing >> Stop
If this doesn't work for you, perhaps try checking for Visual Studio Updates. I'm on 15.6.7 and doing this does indeed turn off Live Unit Testing.


text:
Q: Laravel - Name from foreign key doesn't show in my blade I'm making a project where I use the foreign key from a shop in products. The foreign key works but when I want to show it in my blade by using $product->shop_id->shop_name, it gives a blank spot. My foreign key is named 'shop_id'.Product page without shop name
This is my code:
ProductController:
public function getProduct()
{
   $products = DB::table('products')->inRandomOrder()->simplePaginate(15);

   return view('product', ['products' => $products]);
}

product.blade.php
 @foreach($products as $product)

                    product_image}}" alt="" class="image image-full"/>

{{$product->product_name}}

Inhoud: {{$product->product_volume}}

€{{$product->product_price}}

Winkel:{{$product->shop_id->shop_name}}

                product_url}}" class="button button-small">Bekijk product

Product Model
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    /**
     * @var string
     *
     *
     */
    protected $table = 'products';

    /**
     * @var array
     *
     *
     */
    protected $fillable = [
        'product_name', 'product_volume', 'product_price', 'product_url', 'product_image',
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     *
     *
     */

    public function shop()
    {
        return $this->hasOne('App\Shop', 'shop_id');
    }

}

Shop model
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Shop extends Model
{
    use HasFactory;

    /**
     * @var string
     *
     *
     */
    protected $table = 'shops';

    /**
     * @var array
     *
     *
     */
    protected $fillable = [
        'shop_name',
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function product()
    {
        return $this->belongsTo('App\Product', 'shop_id')->withDefault();
    }

}

A: Your provided wrong namespace and keys in your relationship declaration. You must change as in example below to be able use these methods
Product.php
public function shop()
{
    return $this->hasOne(Shop::class, 'shop_id', 'shop_id');
}

After that you can access product shop using

Winkel: {{ $product->shop->shop_name }}


text:
Q: Find all grouped records where a records are newer than a certain type of record That would be the intermediary output I need:
Id1, Id2, Type,   Date
1,   2,    test,  2010-10-10
1,   3,    stage, 2010-05-05
1,   2,    stage, 2010-12-12
1,   3,    test,  2010-04-04
1,   3,    prod,  2010-12-31

From that point I want to know how many grouped (Id1,Id2) records do exist after the record with Type = 'test'.
for the above I would get this final output:
Id1, Id2, Count
1,   2,   1
1,   3,   2

What sql query would that be?
The use case would be to find all those records who never made it to a later stage than type = "test"

A: You have to get the value of Date for "test" Type for corresponding ID1 and ID2 and then make a count of records. Like this:
drop table if exists dbo.LaterThan;

create table dbo.LaterThan (
    Id1 int
    , Id2 int
    , Type varchar(100)
    , Date date
);

insert into dbo.LaterThan (Id1, Id2, Type, Date)
values (1, 2, 'test', '20101010')
    , (1, 3, 'stage', '20100505')
    , (1, 2, 'stage', '20101212')
    , (1, 3, 'test', '20100404')
    , (1, 3, 'prod', '20101231')

select
    lt.Id1
    , lt.Id2
    , count(case when lt.Date >= test.Date and lt.Type <> 'test' then 1 else null end) as Cnt
from dbo.LaterThan lt
    outer apply (
            select
                top (1)
                tlt.Date
            from dbo.LaterThan tlt
            where lt.ID1 = tlt.Id1
                and lt.ID2 = tlt.Id2
                and tlt.Type = 'test'
    ) test
group by lt.Id1, lt.Id2

A: SELECT x.Id1, x.Id2, x.[Date],
       CountAfter = (
           SELECT COUNT(*) FROM dbo.Table1 AS y
           WHERE x.Id1=y.Id1 AND x.Id2=y.Id2
           AND y.[Date]>x.[Date]) -- After
FROM dbo.Table1 AS x
WHERE x.[Type]='test'

Note: I've assumed that every {Id1, Id2} pair of values have only one row with Type='test'.
Edit 1: If you want to filter all rows with CountAfter = 0 then
SELECT x.Id1, x.Id2, x.[Date]
FROM dbo.Table1 AS x
WHERE x.[Type]='test'
AND NOT EXISTS (
     SELECT * FROM dbo.Table1 AS y
     WHERE x.Id1=y.Id1 AND x.Id2=y.Id2
     AND y.[Date]>x.[Date])

or (but it isn't an optimal solution)
SELECT ...
FROM (
... insert main query ...
) AS mq
WHERE mq.CountAfter = 0

A: I think the query will be,
SELECT Id1, Id2, count(Id1) from <table_name> where Type = 'test' group by Id1, Id2;

A: You can do it this way:
SELECT
    t.Id1,
    t.Id2,
    COUNT(*) AS Count
FROM (SELECT Id1, Id2, Date FROM Table WHERE TYPE = 'test') t
LEFT JOIN Table tt
    ON tt.Id1 = t.Id1 AND tt.Id2 = t.Id2 AND t.Date <= tt.Date
    AND tt.Type <> 'Test'
GROUP BY t.Id1, t.Id2

Example:
DECLARE @table TABLE (Id1 int, Id2 int, [Type] varchar(10),[Date] date)
INSERT INTO @table VALUES (1,   2,    'test',  '2010-10-10'),
(1,   3,    'stage', '2010-05-05'),
(1,   2,    'stage', '2010-12-12'),
(1,   3,    'test',  '2010-04-04'),
(1,   3,    'prod',  '2010-12-31')

SELECT
    t.Id1,
    t.Id2,
    COUNT(*) AS Count
FROM (SELECT Id1, Id2, Date FROM @Table WHERE TYPE = 'test') t
LEFT JOIN @Table tt
    ON tt.Id1 = t.Id1 AND tt.Id2 = t.Id2 AND t.Date <= tt.Date
    AND tt.Type <> 'Test'
GROUP BY t.Id1, t.Id2

A: There might be various dates for similar (Id1, Id2) records.
So If all you need is a count of the records with this (Id1, Id2) pair irrespective of Date field then this will work for you.
SELECT T.Id1,T.Id2,COUNT(*) AS Count
FROM
   (SELECT Id1, Id2, Date
    FROM TABLENAME
    WHERE TYPE = 'test') AS T
GROUP BY
T.Id1, T.Id2

Otherwise, you need to add the Date field in GROUP BY clause.


text:
Q: jQuery .append() not working with jQuery File Upload I'm using jQuery File Upload and on success I'm trying to append hidden input field to a form but it is not working, the element is not being appended.
jupload.fileupload({
    // Uncomment the following to send cross-domain cookies:
    //xhrFields: {withCredentials: true},
    url: '/content/upload',
    done: function (e, data) {
            $("#fileupload").append('<input type="hidden" name="uploaded_files[]">');

        }
});

HTML:
<form action="create-submit" id="fileupload" method="POST" enctype="multipart/form-data">
...
</form>


text:
Q: Counterexample that $a\in G$, $a^n\notin H$, for $H$ a subgroup of finite index $n$ in $G$. Let $G$ be a group and $H$ a subgroup of finite index $n$. Give a counterexample that $a\in G$, $a^n\notin H$ (although I can prove that there exists $k\in\{1,2,\dots,n\}$ such that $a^k\in H$).
Really do not know how to construct the counterexample...
Thanks.

A: Let $S_4$ be a symmetric group with $4$ letters and $H=\langle (1,2,3),(1,2)\rangle$. It is not hard to see that $[G:H]=4$.
Now, consider $(2,3,4)\in S_4$. Obviously, we have $(2,3,4)^4=(2,3,4)\notin H$.

A: I would suggest you to go through following exercise :

If $H\unlhd G$ and $[G:H]=n$ then $g^n\in H$ for all $g\in G$.

Now, If you  see the proof of this, you would see that you can not relax normality of $H$.
Can you find some group with  a subgroup which is not Normal?
Will that be sufficient?


text:
Q: Unable to invoke Build target using msbuild command line on a solution file I have a solution with many projects organized in solution folders. I am trying to invoke Build target on a project of the solution using solution .sln file. The msbuild errs out saying Build target is not available in the said project. I can invoke Clean target, Rebuild target on the same project, but not build.
Wondering what I am doing wrong.
Below is the command line that I am using:

msbuild ..\Galaxy.sln /p:Configuration=Debug /p:"Platform=Any CPU"
/t:"DataTools\CLIUtils:Build"

The error:
error MSB4057: The target "DataTools\CLIUtils:Build" does not exist in the project. [snip\Galaxy.sln]
I am using Visual Studio 2019. I also checked https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2015/msbuild/how-to-build-specific-targets-in-solutions-by-using-msbuild-exe?view=vs-2015 which describes target invocation for solutions. This looks like a bug to me.

A: We can produce an MSBuild file named .sln.metaproj use this method and check this file we can see targets like Clean, Rebuild, Publish, Restore but not Build target.

You can try CoreBuild target, it works in my test:
msbuild ..\Galaxy.sln /p:Configuration=Debug /p:"Platform=Any CPU" /t:"DataTools\CLIUtils:CoreBuild"


text:
Q: gcc doesn't compile C How To Program 'create a random access file' tutorial The tutorial on File Processing in C How To Program 6th Edition (Chapter 11
Fig. 11.11) creates a random access file sequentially. fwrite and fread are used in the code to create 100 blank records using structs.
The problem is that after compiling using gcc:
gcc myprogram.c -o myprogram
Why is 'myfile.dat' (using gedit) opening with the following error message:

The file you opened has some invalid characters. If you continue editing this file you could corrupt this document.Character Encoding: Current Locale(UTF-8)

Is gcc the issue or gedit? Can someone please recommend a compiler or text editor suitable for C programming in Linux. Thank you.


text:
Q: How to implement 'SELECT column_default' in a QGIS processing script? When creating a PostgreSQL serial value using the QGIS DB-Manager, the sequence is named /*schema*/./*table*/_/*column*/_seq.

I've created a processing script that drops the default value/sequence if there is no need for it:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#--------- define Interface
##PostgreSQL/PostGIS Tools=group
##Drop default value/sequence=name
##PostgreSQL_Table=vector
##Column=field PostgreSQL_Table

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import *

from qgis.core import *
from qgis.gui import *
from qgis.utils import *

import psycopg2

#get the parameters for the tpg table into a directory
#get the table
pg_table = processing.getObject(PostgreSQL_Table)
#create empty dictionary for key/value pairs of the tables connection parameters
db_params = {}
db_params['clmn'] = Column
#iterate over connection string
progress.setInfo(20*'-' + '  Connection parameters')
for param in pg_table.dataProvider().dataSourceUri().split(' '):
    key_val = param.split('=')
    progress.setInfo(str(key_val))
    try:
        #set key/value pair
        db_params[key_val[0]] = key_val[1]
    except:
        pass

#generate the sql statement string
#the text in round brackets are the keys from the db_params dictionary created above
#the values belonging to the keys are inserted into the string
progress.setInfo(20*'-' + '  SQL statement')
sql = """ALTER TABLE %(table)s
ALTER COLUMN %(clmn)s DROP DEFAULT;
DROP SEQUENCE IF EXISTS %(table)s_%(clmn)s_seq;
COMMIT;""" % db_params
#remove double quotes
sql = sql.replace('"','')
progress.setInfo(sql)

#make connection string
constr = """dbname=%(dbname)s host=%(host)s port=%(port)s user=%(user)s password=%(password)s""" % db_params
progress.setInfo(20*'-' + '  DB Connection string')
progress.setInfo(constr)
#make db connection
con = psycopg2.connect(constr)
cur = con.cursor()
#execute the above created sql statement
progress.setInfo(20*'-' + '  Executing SQL statement ...')
cur.execute(sql)
progress.setInfo(20*'-' + '  ... done.')

I also want to drop the default value if the sequence is named different than /*schema*/./*table*/_/*column*/_seq? How can I implement the following SQL query in the processing script?
SELECT column_default
FROM information_schema.columns
WHERE (table_schema, table_name, column_name) = ('/*schema*/', '/*table*/', '/*column*/');

A: EDIT 3:
This code should include what you need to make your script work. Additional discussion is below in the earlier responses (after the line):
import psycopg2
import re

db_name = 'DB_NAME'
db_user = 'DB_USER'
db_password = 'DB_PASSWORD'

conn = psycopg2.connect("dbname={0} user={1} password={2}".format(db_name, db_user, db_password))

schema = 'public'
table_name = 'temp_table'
column_name = 'gid'

with conn.cursor() as curs:
    # retrieve name of sequence from column default
    sql = """
            SELECT column_default FROM information_schema.columns
            WHERE table_schema = %s
            AND table_name = %s
            AND column_name = %s;
          """
    curs.execute(sql, (schema, table_name, column_name))

    seq_name = curs.fetchone()
    # Extract the sequence name from the result tuple.
    # need to remove result from list, only get text between quotes,
    # and then remove that from a list format for a string to put in SQL.
    seq_name = re.findall(r"'(.*?)'", seq_name[0])[0]

    # drop default from column, essentially converting serial to integer
    sql2 = """
            ALTER TABLE {0}.{1} ALTER COLUMN {2} DROP DEFAULT;
           """.format(schema, table_name, column_name)
    curs.execute(sql2)

    # drop sequence from database
    sql3 = """
            DROP SEQUENCE IF EXISTS {0}.{1};
           """.format(schema, seq_name)
    curs.execute(sql3)

    # commit changes if everything went OK
    conn.commit()

---------------------------------------------------------------------------
I'm not following everything you want to do, but may be able to get the conversation started on your ending question about how to execute the select statement. The following code returns [('false',)] on one of my databases - a tuple inside a list. You will need to do some indexing and conversion if you want this as Python False rather than a string in a tuple in a list.
You will need to assign the the variables in your script. Since you are using psycopg2, it will escape on %s, passed into the execute as tuples.
import psycopg2

db_name = 'DB NAME'
db_user = 'DB_USER'
db_password = 'DB_PASSWORD'

conn = psycopg2.connect("dbname={0} user={1} password={2}".format(db_name, db_user, db_password))

schema = 'topology'
table_name = 'topology'
column_name = 'hasz'

with conn.cursor() as curs:
    sql = """
            SELECT column_default FROM information_schema.columns
            WHERE table_schema = %s
            AND table_name = %s
            AND column_name = %s;
          """
    curs.execute(sql, (schema, table_name, column_name))

    print(curs.fetchall())

As an aside, if you use Python string formatting with the {} brackets in addition to the %s, you can develop a lot of flexibility in letting your script modify some parts of the SQL while still letting psycopg2 take care of escaping and date formats, etc based on the %s.
It sounds like you plan to incorporate the select with some SQL to delete or update rows, but I don't follow your plan quite well enough to take a stab at that.
EDIT:
While troubleshooting with psycopg2, I often find it useful to use a line like
print(curs.mogrify(sql, (schema, table_name, column_name)))

and comment out the actual execute statement. Mogrify will print out the SQL string that is being sent to Postgres, with all the text escaped, date formatting, etc. You can easily copy the text into pgAdmin for more direct experimenting without wondering if the problem is in SQL or Python.
EDIT 2:
From what I can put together, the only significant link between a column in a table and a sequence in Postgres is within the default value. The sequence lives as an object separate from the table and column itself. Therefore, when you drop the default from the column, you are removing the one thing that tells you what sequence the column is tied to. You should get this information prior to dropping the default. The SQL to return the column_default is above.
Once you execute this statement with a cursor and then fetchone, you will have a string similar to "nextval('background.temp_table_gid_seq'::regclass)". From here, you can use something like the Python in this post to extract the name of the sequence and store it in a Python variable rather than printing like my code above. Then, after you drop the default, you can use the variable to drop the sequence.
In the end, you will be executing three SQL statements:

*

*Find the name of the sequence from the column default.

*Drop the column default, like you have done with ALTER COLUMN...

*Drop the sequence using the result from the first SQL execution.

In psycopg2, each of these will be its own curs.execute() call. If all of that goes well, you can then commit the changes with conn.commit() after completing all three executes. You should be left with an integer primary key that has no default value and cannot be null, and the sequence should be deleted.
Disclaimer: there doesn't seem to be a whole lot on Google, etc. about going from a serial type to integer type. Most people are going the other way. Here is one post I found that is older but provides some information. I think you are safer querying the information_schema. I am not the best person to ask what other behind the scenes links or impacts may be caused by what you are doing, but I think the process above will get you to where you can delete the sequence even if it has been renamed.


text:
Q: HTML5 Video option Now it may seem like a dumb question but for in regard to html5 video, is it possible to show the video poster once you navigate away from the page?
Example, I have a JQM page that has a html video in it with a poster assigned to it. When I navigate away from the page, I have a little script that sets the play time back to 0 and pauses the video
<script>
 var video = document.getElementById("video");
 $("#trigger").bind("click", function(){
        video.pause();
        video.currentTime = 0;});
</script>

This works but I also want to be able to display the video poster as well. Is there a way to do this though my javascript?

A: Just set the poster via javascript anew to "restore" the poster:
<script>
var video = document.getElementById("video");
$("#trigger").bind("click", function(){
    video.pause();
    video.currentTime = 0;
    video.poster = "yourPoster.png";});
</script>


text:
Q: Limiting user selections with mobiscroll 2.5.0 I am using this library: mobiscroll.custom-2.5.0.min.js. How do I set limits to deny users' selecting past dates?
My code:
xtype:'panel',
layout:'hbox',
            width: (screenWidth-(84+24+55))/2,
            cls: 'paymentsSectionDetailsDate',
            items:[{
             xtype:'panel',
             html:'
'+txt_PayOn+'
',
             width: 80
             },{
             xtype: 'button',
             text:txt_select_date,
             name: 'BillPayDetailsForm_date',
             id:'BillPayDetailsForm_date',
             cls: 'paymentsSectionDetailsDateTextButt',
             listeners:{
              tap : function()
              {
               inputNumber=4;
               $('#dateIos').fadeIn("slow");
              }
             }

            }]

A: I am not familiar with mobiscroll, could you use a datepicker? It has 'yearFrom' and 'yearTo' configuration options. You might be able to use a listener to get the data into mobiscroll.


text:
Q: Core Data issue: unrecognized selector when I update the data model I have a project that manages a database with Core Data. This DB works fine, but I need to add a new field in a table. When I create a new version of the data model, add the field and back to create the NSManagedObject subclasses (autogenerated). the application finishes with an error about "unrecognized selector" in the new field that I added.
The new autogenerated table is the next:
File.h
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@class Session;

@interface File : NSManagedObject

@property (nonatomic, retain) NSDate * date;
@property (nonatomic, retain) NSString * fileType;
@property (nonatomic, retain) NSString * pathFile;
@property (nonatomic, retain) NSString * name;     // NEW FIELD
@property (nonatomic, retain) Session *session;

@end

File.m
#import "File.h"
#import "Session.h"

@implementation File

@dynamic date;
@dynamic fileType;
@dynamic pathFile;
@dynamic name;      // NEW FIELD
@dynamic session;

@end

These are all the relationships in the database:

And this is the creation of the entity in the code:
File *newFile = [File createEntity];
newFile.pathFile = pathFile;
newFile.fileType = @"Video";
newFile.name = @"Video 1";
newFile.date = [[NSDate alloc] init];
if ([sessionPicker selected] < sessions.count) {
     newFile.session = [sessions objectAtIndex:[sessionPicker selected]];
}

[[NSManagedObjectContext defaultContext]saveToPersistentStoreWithCompletion:nil];

And the error that I mentioned before is the next (only fails in the new field, if I comment the line to add the name of the file, the creation works fine):
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[File setName:]: unrecognized selector sent to instance 0xc667770'

I tried to remove the references to datamodel and added them again, but this fails too. Also, I tried to clean the project and remove the app of the simulator, but this fails too.
Any solution or suggestion, please?
Edit:
NSLog output
(lldb) po [[newFile entity] properties]
<__NSArrayM 0xc6f7340>(
(<NSAttributeDescription: 0xc2ac350>), name date, isOptional 1, isTransient 0, entity File, renamingIdentifier date, validation predicates (
), warnings (
), versionHashModifier (null)
 userInfo {
}, attributeType 900 , attributeValueClassName NSDate, defaultValue (null),
(<NSAttributeDescription: 0xc2ac3a0>), name fileType, isOptional 0, isTransient 0, entity File, renamingIdentifier fileType, validation predicates (
), warnings (
), versionHashModifier (null)
 userInfo {
}, attributeType 700 , attributeValueClassName NSString, defaultValue (null),
(<NSAttributeDescription: 0xc2ac3f0>), name pathFile, isOptional 0, isTransient 0, entity File, renamingIdentifier pathFile, validation predicates (
), warnings (
), versionHashModifier (null)
 userInfo {
}, attributeType 700 , attributeValueClassName NSString, defaultValue (null),
(<NSAttributeDescription: 0xc2ac440>), name syncID, isOptional 1, isTransient 0, entity File, renamingIdentifier syncID, validation predicates (
), warnings (
), versionHashModifier (null)
 userInfo {
}, attributeType 700 , attributeValueClassName NSString, defaultValue (null),
(<NSRelationshipDescription: 0xc2acc50>), name session, isOptional 1, isTransient 0, entity File, renamingIdentifier session, validation predicates (
), warnings (
), versionHashModifier (null)
 userInfo {
}, destination entity Session, inverseRelationship files, minCount 0, maxCount 1, isOrdered 0, deleteRule 1
)

A: Finally, I achieved solve the problem: in the "Build phases" (in the properties of the project), I delete a copy of the bundle of the DB and back to added.
The problem was that this bundle was generated in the Derived Data folder, and although I will create new copies, this file is keeping deprecated. When I deleted all files and folders of Derived Data, xCode shows me several errors about this folder and related to the bundle. So, I build the datamodel again, copy the new bundle in the project, and add again (after delete the old bundle) in the "Build phases" of the project.

A: You cannot simply upgrade the Database schema in Core Data without migrating it. This provides a "mapping" for the app to follow. Read through this Apple Doc for more info, and instructions on how to migrate.


text:
Q: Showing text horizontally to image with multiple images verticaaly alliagned I want to show text horizontally to image with multiple images vertically alliagned .
Thislayout is not throwing any exception but only one image is coming ..other two images are not coming up in my layout .
my layout xml :
<?xml version="1.0" encoding="utf-8"?>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"

     >
<ScrollView  android:id="@+id/scrollviewmotherregister" android:layout_width="fill_parent" android:layout_height="fill_parent"
android:layout_marginTop="2dip"  android:layout_marginBottom="2dip">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
 >
    <ImageView
        android:id="@+id/icon"
        android:layout_width="90dip"
        android:layout_height="90dip"
        android:layout_marginLeft="4dip"
        android:layout_marginRight="10dip"
        android:layout_marginTop="20dip"
        android:src="@drawable/icici"
         >
    </ImageView>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
     android:orientation="vertical"
     >

     <TextView

        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </TextView>
      <TextView
        android:id="@+id/label2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ICICI Bank"
        android:textSize="20dip" >
    </TextView>

      <TextView
        android:id="@+id/label3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Timings : 9 AM to 5 PM"
        android:textSize="20dip" >
    </TextView>

     <TextView
        android:id="@+id/label5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:text="Contact Number : 9894198941"
        android:textSize="20dip" >
    </TextView>

    </LinearLayout>

    <ImageView
        android:id="@+id/indianbank"
        android:layout_width="90dip"
        android:layout_height="90dip"
        android:layout_marginLeft="4dip"
        android:layout_marginRight="10dip"
        android:layout_marginTop="20dip"
        android:src="@drawable/hdfc"
         >
    </ImageView>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
     android:orientation="vertical"
     >

     <TextView

        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </TextView>
      <TextView
        android:id="@+id/label2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="HDFC Bank "
        android:textSize="20dip" >
    </TextView>

      <TextView
        android:id="@+id/label3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Timings : 10 AM to 6 PM"
        android:textSize="20dip" >
    </TextView>

     <TextView
        android:id="@+id/label5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:text="Contact Number : 9740999443"
        android:textSize="20dip" >
    </TextView>

    </LinearLayout>

     <ImageView
        android:id="@+id/axisbank"
        android:layout_width="90dip"
        android:layout_height="90dip"
        android:layout_marginLeft="4dip"
        android:layout_marginRight="10dip"
        android:layout_marginTop="20dip"
        android:src="@drawable/axis"
         >
    </ImageView>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
     android:orientation="vertical"
     >

     <TextView

        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </TextView>
      <TextView
        android:id="@+id/label2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Axis Bank"
        android:textSize="20dip" >
    </TextView>

      <TextView
        android:id="@+id/label3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Timings : 9:30 AM to 5:30 PM"
        android:textSize="20dip" >
    </TextView>

     <TextView
        android:id="@+id/label5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Contact Number : 9003245643"
        android:textSize="20dip" >
    </TextView>

    </LinearLayout>

</LinearLayout>
</ScrollView>
</LinearLayout>

Problem :
I am getting first images but other two images are not showing up .

A: Take a scroll view inside that linear layout of scroll view take a different linear horizontal layout,,,than on each orizontal layout take one image +text view...

A: Every LinearLayout containing the TextViews set each layout's Width to WRAP_CONTENT from the FILL_PARENT
Cause the first LinearLayout with TextViews are showing up..and after that the whole space is taken by the first LinearLayout - that's Fill_Parent so..need to change it to Wrap-Content.
This is what it looks like to me the problem.

A: Try RelativeLayout under LinearLayout. RelativeLayout has all aligned properties that will help your target.


text:
Q: listenglobal renderer event trigger in angular 6 testing script I want to test my RolesComponent listenGlobal Renderer method. RolesComponent code below.
import { Component, OnInit, Renderer, AfterViewInit } from '@angular/core';
import { Router } from '@angular/router';

import { AhanaService } from '../../services/ahana.service';

@Component({
    selector: 'app-roles',
    template: '
<button roleId="1">test click</button>
',
    styleUrls: ['./roles.component.css']
})
export class RolesComponent implements AfterViewInit {

    constructor(public router: Router, private ahanaService: AhanaService, private renderer: Renderer) {}

    ngAfterViewInit(): void {
        this.renderer.listenGlobal('document', 'click', (event) => {
            if (event.target.hasAttribute("roleId")) {
                var roleId = event.target.getAttribute('roleId')
                // console.log('/configuration/update-role/' + roleId)
                this.router.navigate(['/configuration/update-role/' + roleId]);
            }
        });
    }

}

how to convert RolesComponent.spec.ts and ngAfterViewInit(): void {        this.renderer.listenGlobal('document', 'click', (event) => { method call.

A: If you want to test that your click listener is behaving as expected, then you can manually call the ngAfterViewInit lifecycle hook from your test and assert that router.navigate() is called as expected. In order to do this, you can mock and spy on the router.navigate method and expect it to have been called with a particular url route. The result is very similar to this stack overflow answer.
import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { Router } from '@angular/router';
import { RolesComponent } from './roles.component';

describe('RolesComponent', () => {
  let component: RolesComponent;
  let fixture: ComponentFixture<RolesComponent>;
  const routerSpy = { navigate: jasmine.createSpy('navigate') }; // Create our router mock, which we will spy on

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ RolesComponent ],
      providers: [{ provide: Router, useValue: routerSpy }], // Register our mock router as a provider
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(RolesComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should register click listener', fakeAsync(() => {
    component.ngAfterViewInit(); // Call the lifecycle hook
    const button = fixture.debugElement.nativeElement.querySelector('button');
    button.click(); // "Click" the button
    tick();
    expect(routerSpy.navigate).toHaveBeenCalledWith(['/configuration/update-role/1']); // Assert that our mock was called
  }));
});


text:
Q: Jupyter notebook does not rendered with sphinx I am using sphinx to document a python project. I want to add some tutorial as *.ipynb.
I have a problem about how to render jupyter notebook. Here is my code.
I created a docs folder and all sphinx command will run under this folder. Below is the structure of my roject
demos/
src/
docs/
  source/
     config.py
     demos.rst
     modules.rst
     src.rst
     index.rst
     ....
  build/

here is the content of demos.rst
Demonstration
=============

demos.tuto1
----------------------
demos/tuto1.ipynb

demos.tuto2
-------------------
demos/tuto2.ipynb

here is the content of the  index.rst
Welcome to my python project
============================

.. toctree::
   :maxdepth: 2
   :caption: Contents:

   modules
   src
   demos

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

In config.py file:
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.autodoc', 'nbsphinx']
nbsphinx_execute = 'never'
nbsphinx_allow_errors = True
source_suffix = ['.rst', '.ipynb']
html_theme = 'sphinx_rtd_theme'

When I run make html I render everything except the jupyter notebook.
What does I miss?

A: You confused syntax between two different contexts.
If you have a toctree entry context, such as in your index.rst, then you can do this:
.. toctree::
    :maxdepth: 2
    :caption: Contents:

    modules
    src
    demos/tuto1.ipynb
    demos/tuto2.ipynb

If you want to have a separate "normal reST file", then you can do this:
.. _link: demos/tuto1.ipynb


text:
Q: Jackson annotations tutorials? Does somebody aware of some good jackson annotations tutorials? Especially, how do you parse json array using jackson annotations?
 Suppose I have json like this:
{
...
"item1": "aaa",
"item2": "bbb",
"fl": [
     {
         "item3": "ccc",
         "item4": "ddd"
      }
  ]
}

How does one parse json including array using jackson annotations?

A: I assume you are asking about how to map JSON into Java objects (parsing typically refers to lower level activity of decoding JSON content stream into another representation, which may or may not be set of objects).
With Jackson (as well as many other libs, Genson, GSON etc), you have choice of either binding it into a POJO with matching structure, say:
public class Value {
  public String item1; // or some other type one can bind from JSON String
  public String item2; // can alternatively use getters/setters instead of public fields
  public List<EntryType> f1;
}
public class EntryType {
  public String item3;
  public String item4;
}

or reading it as a Tree representation like so:
JsonNode rootNode = mapper.readTree(inputSource);

In latter case, you need to traverse the tree nodes to find your data.
As to annotations: you only need to use annotations if you need to change default properties of binding; like mapping between JSON Object fields and POJO property names.
For Jackson-specific configuration including some of annotations, see Jackson-databind github project: https://github.com/FasterXML/jackson-databind/

A: There are three ways to parse json using Jackson -

*
* Using a streaming Parser. (http://www.studytrails.com/java/json/java-jackson-json-streaming.jsp)

*Parsing Json to a tree model - http://www.studytrails.com/java/json/java-jackson-json-tree-parsing.jsp

*Data binding with our without annotations - data binding, data binding with filters, Polymorphic data binding


text:
Q: How to enable spark UI for Glue Interactive notebooks? Is there any way I can enable spark UI (by storing the logs in s3) while running a glue job using interactive notebook?

A: For the Notebook, you have to add %%configure
{
"--enable-spark-ui": "true",
"--spark-event-logs-path": "s3://path/here"
}


text:
Q: why when try upload a large video, app engine gcloud throws error 413 entity too large? I have an API rest with spring boot and with it I upload a video, the question is that when I run it in my local environment, it runs perfect for long videos and actually uploads them to my storage in gcloud, but when I upload to production for this type video throws error 413 entity too large.
any idea why it works locally and not in production
this is the controller:
@RequestMapping(value = "/{videoId}/upload", method = RequestMethod.POST )
public ResponseEntity<Object> uploadTest(@PathVariable Long videoId, @RequestParam("file") MultipartFile file) {
    try {
        return ResponseEntity.ok(uploadVideo(videoId, file));
    } catch (Exception e) {
        return processException(e);
    }
}

this function is called from controller:
public String uploadVideo(MultipartFile fileStream, final String folder, final String bucketName) throws IOException, ServletException {

InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("project.json");

storage = getInstance(resourceAsStream);

        String blobName = fileStream.getName();
        BlobId blobId = BlobId.of(bucketName, blobName);
        byte[] content = fileStream.getBytes();

        DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS");
        DateTime dt = DateTime.now(DateTimeZone.UTC);
        String dtString = dt.toString(dtf);
        String extension = fileStream.getOriginalFilename().substring(fileStream.getOriginalFilename().lastIndexOf(".") + 1);
        final String fileName = fileStream.getName() + dtString + "." + extension;

        BlobInfo blobInfo = BlobInfo.newBuilder(bucketName, folder + "/" + fileName)
                                    .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER))))
                                    .build();
        try (WriteChannel writer = storage.writer(blobInfo)) {
            try {
                writer.write(ByteBuffer.wrap(content, 0, content.length));
                return "https://storage.googleapis.com/" + bucketName + "/" + folder  + "/" + fileName;
            } catch (Exception ex) {
                System.out.println(ex.toString());
                throw new BadRequestException("Error uploading");
            }
        }
}

thank so much, for you help

A: App Engine (standard?) limits the request size to 32MB (link).
While it's understandable, I think it's not good practice to assume the dev server is a proxy for the production service.
I recommend you upload the files directly to Cloud Storage and consider use notifications to e.g. enqueue metadata of the object, ultimately then triggering your App Engine processing handler.


text:
Q: Flask/Python - How can I render this data in a text-form instead of list I am trying to get data from an calendar URL using flask. I have an URL which I am requesting data from. I am getting the output in a list which is not what I want. I want the data from the URL to be rendered in a text-form (like https://www.w3schools.com/html/html_forms.asp) so I can edit the results I get. Right now I can't edit it since its in a
* list, like this word.
I want it to be something like this "Key : value (the value is in a text-form)".
My current code iterates through the data and renders it in a list instead of a form.
import requests
from flask import Flask
from flask import render_template

app = Flask('__name__')

def get_json(id):
url =             'https://cloud.timeedit.net/ltu/web/schedule1/{0}.json'.format(id)
r = requests.get(url)
return r.json()['reservations']

@app.route('/')
def index():
reservations = get_json('ri107357055Z76Q506656Q65yZ075W2313Y63Q5Q')
return render_template('reservations.html', reservations=reservations)

if __name__ == '__main__':
app.run()

HTML:
e {% for reservation in reservations %}

{% for key in reservation %}
    {% if key == 'columns' %}

{{ key }} -

        {% for item in reservation[key] %}
            {% if item %}

{{ item }}

            {% endif %}
        {% endfor %}

    {% else %}

{{ key }} - {{ reservation[key] }}

    {% endif %}
{% endfor %}

{% endfor %}

A: see if this works for you,
Only need to make changes in the html file
{% for reservation in reservations %}

{% for key in reservation %}
    {% if key == 'columns' %}

{{ key }} -

        {% for item in reservation[key] %}
            {% if item %}

{{ item }}

            {% endif %}
        {% endfor %}

    {% else %}
       <form action="/action_page.php">
          {{ key }} - s <input type="text" name="lname", value="{{ reservation[key] }}">

      </form>
    {% endif %}
{% endfor %}

{% endfor %}

Output


text:
Q: Remove Outline on Right-clicked Rows in SwiftUI Mac App List I'm building a macOS app with SwiftUI, and I'm trying to remove (or even cover up) the border added to a List item when I right-click it.
Here it is by default:

Now with a right-click and a contextMenu view modifier:

I figured this is an NSTableView quirk, so I tried the approaches in these three Stack Overflow posts:

*

*Customize right click highlight on view-based NSTableView

*NSTableView with menu, how to change the border color with right click?

*Disabling the NSTableView row focus ring

*NSTableView: blue outline on right-clicked rows
I couldn't get any of those to work, and that may be due to the fact that I can't subclass an NSTableView, but can only override its properties and methods with an extension. Here's what I have so far that successfully removes the default table background and such:
extension NSTableView{
  open override func viewDidMoveToWindow() {
    super.viewDidMoveToWindow()

    //Remove default table styles
    backgroundColor = NSColor.clear
    enclosingScrollView!.drawsBackground = false
    selectionHighlightStyle = .none
  }
}

Is there any way to remove that right-click border in SwiftUI? I'm even open to covering it with other views, but I can't seem to draw SwiftUI views in that space around the table cell.

A: I found a workaround for this. I put my List in a ZStack and then set its opacity to zero. I then built out a fully custom version of the same list, but using LazyVStack:
//Message List
ZStack{
  //Ghost list for keyboard control
  List($model.messages, id: \.self, selection: $model.selectedMessages){ $message in
    MessageItemView(message: $message)
  }
  .focusable()
  .opacity(0)

  //Custom UI for the above List
  ScrollView{
    ZStack{
      LazyVStack(spacing: 5){
        ForEach($model.messagesToday){ $message in
          MessageItemView(message: $message)
        }
      }
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity)
  }
}
.frame(maxWidth: .infinity, maxHeight: .infinity)

Each list is bound to the same model, so if I click a message to select it in the custom UI, the same thing gets selected in the invisible List. All the keyboard shortcuts that come with table use in a List look like they are working on the custom version.
So how does this solve my original problem? You can right-click on the custom MessageItemView and the default ring around the cell is invisible, but the contextMenu still works (it's defined inside my MessageItemView).
This isn't as elegant as I'd like, but it's nice to have 100% control over the UI but still get all the keyboard controls that come for free with a List.


text:
Q: Ionic toggle group check one item and uncheck the others I have created a toggle view to select available items in Ionic, and if anyone of the item were selected, I want to uncheck all the other items. I also have a scan function which allows me to dynamically update the items list
I'm fairly new to ionic, so I just have the following code in my settings.html
<ion-toggle ng-repeat="item in itemsList"
         ng-model="item.checked">
    {{ item.text }}
</ion-toggle>

and then I have created a simple settings.js:
(function () {
    'use strict';

    angular.module('i18n.setting').controller('Settings', Settings);
    SettingController.$inject = ['$scope'];

    function Settings($scope){
        $scope.settingsList = [
            {text: "item1", checked: true},
            {text: "item2", checked: false}
        ];
    }
})();

I know ng-model="item.checked" will do the job of changing the attribute $scope.settingsList.checked for me. But what I want to know this how to use it to check one items and uncheck all the other ones?

A: loop through all the items, set the checked state of all the values to false and then your html code must be:
<ion-toggle ng-repeat="item in settingsList"
                ng-model="item.checked"
                ng-checked="item.checked" style="border:1px solid #28a54c" ng-change="toggleChange(item)">
      {{ item.text }}
</ion-toggle>

Your Controller code
$scope.toggleChange = function(item) {
      if (item.checked == true) {
          for(var index = 0; index < $scope.settingsList.length; ++index)
              $scope.settingsList[index].checked = false;
          item.checked = true;
      } else {
        item.checked = false
      }
};

And it's better to use forEach in async environment.

A: Angular 2+ Version, Ionic 4
HTML

{{item.title}}

    <ion-toggle [(ngModel)]="item.checked" (ngModelChange)="ToogleChange(item.id)" color="success"></ion-toggle>

TS
public toogleConfig = [
    {id:0, title:'Recurrent', checked: false},
    {id:1, title:'One time', checked: false},
  ]

public ToogleChange(index:number) {
    this.toogleConfig.forEach(toogle => { toogle.checked = false; });
    this.toogleConfig[index].checked = true;
  }


text:
Q: Better solution for existing sql query I have table like this:
type       | date       | id
-----------------------------
1          | 2012-01-01 | 1
2          | 2012-01-01 | 2
1          | 2012-02-02 | 3
2          | 2012-02-02 | 4

I need to build query that will pick all "up-to-date" distinct values of type ( in this example it will be records with id's 3 and 4). Now i have this solution :
select * from test t1 where date =
(select max(date) from test t2 where t2.type = t1.type ) order by type, date desc

I am embarrassed by the presence of nested select, maybe there is more elegant solution ?

A: since you didn't mention the RDBMS you are using, try this one. will work on most RDBMS.
SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT  type, MAX(DATE) maxDAte
            FROM tableName
            GROUP BY type
        ) b ON a.type = b.type AND
                a.DATE = b.maxDate

*

*SQLFiddle Demo
or if you RDBMS supports Window Function
SELECT type, date, id
FROM
(
    SELECT type, date, id,
            ROW_NUMBER() OVER (PARTITION BY type
                                ORDER BY date DESC) rn
    FROM tableNAme
) s
WHERE rn = 1

*

*SQLFiddle Demo

A: In your particular example, this could work also:
select type, max(date), max(id)
from your_table
group by type

but notice that it will work only if you are absolutely sure that dates and ids are always increasing. If this is not the case, max(date) and max(id) could be on two different rows. Use this only if you know what you are doing! If not, there's nothing wrong with nested queries.


text:
Q: Valgrind not showing error regarding memory region overlap In the process of testing all kinds of dynamic memory-related errors using Valgrind (or to be specific, Memcheck), I came accross a situation where, I'm creating the memory overlap intentionally, but there is no error report from Valgrind/memcheck. Below are the codes used. Please share what I'm missing.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char * pOne;
    char * pTwo;

    pOne = (char *)malloc (24);
    pTwo = pOne + 4;
    strcpy (pOne, "Sourav Ghosh");
    printf("pOne = %s\npTwo = %s\n", pOne, pTwo);
    memcpy (pTwo, pOne, 16); //Overlapping issue should be here
    printf("pOne = %s\npTwo = %s\n", pOne, pTwo);

    free (pOne);
    return 0;
}

Compilation
[sourav@titan temp]$ gcc -g srvtest.c -o memory

Sample run and output
[sourav@titan temp]$ valgrind --leak-check=full ./memory
==6982== Memcheck, a memory error detector
==6982== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==6982== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==6982== Command: ./memory
==6982==
pOne = Sourav Ghosh
pTwo = av Ghosh
==6982== Conditional jump or move depends on uninitialised value(s)
==6982==    at 0x4006817: strlen (mc_replace_strmem.c:275)
==6982==    by 0xAD0C0D: vfprintf (in /lib/libc-2.5.so)
==6982==    by 0xAD6E82: printf (in /lib/libc-2.5.so)
==6982==    by 0x8048477: main (srvtest.c:15)
==6982==
pOne = SourSourSourSourSour
pTwo = SourSourSourSour
==6982==
==6982== HEAP SUMMARY:
==6982==     in use at exit: 0 bytes in 0 blocks
==6982==   total heap usage: 1 allocs, 1 frees, 24 bytes allocated
==6982==
==6982== All heap blocks were freed -- no leaks are possible
==6982==
==6982== For counts of detected and suppressed errors, rerun with: -v
==6982== Use --track-origins=yes to see where uninitialised values come from
==6982== ERROR SUMMARY: 2 errors from 1 contexts (suppressed: 12 from 8)
[sourav@titan temp]$

There is actually no information about the memory region overlap. As per the Valgrind manual, it should have showwn something like:
==27492== Source and destination overlap in memcpy(0xbffff294, 0xbffff280, 21)

What is the missing part in my case?
System information:
[sourav@titan temp]$ uname -r
2.6.18-194.el5PAE
[sourav@titan temp]$ gcc --version
gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-48)
[sourav@titan temp]$ ldd --version
ldd (GNU libc) 2.5
[sourav@titan temp]$ valgrind --version
valgrind-3.5.0

A: Thanks to @Hasturkun, the issue was with the compiler inlining memcpy() with a builtin. So, valgrind was not able to hook the memcpy() and catch the error.
Modified compilation
 [sourav@titan temp]$ gcc -g -fno-builtin srvtest.c -o memory

Modified Output
[sourav@titan temp]$ valgrind --leak-check=full ./memory
==19785== Memcheck, a memory error detector
==19785== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==19785== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==19785== Command: ./memory
==19785==
pOne = Sourav Ghosh
pTwo = av Ghosh
==19785== Source and destination overlap in memcpy(0x402602c, 0x4026028, 16)
==19785==    at 0x4007AE2: memcpy (mc_replace_strmem.c:482)
==19785==    by 0x80484B3: main (srvtest.c:14)
==19785==
pOne = SourSourav Ghosh
pTwo = Sourav Ghosh
==19785==
==19785== HEAP SUMMARY:
==19785==     in use at exit: 0 bytes in 0 blocks
==19785==   total heap usage: 1 allocs, 1 frees, 24 bytes allocated
==19785==
==19785== All heap blocks were freed -- no leaks are possible
==19785==
==19785== For counts of detected and suppressed errors, rerun with: -v
==19785== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 12 from 8)
[sourav@titan temp]$


text:
Q: Oracle Instant Client link error when building on OSX I am trying to compile a simple Oracle application on OS X and running into link issues. Any help would be appreciated.
#include <iostream>
#include <occi.h>

using namespace std;
using namespace oracle::occi;

Environment * env;
Connection * conn;

int main(int argc, char ** argv)
{
    env = Environment::createEnvironment(Environment::OBJECT);
    conn = env->createConnection("scott", "tiger", "//lcoalhost:1521/xe");
    Statement *stmt = conn->createStatement("SELECT COUNT(*) FROM TAB");
    ResultSet *rs=stmt->executeQuery();
    rs->next();
    string ntabs=rs->getString(1);
    cout << "Number of tables " << ntabs << endl;
    conn->terminateStatement(stmt);
    // Close connection etc
    env->terminateConnection(conn);
    Environment::terminateEnvironment(env);
    return 0;
}

I have the x64 oracle instant client installed in ~/oracle_client. I can connect to the database using sqlplus and python (cx_Oracle).
I am compiling the file with the following command
gcc main.cpp -I ~/oracle_client/sdk/include/ -L ~/oracle_client -locci -lclntsh

Below is the ld error I receive:
ld: warning: ignoring file <ORACLE_HOME >/libclntsh.dylib, file was built for unsupported file format ( 0x62 0x6f 0x6f 0x6b 0x 0 0x 0 0x 0 0x 0 0x6d 0x61 0x72 0x6b 0x 0 0x 0 0x 0 0x 0 ) which is not the architecture being linked (x86_64): <ORACLE_HOME>/libclntsh.dylib
Undefined symbols for architecture x86_64:
"std::allocator::allocator()", referenced from:
_main in ccWf4dno.o
"std::allocator::~allocator()", referenced from:
_main in ccWf4dno.o
"std::basic_ostream >::operator >& (*)(std::basic_ostream >&))", referenced from:
_main in ccWf4dno.o
"std::basic_string, std::allocator >::basic_string(char const*, std::allocator const&)", referenced from:
_main in ccWf4dno.o
"std::basic_string, std::allocator >::~basic_string()", referenced from:
_main in ccWf4dno.o
"std::ios_base::Init::Init()", referenced from:
__static_initialization_and_destruction_0(int, int)in ccWf4dno.o
"std::ios_base::Init::~Init()", referenced from:
___tcf_0 in ccWf4dno.o
"std::cout", referenced from:
_main in ccWf4dno.o
"std::basic_ostream >& std::endl >(std::basic_ostream >&)", referenced from:
_main in ccWf4dno.o
"std::terminate()", referenced from:
_main in ccWf4dno.o
"std::basic_ostream >& std::operator >(std::basic_ostream >&, char const*)", referenced from:
_main in ccWf4dno.o
"std::basic_ostream >& std::operator, std::allocator >(std::basic_ostream >&, std::basic_string, std::allocator > const&)", referenced from:
_main in ccWf4dno.o
"___gxx_personality_v0", referenced from:
Dwarf Exception Unwind Info (__eh_frame) in ccWf4dno.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status

A: Undefined symbols for architecture x86_64:
"std::allocator::allocator()", referenced from:
_main in ccWf4dno.o
[...]

All these undefined symbols are C++ runtime support library functions, unrelated to Oracle.  The simplest and best way to get GCC to bring these in is to link C++ code with the g++ command, not gcc:
g++ main.cpp -I ~/oracle_client/sdk/include/ -L ~/oracle_client -locci -lclntsh

The linker's architecture warnings about libclntsh.dylib are just warnings, so it's possible that the instant client you've installed contains the right architecture as well as the stuff it's complaining about.  In any case, having got rid of these spurious C++ runtime linking problems, you'll be in a better position to debug any remaining Oracle linking problems.

A: At first glance it looks like you either installed the 32-bit instant client, in which case you can only build 32-bit binaries and therefore need to add a -m32 flag to gcc; or you installed the 64-bit instant client and gcc is defaulting to 32-bit for some reason (such as an alias), in which case you can override with a -m64 flag.
Either way, your instant client appears to be the wrong architecture... and actually from the x86_64 in your error message, you're building in 64-bit mode, therefore you seem to have installed the 32-bit instant client. But you said in the question that you did install the 64-bit version, which you can verify (as you probably know) with:
$ file ~/oracle_client/libclntsh.dylib.11.1

... which will end with x86_64 if it is 64-bit. Since it isn't complaining about libocci.dylib it seems to be able to cope with that, suggesting a kind of hybrid installation. Presumably you've created symbolic links for libclntsh.dylib and libocci.dylib pointing to the full .11.1 versions. Is it possible that libclntsh.dylib is pointing to a 32-bit version in another directory; or that you'd copied it to that name as a 32-bit and then replaced everything with the 64-bit versions and missed the manually-copied file? What architecture does this show:
$ file ~/oracle_client/libclntsh.dylib

It still won't compile with that sorted out, but the remaining errors aren't Oracle related as far as I can tell... and as John Marshall pointed out, just switching the command from gcc to g++ resolves the remaining issues.
g++ -m32 main.cpp ...

... creates an a.out if the 32-bit instant client is installed/linked properly.
Just for comparison, using a 32-bit client with a 64-bit build fails:
$ g++ -m64 main.cpp -I ~/oracle_client32/sdk/include/ -L ~/oracle_client32 -locci -lclntsh
ld: warning: ignoring file /Users/alex/oracle_client32/libocci.dylib, file was built for unsupported file format ( 0xce 0xfa 0xed 0xfe 0x 7 0x 0 0x 0 0x 0 0x 3 0x 0 0x 0 0x 0 0x 6 0x 0 0x 0 0x 0 ) which is not the architecture being linked (x86_64): /Users/alex/oracle_client32/libocci.dylib
ld: warning: ignoring file /Users/alex/oracle_client32/libclntsh.dylib, file was built for unsupported file format ( 0xce 0xfa 0xed 0xfe 0x 7 0x 0 0x 0 0x 0 0x 3 0x 0 0x 0 0x 0 0x 6 0x 0 0x 0 0x 0 ) which is not the architecture being linked (x86_64): /Users/alex/oracle_client32/libclntsh.dylib
Undefined symbols for architecture x86_64:
  "oracle::occi::Environment::createEnvironment(oracle::occi::Environment::Mode, void*, void* (*)(void*, unsigned long), void* (*)(void*, void*, unsigned long), void (*)(void*, void*))", referenced from:
      _main in ccWD5dXB.o
  "oracle::occi::Environment::terminateEnvironment(oracle::occi::Environment*)", referenced from:
      _main in ccWD5dXB.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status

Using a 64-bit client with a 32-bit build fails:
$ g++ -m32 main.cpp -I ~/oracle_client64/sdk/include/ -L ~/oracle_client64 -locci -lclntsh
ld: warning: ignoring file /Users/alex/oracle_client64/libocci.dylib, file was built for unsupported file format ( 0xcf 0xfa 0xed 0xfe 0x 7 0x 0 0x 0 0x 1 0x 3 0x 0 0x 0 0x 0 0x 6 0x 0 0x 0 0x 0 ) which is not the architecture being linked (i386): /Users/alex/oracle_client64/libocci.dylib
ld: warning: ignoring file /Users/alex/oracle_client64/libclntsh.dylib, file was built for unsupported file format ( 0xcf 0xfa 0xed 0xfe 0x 7 0x 0 0x 0 0x 1 0x 3 0x 0 0x 0 0x 0 0x 6 0x 0 0x 0 0x 0 ) which is not the architecture being linked (i386): /Users/alex/oracle_client64/libclntsh.dylib
Undefined symbols for architecture i386:
  "oracle::occi::Environment::createEnvironment(oracle::occi::Environment::Mode, void*, void* (*)(void*, unsigned long), void* (*)(void*, void*, unsigned long), void (*)(void*, void*))", referenced from:
      _main in ccuBypLo.o
  "oracle::occi::Environment::terminateEnvironment(oracle::occi::Environment*)", referenced from:
      _main in ccuBypLo.o
ld: symbol(s) not found for architecture i386
collect2: ld returned 1 exit status

But notice that both complain about both libraries, not just libclntsh. Using a 32-bit client and 32-bit build, or 64-bit client and 64-bit build, both work:
$ g++ -m32 main.cpp -I ~/oracle_client32/sdk/include/ -L ~/oracle_client32 -locci -lclntsh
$ file a.out
a.out: Mach-O executable i386

$ g++ -m64 main.cpp -I ~/oracle_client64/sdk/include/ -L ~/oracle_client64 -locci -lclntsh
$ file a.out
a.out: Mach-O 64-bit executable x86_64


text:
Q: Step down voltage regulator uncertainties The step down voltage regulator I'm currently looking at is the 5V, 5A Step-Down Voltage Regulator D24V50F5 from Pololo ( https://www.pololu.com/product/2851 )
In the description it mentions an EN (standing for enable) pin that can be used to power down or power up the regulator. This sounds like a neat functing I can certainly find use for, however, I'm not sure on the explanation on using it:

The regulator is enabled by default: a 100 kΩ pull-up resistor on the board connects the ENABLE pin to reverse-protected VIN. The ENABLE pin can be driven low (under 0.6 V) to put the board into a low-power state. The quiescent current draw in this sleep mode is dominated by the current in the pull-up resistor from ENABLE to VIN and by the reverse-voltage protection circuit, which will draw between 10 µA and 20 µA per volt on VIN when ENABLE is held low.

If I understand this correctly, if i connect the EN pin with GND it will disable to regulator and thus cut the VOUT?
Thanks for your suggestions!

A: I think you understand it well. They are basically telling you that without an added connection (made by you, somehow), their power supply will be ON by default. They then add that if you add a connection to over-ride their default behavior, which they anticipate you may want to do, then you need to be aware of the fact that to over-ride it you have to "sink" (or pull-down) enough current to achieve it.
It's a very modest amount of current. But since they don't entirely know exactly what \$V_{IN}\$ you will be providing, they instead tell you that they have a \$100\:\textrm{k}\Omega\$ resistor there and also that there may be some added current you have to sink (beyond that resistor's requirements) for their added protection circuitry. The upshot of this is that you should be prepared to sink at least \$20\:\mu\textrm{A}\$ per volt and that you should consider the input to look like this:

simulate this circuit – Schematic created using CircuitLab
(Here, you can easily compute \$R_1=\frac{1\:\textrm{V}}{20\:\mu\textrm{A}}=50\:\textrm{k}\Omega\$.)
If you want to disable the module, you need to make sure that the ENABLE line is pulled below \$600\:\textrm{mV}\$. Just grounding it works fine (of course.) That pretty much guarantees it. But they know that no one is really just going to ground that input. That would be pointless. So they also want to make sure you understand the details enough that you can make sure that whatever you use will be able to "pull down" enough.
Suppose you didn't just ground it but instead hooked up a \$10\:\textrm{k}\Omega\$ resistor from ENABLE to ground. And suppose \$V_{IN}=35\:\textrm{V}\$. Then it's pretty clear that the voltage would be perhaps as high as \$35\:\textrm{V}\cdot\frac{10\:\textrm{k}\Omega}{10\:\textrm{k}\Omega+50\:\textrm{k}\Omega}\approx 5.8\:\textrm{V}\$, which obviously won't work. In this case, you'd need to use a resistor of less than \$872\:\Omega\$, which will sink near \$690\:\mu\textrm{A}\$, to meet the specifications.
This is what they are trying to get across to you. You might need to sink almost a milliamp in some cases and they want you to be aware of it. They also want you to know enough so that if you do want to control it, you can successfully design a reasoned circuit arrangement.

A: You're right, but "cut" isn't the term I'd use - the output is still connected, it's just that no voltage will be output on it. It won't be isolated from your load as if a switch were opened.

A: TTL medium scale logic always used active low input to control something, like Register load, Master reset, because it didn't matter if one used an open collector switch or totem pole or now CMOS.
You don't even need a power source to disable the output. Just a switch to ground, NPN or any logic Vol  that can go below 0.6V with 100K pull-up, which includes all CMOS and TTL.
This is the most common method to control outputs in supplies for either powerup sequencing or going to sleep mode with a small Aux supply left on. for sleep or wake-up functions.
PC's however use a low logic level from the front panel to power up the ATX supply main outputs.


text:
Q: Assign values to a empty matrix from other matrix in R I have one empty matrix which I would like to fill in with the values of two other matrix.
This is my empty matrix:
Att_table_S01_E031_Mod <- matrix(NA, nrow = 16, ncol = 13)
colnames (Att_table_S01_E031_Mod) <- c("ID", "Area", "LU_1990", "LU_2000", "LU_2005", "CHLU_90_00", "CHLU_00_05", "Tile", "Unique_ID", "D_90_00", "D_00_05", "Source_90_00", "Source_00_05")

The other two matrix contain the information I want to include in this new matrix such as ID, Area, LU_1990 and so on. However, I have not found a way to do it yet. Some hints would be well appreciated.
The matrix Att_table_S01_E031 seems to have only one column. Do you know how can I split it?  [1] "ID.Area_ORG.LU_1990.LU_2000.CHLU_90_00.LU_2005.CHLU_00_05.Tile.UNIQ_ID.AREA.D_90_00.D_00_05.Sour_90_00.Sour_00_05.Conf_90_00.Conf_00_05"

A: For complementary matricies,
columnsToTransfer <- c('ID','Area','Tile','Unique_ID','LU_1990')
otherColumns <- colnames(Att_table_S01_E031_Mod)[!(colnames(Att_table_S01_E031_Mod) %in% columnsToTransfer)]
Att_table_S01_E031_Mod[,columnsToTransfer] <- table2[,columnsToTransfer]
Att_table_S01_E031_Mod[,otherColumns] <- table3[,otherColumns]

if the two smaller matricies aren't going to completely fill the big matrix,
columnsToTransfer1 <- c('ID','Area','Tile','Unique_ID')
columnsToTransfer2 <- 'LU_2000'
Att_table_S01_E031_Mod[,columnsToTransfer1] <- table2[,columnsToTransfer1]
Att_table_S01_E031_Mod[,columnsToTransfer2] <- table3[,columnsToTransfer2]


text:
Q: Exchange 2010 SP2 log files taking up space I administrate an Exchange server for a customer, and now the (transaction?) logs are taking up massive amounts of space.
Are they safe to delete?
The logs are taking ~70GB of space, while the database itself is only ~8GB.

A: Are they safe to delete? NO. ABSOLUTELY NOT.
Exchange transaction logs contain records of actions taken on the mail store (including email data) and this data is supposed to be committed to the main database when time permits, and the logs tidied up after a successful full 'exchange aware' backup.
Just deleting them is a great way to lose data; instead you need to investigate why they're not being managed as part of the normal operation of that exchange server. This problem suggests at the very least that backups are not taking place, or possibly that a worse problem exists.


text:
Q: Content area setting not working in UIScrollView in NIB settings I have setup the the content area for UIScrollView in NIB file but i can see it no more scrollable.

A: When you add some view programmatically, you must add in your code (programmatically), a good place to add a UIButton is in the viewDidLoad methods in your implementation (.m) file, here an example:
  - (void)viewDidLoad
{
[super viewDidLoad];

// other code...

UIButton *newButton = [[UIButton alloc] initWithFrame:CGRectMake(50, 50, 40, 40)];
[newButton setTitle:@"ProButton" forState:UIControlStateNormal];
// more properties you can configurate. See Apple doc
[newButton addTarget:self action:@selector(methodToFire:) forControlEvents:UIControlEventTouchUpInside];
// more action you can configurate for event...
[self.view addSubview:newButton];

// more code...
}

A: Try to this code:
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
           action:@selector(buttonClickMethod:)
 forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Button Title" forState:UIControlStateNormal];
button.frame = CGRectMake(50.0, 100.0, 160.0, 40.0);
[view addSubview:button];


text:
Q: Invalid LOC header (bad signature) when opening Excel file We met an error while trying to open an Excel file with Apache POI. Calling new XSSFWorkbook(excelFile) resulted in:
 org.apache.poi.openxml4j.exceptions.InvalidFormatException: invalid LOC header (bad signature)
 at org.apache.poi.openxml4j.opc.PackageRelationshipCollection.parseRelationshipsPart(PackageRelationshipCollection.java:369) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.PackageRelationshipCollection.<init>(PackageRelationshipCollection.java:164) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.PackageRelationshipCollection.<init>(PackageRelationshipCollection.java:132) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.PackagePart.loadRelationships(PackagePart.java:561) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.PackagePart.<init>(PackagePart.java:109) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.PackagePart.<init>(PackagePart.java:80) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.PackagePart.<init>(PackagePart.java:125) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.ZipPackagePart.<init>(ZipPackagePart.java:78) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:241) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:684) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:254) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:201) ~[tika-app-1.11.jar!/:1.11]
 at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:301) ~[tika-app-1.11.jar!/:1.11]

However, it's not with all files. Some work just fine.
The Excel files are on a server we cannot fully accessed, so it's difficult to know what is different about the ones that worked and the ones that failed. We thought it could be password protection but nope, a password encrypted file gives us another error.
Does anyone have a hint about what in certain of these Excel files could trigger this exception?

A: An Excel file uploaded via FTP as text, hence transforming \r\n into \n. Instead of the type binary data it is.
This can be seen when the upload happens on Windows and the uploaded file is a couple of bytes smaller, statistically by 0.4%.


text:
Q: Assertion Failed on Raspberry Pi 4 Have been working on basic code to run multiple cameras on raspberry pi 4 and 3
import numpy as np
import cv2

cap = cv2.VideoCapture(1)

cap2 = cv2.VideoCapture(2)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()
    ret, frame2 = cap2.read()

    # Our operations on the frame come here
    #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Display the resulting frame
    cv2.imshow('CAM 1',frame)
    cv2.imshow('CAM 2',frame2)
    #cv2.imshow('gray',gray)
    if cv2.waitKey(20) & 0xFF == ord('q'):
        break

 # When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

I have been encountering this the following error
Traceback (most recent call last):
  File "/home/pi/Imageprocessing/webcamtest.py", line 16, in <module>
    cv2.imshow('CAM 1',frame)
cv2.error: OpenCV(3.4.3) /home/pi/opencv-3.4.3/modules/highgui/src/window.cpp:356: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'imshow'

Tried changing from (-1to 2 ) but no success
One of the cameras turns on but image is displayed.
The cameras work on web browser.
System : Raspberry Pi 4 4GB
OS: Buster
Python version : 2.7 and 3.7.3
Open CV version 3.4.3
Cameras: Logitech C310 720p

Even The Single camera is not working and comes up with the same error

A: Try to number your cameras starting from 0 (zero):
cap = cv2.VideoCapture(0)
cap2 = cv2.VideoCapture(1)


text:
Q: How does one access browser localStorage using server side scripts like php/asp.net from the frontend? I have searched for a solution to this problem and many answers I read said it is not possible.
I found this way and it worked. Let me know if it is a bad way of doing it.
<?php  echo '<script>
 document.getElementById("displayLSValueThroughPHP").innerHTML =
 JSON.parse(localStorage.getItem(\'localStorageValue\'))</script>';?></div>```

A: front end vs back end
what do you mean server side scripting?

*

*you can access cookies on server, because they are sent with every single request.

*you can't access local storage on server, because it is accessible only in exact browser.

the only way it is possible is:

*

*dummy page with javascript

*execute javascript in the browser

*redirect including the data

*render content again using the local storage data server-side

<script>
    const localStorageValue = encodeURIComponent(localStorage.getItem('localStorageValue'))
    window.location = '/local-storage-data-back?localStorageValue=' + localStorageValue;
</script>

NOTE: for higher security use https and POST instead of GET parameters


text:
Q: identity theorem to prove/disprove the existence of a holomorphic function Does there exist a holomorphic function $f$ the unit disk $\{z :|z|<1 \}$ such that
$f(\frac{1}{n}) \leq \frac{1}{2^n} $ for all $ n \in \mathbb{N}$?
I know by identity theorem we can prove that $f$ not exists with $f(\frac{1}{n}) = \frac{1}{2^n} $ but not sure if this inequality can change the conclusion.

A: Conjecture:  The function $f(z)=0$ suggested by @Desperado is the unique holomorphic function that satisfies $$|f(1/n)| \le \frac{1}{2^n}.$$

A: I guess the conjecture of @mjw is right, here a tentative proof. Let me now if there are mistakes.
The zero-function satisfies the conditions, and looking for a contradiction,
let $f$ be a non-zero holomorphic function satisfying the condition too. The function $f$must have a zero of order $m\in\mathbb N_{>0}$ in $z=0$, hence
$g(z):=f(z)/z^m$ is also holomorphic and $g(0)\neq 0$. On the other hand, it holds
$$|g(0)|= \lim_{n\to \infty}|g(1/n)|=\lim_{n\to \infty} |n^m f(1/n)|\leq \lim_{n\to \infty}\frac{n^m}{2^n}=0$$
a contradiction.


text:
Q: Discrete random variables and probability models During jury selection a large number of people are asked to be present, then persons are selected one by one in a random order until the required number of jurors has been chosen. Because the prosecution and defense teams can each reject a certain number of persons, and because some individuals may be exempted by the judge, the total number of persons selected before a full jury is found can be quite large.
(a) Suppose that you are one of 150 persons asked to be present for the selection of a jury. If it is necessary to select 40 persons in order to form the jury, what is the probability you are chosen?
(b) In a recent trial the numbers of men and women present for jury selection were 74 and 76. Let Y be the number of men picked for a jury of 12 persons. Give an expression for P (Y = y), assuming that men and women are equally likely to be picked.
(c) For the trial in part (b), the number of men selected turned out to be two. Find P (Y ≤ 2). What might you conclude from this?
I'm a little stuck on where to begin/which model to use, any tips? thanks!

A:
(a) Suppose that you are one of 150 persons asked to be present for the selection of a jury. If it is necessary to select 40 persons in order to form the jury, what is the probability you are chosen?

The overly complicated method is to count how to select yourself and 39 of the 149 other people out of all the ways to select 40 of 150 people.
$$\mathsf P(U) = {1\choose 1}{149\choose 39}\bigg/{150\choose 40} = \frac {\Box}{\Box}$$
There is a much simpler way to express this.  Fill in the boxes.

(b) In a recent trial the numbers of men and women present for jury selection were 74 and 76. Let Y be the number of men picked for a jury of 12 persons. Give an expression for $\mathsf P (Y = y)$, assuming that men and women are equally likely to be picked.

However, here that method is best.  Count the ways to select $y$ of the men and how many of women out of all the ways to select 12 of 150 people.
$$\mathsf P(Y=y) = {\Box\choose \Box}{\Box\choose \Box}\bigg/{150\choose 12}$$
Fill in the boxes.

(c) For the trial in part (b), the number of men selected turned out to be two. Find $\mathsf P (Y \leqslant 2)$. What might you conclude from this?

$$\mathsf P(Y\leq 2) = \mathsf P(Y=0) + \mathsf P(Y=1) + \mathsf P(Y=2)$$
Use the formula from part (b), evaluate, and comment.


text: Q: PostgreSQL installer crash up at startup I downloaded postgresql-13.2-2-windows-x64.exe file and when I try to start up installation I see only logo for one second and this is end. I see this file in task manager as a background process, sometimes as a sub-process of Opera(thread I think). Maybe anyone can help me to fixed this problem.


text:
Q: Trigger macro with ONE click on specific cell Would you mind pointing a way to start a macro in Excel 2010 by clicking only once on a specified cell? I had seen a solution somewhere, but now I can't trace it back.

A: The following code will fire when cell D4 is clicked in the worksheet.
Right-click the sheet tab and select "View Code". Paste this into the code window:
Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Selection.Count = 1 Then
        If Not Intersect(Target, Range("D4")) Is Nothing Then
            MsgBox "Hello World"
        End If
    End If
End Sub

Adjust the cell reference from "D4" to reflect your desired cell. Replace the MsgBox line with your desired code.

A: Here is a slightly different approach to the original question, which may suit some applications.
' Make the desired cell a hyperlink to itself ...
With ThisWorkbook.Sheets(mysheet)
  .Hyperlinks.Add Anchor:=.Cells(myrow,mycol), Address:="", SubAddress:="R[0]C[0]"
End With

' ... and then let the handler for the FollowHyperlink event do the business:
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
  Debug.Print "clicked " & Target.TextToDisplay & " on row " & Target.Range.Row
End Sub

A: The Worksheet_SelectionChange event does NOT fire unless the cell value is changed.  Just clicking on the cell does NOT fire the event.


text:
Q: Mapbox GL JS - Trouble Loading Data to Create Layer I am new to Mapbox GL JS and working with starter code from "Create a Time Slider" below:
https://docs.mapbox.com/mapbox-gl-js/example/timeline-animation/

To pull in the data, the code uses d3.json to perform a fetch (also I am new to d3....). I have imported this starter code into a Ruby on Rails app that I am creating for some basic data visualization.
https://docs.mapbox.com/mapbox-gl-js/assets/significant-earthquakes-2015.geojson

My goal is to modify the starter code to suit my own data set. So I had saved down the data...
https://docs.mapbox.com/mapbox-gl-js/assets/significant-earthquakes-2015.geojson

..into a local file earthquakes.geojson in the root directory of my app, assuming that the d3.json would just as easily point to my internal file instead of the Mapbox hosted URL
So the original starter code here:
d3.json('https://docs.mapbox.com/mapbox-gl-js/assets/significant-earthquakes-2015.geojson', function(err, data) {
if (err) throw err;

Is modified with a new URL for my local file:
d3.json('./earthquakes.geojson', function(err, data) {
if (err) throw err;

After making the above modification, none of the data pulls through, but I am not receiving any errors or info to point me in a new direction to investigate the issue.
Can someone give me a hint or point me in the right direction as to how to get Mapbox to connect with the data using d3?

A: The dot "." in a path is something used in Linux to mean the current directory. On the web you can either use "/file.json" if in the root or just "file.json" if relative to your HTML file.
It's not really using D3, just d3.json as a shorthand for XMLHttpRequest.

A: i figured out the answer... was a file location, directory issue. i relocated to a newly created folder in ending up with "app/public/data/earthquakes.geojson"
then in my .js the proper path updated
d3.json("/data/earthquakes.geojson", function(err, data) {
  if (err) throw err;


text:
Q: PHP: creates file but can't append with (apparently) correct server permissions (LAMP) I have seen many questions and answers on this topic but none seem to help my situation. My PHP code is successfully creating a new logfile, but then cannot access that file to append further info, close it, etc.
I am migrating an application from local XAMPP onto LAMP: hence problem only showing up now due to Windows/XAMPP giving no permission troubles.
I started with a default Bitnami LAMP stack, and then manually setup relevant directory permissions on server:
- my sftp user has rwx on htdocs and assorted out-of-web-root directories
- apache is running as 'daemon' so I have given read & execute permissions to relevant directories for 'daemon' as group
- in most directories I have disallowed write permissions for 'daemon'
- however for my (application generated, internal) logs I have a 'logfiles' directory which has rwx for both my user and the 'daemon' group
- 'other' is -rwx for all
When I run my application it falls over pretty much immediately.  The error logs showing fopen failed to open stream: permission denied.  However, the permissions indicate that it should have access.
When I check the file involved it has following permissions:
-rw-r--r-- 1 daemon daemon 962 Oct  3 10:14 20151003logfile03-10-33530.txt

This tells me that the file was created by Apache (i.e. by my PHP script) and that it has read and write permissions, from when I fopen() with "w"
EDIT: adding directory info:
Folder level permissions give my ftps user and daemon (group) full rwx access:
drwxrwx--- 2 ftpuser daemon 4096 Oct  3 10:30 logfiles

BUT it can't then fopen with "a"
I am assuming that this IS a file permission problem because:
a) it works fine on XAMPP
b) it states permission error in the error log
However, I can't see why it should be a problem, given directly-specified OS-level permissions ...  maybe Apache requires an .htaccess 'allow' on this directory also?
Any ideas?

Clarification re why I don't think CHMOD is the answer (sorry @RedAcid):
CHMOD 777 etc is simply a way to set the underlying permissions I already have. Each digit represents 3 binary chars, so 7 is 111 (i.e. read, write and execute).  As you can see above, I have read/write/execute for PHP/Apache on folder, together with read/write for file.  What I've read suggests that you need execute at directory level, but not at file level because its not trying to execute the file.
So what am I missing here? Why else might it be denying permission?

A: use chmod 666 for the file and proper user group permissions. folder where files are located must be writable with  chmod 777

A: OK - I found out the problem was higher level parent directory not having read/execute permissions.  Now working!  (AT LAST!)
For more detail see this previous question:
PHP fopen() fails on files even with wide-open permissions