text:
Q: Java program not producing correct result I am trying to write a program that takes a set of 10 numbers from the user, finds the smallest and largest value within the set, and displays it to the user. I kind of got the program to work but I am experiencing an issue. It looks like it skips through the first number and assigns the second number to be the smallest value. In class we haven't gotten to arrays yet so, I have to assume that the first value entered in the smallest and largest value Here's what I have:
   int smallestValue;
   int largestValue;
   int numInput;
   int counter = 1;
   int numSets = 0;

   Scanner input = new Scanner(System.in);

   System.out.print("Enter a set of 10 numbers: ");
   numInput = input.nextInt();
   smallestValue = input.nextInt();
   largestValue = input.nextInt();

   counter++;

   while (counter != 9)
   {

      numInput = input.nextInt();
      counter++;

      if (numInput > largestValue)
      {
         largestValue = numInput;
      }

      else if (numInput < smallestValue )
      {
          smallestValue = numInput;
      }

    }

        System.out.println( "Smallest is " + smallestValue );
        System.out.println("Largest is " + largestValue);

Thanks in advance!

A: It skips value because you call input.nextInt() before the loop, you don't need to, and use Integer.MAX_VALUE and Integer.MIN_VALUE to initialize the min and max. Also when you iterate depending on a counter, it's commonly with a for loop
int numInput;
int smallestValue = Integer.MAX_VALUE;
int largestValue = Integer.MIN_VALUE;

Scanner input = new Scanner(System.in);
System.out.print("Enter a set of 10 numbers: ");

for(int i=0; i<10; i++){
    numInput = input.nextInt();

    if (numInput > largestValue){
        largestValue = numInput;
    }else if (numInput < smallestValue ){
         smallestValue = numInput;
    }
}

System.out.println( "Smallest is " + smallestValue );
System.out.println("Largest is " + largestValue);


text:
Q: Autocad C# Developer's Guide zoom example I am trying to follow the Autocad C# Developer's Guide examples and learn how to write my own codes, however, when I worked on this zoom example, I cannot use the zoom assembly or method (sorry, do not what what to call it), when I type it in Visual Studio, it does not work as a class.
I could really use some help on these, thank you in advance.

A: The extension methods I use:
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Autodesk.AutoCAD.EditorInput
{
    public static class ExtensionMethods
    {
        public static Matrix3d EyeToWorld(this ViewTableRecord view)
        {
            if (view == null)
                throw new ArgumentNullException("view");

            return
                Matrix3d.Rotation(-view.ViewTwist, view.ViewDirection, view.Target) *
                Matrix3d.Displacement(view.Target - Point3d.Origin) *
                Matrix3d.PlaneToWorld(view.ViewDirection);
        }

        public static Matrix3d WorldToEye(this ViewTableRecord view)
        {
            return view.EyeToWorld().Inverse();
        }

        public static void Zoom(this Editor ed, Extents3d ext)
        {
            if (ed == null)
                throw new ArgumentNullException("ed");

            using (ViewTableRecord view = ed.GetCurrentView())
            {
                ext.TransformBy(view.WorldToEye());
                view.Width = ext.MaxPoint.X - ext.MinPoint.X;
                view.Height = ext.MaxPoint.Y - ext.MinPoint.Y;
                view.CenterPoint = new Point2d(
                    (ext.MaxPoint.X + ext.MinPoint.X) / 2.0,
                    (ext.MaxPoint.Y + ext.MinPoint.Y) / 2.0);
                ed.SetCurrentView(view);
            }
        }

        public static void ZoomCenter(this Editor ed, Point3d center, double scale = 1.0)
        {
            if (ed == null)
                throw new ArgumentNullException("ed");

            using (ViewTableRecord view = ed.GetCurrentView())
            {
                center = center.TransformBy(view.WorldToEye());
                view.Height /= scale;
                view.Width /= scale;
                view.CenterPoint = new Point2d(center.X, center.Y);
                ed.SetCurrentView(view);
            }
        }

        public static void ZoomExtents(this Editor ed)
        {
            if (ed == null)
                throw new ArgumentNullException("ed");

            Database db = ed.Document.Database;
            db.UpdateExt(false);
            Extents3d ext = (short)Application.GetSystemVariable("cvport") == 1 ?
                new Extents3d(db.Pextmin, db.Pextmax) :
                new Extents3d(db.Extmin, db.Extmax);
            ed.Zoom(ext);
        }

        public static void ZoomObjects(this Editor ed, IEnumerable<ObjectId> ids)
        {
            if (ed == null)
                throw new ArgumentNullException("ed");

            using (Transaction tr = ed.Document.TransactionManager.StartTransaction())
            {
                Extents3d ext = ids
                    .Where(id => id.ObjectClass.IsDerivedFrom(RXObject.GetClass(typeof(Entity))))
                    .Select(id => ((Entity)tr.GetObject(id, OpenMode.ForRead)).GeometricExtents)
                    .Aggregate((e1, e2) => { e1.AddExtents(e2); return e1; });
                ed.Zoom(ext);
                tr.Commit();
            }
        }

        public static void ZoomScale(this Editor ed, double scale)
        {
            if (ed == null)
                throw new ArgumentNullException("ed");

            using (ViewTableRecord view = ed.GetCurrentView())
            {
                view.Width /= scale;
                view.Height /= scale;
                ed.SetCurrentView(view);
            }
        }

        public static void ZoomWindow(this Editor ed, Point3d p1, Point3d p2)
        {
            using (Line line = new Line(p1, p2))
            {
                ed.Zoom(line.GeometricExtents);
            }
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text: Q: Media transfer protocol node js I am looking for a way to transfer files from a windows machine to an android device using node js using the media transfer protocol, or any other way if possible as i would like to move some files listed on the computer to the device. I would also guess i could run an executable in a child process, but have no experience in writing an executable that could be run. Any help or resources to accomplish this I would be very grateful. There is also no guarantee of being able to mount the device which is why i thought MTP.


text:
Q: How to find the object where property values match in two nested objects? (Javascript) I have two airport datasets - one stored locally and another one fetched from a server.
The local dataset, airports, has around 45,000 individual objects, where each object has the following structure:
  {
    "ident": "AYPY",
    "type": "large_airport",
    "name": "Port Moresby Jacksons International Airport",
    "latitude_deg": -9.443380356,
    "longitude_deg": 147.2200012,
    "iso_country": "PG"
  },

The fetched dataset is created using the createDestinationObject(title), which fetches the related data from the title page and stores it in the finalList variable. This is how it looks:
  {
    "ICAO": "AYPY",
    "name": "Port Moresby Jacksons International Airport",
    "latitude": 0,
    "longitude": 0,
  },

The fetched dataset lacks coordinates (hence the placeholder zeroes). I want to take the coordinates from the airports dataset by matching airports.ident with finalList.ICAO, as they both are standard ICAO codes for airports. Then I assign the latitude_deg and longitude_deg values from the matching airports item to the latitude and longitude properties of the finalList item.
To try and solve this, I used a nested for loop where each finalList item is looped through the airports dataset, and if the ICAO code matches, it assigns the coordinates. The code works, but The problem is that it takes quite some time (even up to 20-30 seconds if finalList dataset has >300 objects). Is there any way to solve this faster, without looping every finalList item through each of the +40k items in the airports dataset?
import airports from './airports.json';

async function assignCoordinates(title) {
  var finalList = await createDestinationObject(title);
  for (var destination in finalList) {
    for (var airport in airports) {
      if (finalList[destination].ICAO === airports[airport].ident) {
        finalList[destination].latitude = airports[airport].latitude_deg;
        finalList[destination].longitude = airports[airport].longitude_deg;
      }
    }
  }
  console.log(finalList);
}

var title = "Vilnius_Airport";
assignCoordinates(title);

I am extremely new to Javascript, so my code might be sloppy in general, don't hesitate to critique.
EDIT:
To give more information, airports is stored locally and imported into the .js file.
finalList is a list of destinations (airports) from the title airport.
The createDestinationObject(title) function:

*

*Fetches the wikipedia section list from the title page.

*Finds the section where destinations are listed.

*Fetches the wikitext from this section and stringifies it.

*Filters the text to find invididual airports and their pagenames.

*Fetches the summary of each of the individual airports and uses regexp to find the ICAO code in the summary or the infobox.

*returns a nested object where finalList.ICAO is the fetched ICAO code; finalList.name is the airport name from the destination section wikitext; finalList.longitude and finalList.latitude are placeholder properties to store coordinate data. There are as many objects in finalList as there are destinations from the title airport, each object being one destination airport.

The createDestinationObject(title) function itself takes maybe 1-2 seconds to run.

A: A better strategy to improve the complexity of visiting the airports array again and again for each destination, you could first spend an entire visit of its elements just for the sake of creating a map that will bind each .ident value to the corresponding airport object.
Once you have that map, you can just perform your algorithm that for each destination in the array returned from the api fetch, it picks the corresponding airport just by doing airportsMap[destination.ICAO], and if found, sets its latitude and longitude accordingly.
The strategy I used to make such map is:
let airportsMap = Object.assign({}, ...airports.map((a) => ({[a.ident]: a})));

That just assign to an empty object all the properties (key-value pairs) coming from airports.map

var airports = [
  {
    "ident": "AYPY",
    "type": "large_airport",
    "name": "Port Moresby Jacksons International Airport",
    "latitude_deg": -9.443380356,
    "longitude_deg": 147.2200012,
    "iso_country": "PG"
  },
  {
    "ident": "ZHHE",
    "type": "large_airport",
    "name": "Another International Airport",
    "latitude_deg": -65.3422234,
    "longitude_deg": 143.653453,
    "iso_country": "US"
  },
];

const createDestinationObject = (title) => {
  return [{
      "ICAO": "AYPY",
      "name": "Port Moresby Jacksons International Airport",
      "latitude": 0,
      "longitude": 0,
    },
    {
      "ICAO": "notexisting",
      "name": "...",
      "latitude": 0,
      "longitude": 0,
    },
  ];
};

//this will create a map where each airport is indexed by ICAO
let airportsMap = Object.assign({}, ...airports.map((a) => ({[a.ident]: a})));

function assignCoordinates(title) {
  var finalList = createDestinationObject(title);
  for (let destination of finalList) {
    if (Object.hasOwn(airportsMap, destination.ICAO)) {
      const airport = airportsMap[destination.ICAO];
      destination.latitude = airport.latitude_deg;
      destination.longitude = airport.longitude_deg;
    }
  }
  return finalList;
}

var title = "bogus";
const o = assignCoordinates(title);
console.log(o);


text:
Q: Picture is not showing up in my activity after I take a photo On Android 10 and below, when I take a picture using the code below, everything is fine except for Android 11 and above.
private fun openCameraApp() {
        val photoURI: Uri = FileProvider.getUriForFile(
            this,
            "com.example.android.fileprovider",

        appFolder

    )
    refresh()
    val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
    println("::Camera result::  ${photoURI}")

    resultLauncher.launch(cameraIntent)
}

A: Since API level 30 (Android 11), there have been changes in the package visibility.
For your package manager to work properly, you need to declare <queries> in your Androidmanifest.xml file
Code.
<manifest package="your.package.name">
<queries>
    <intent>
        <action android:name="android.media.action.IMAGE_CAPTURE" />
    </intent>
</queries>
</manifest>

This will only be worked for android default camera apps
Happy Coding :)


text:
Q: C++ Indexing TCHAR string I am doing some static analysis work on some old C++ code and my C++ is not the strongest. I have this piece of code:
void NIDP_clDPLogger::log(TCHAR *logString)
{
    TCHAR temp_logString[1024] = {0};
    _tcsncpy(temp_logString,logString,1024);
    temp_logString[1023] = NULL;
            ...

The static analysis tool is complaining here of indexing logString (the parameter passed in to function) at 1024 when it may be shorter (the size varies, 1024 is the max. size I guess). So I guess my fix is to check the size of logString and use that, like this:
void NIDP_clDPLogger::log(TCHAR *logString)
{

    size_t tempSize = sizeof(logString);
    TCHAR temp_logString[tempSize] = {0};
    _tcsncpy(temp_logString,logString,tempSize);
    temp_logString[tempSize-1] = NULL;

I am just wondering, will this work OK? Can anybody see any flaws/problems? Building and testing this project is slightly difficult so I am basically just looking for a sanity check before I go through all that. Or is there a better way for me to do it? Can I pass a size_t value in to _tcsncpy, because a hardcoded int was there before?
Thanks for all help.

A: sizeof(logString) will return the size of a TCHAR*, not the size of the array passed as arrays decay to pointers when passed as argument.
If it is guaranteed that logString is null terminated you could obtain its length using _tcslen(). Otherwise, the only way to know the size of logString is to pass it into the function as another argument.


text:
Q: x86 How to change gdt after it has been already loaded? I have my idtr addressing defined as
gdt_pointer:
    DW 0;size_of_gdt
    DD 0;start_of_gdt

and I can load it with LGDT [gdt_pointer].
But how can I change the contents of gdt later if I have to?
Can I use the LGDT instruction again after setting the proper values?
EDIT:
I'm planning to keep my gdt_pointer start address same all the time, but I'll be changing the size parameter. Also I'm loading and changing the gdt from 32 bit protected mode.

A: If you change the contents of the GDT (but leave it at the same address), then you only have to load segment registers that would be effected by the changes (if any).
If you change the (virtual) address of the GDT (but leave its contents the same), then you only have to do lgdt again.
If you change both the (virtual) address of the GDT and its contents, then you'd need to do lgdt and also load any effected segment registers.


text:
Q: DbContext and navigation properties in EF 4.4 After switching a project from the EntityObject generator to DbContext, I ran into an issue using some navigation properties on new objects.  I've spent a significant amount of time researching the problem, and I'm no closer to a desirable solution.
First, the generated class definitions:
public partial class Category
{
    public Category()
    {
        this.Limits = new HashSet<Limit>();
    }

    public int CategoryId {get; set;}
    public string Name {get; set;}
    public virtual ICollection<Limit> Limits { internal get; set; }
}

public partial class Limit
{
    public int CategoryId {get; set;}
    public string Description {get; set;}
    internal virtual Category Category { get; set; }
}

I am creating test data during an integration test using the following code:
using (GFCAMDataContext db = new GFCAMDataContext())
{
    limit = new Limit()
    {
        CategoryId = testData.CategoryId,
        Description = "SignerController.Update"
    };

    db.Limits.Add(limit);
    db.SaveChanges();
}

Without any other changes, the Limit.Category property of my newly-created Limit object does not return anything.  However, if I query the desired Category from the DbContext before SaveChanges is called the navigation property on my new Limit starts returning the associated Category.  With ObjectContext, the Category property is updated without any intervention from me.
I would like to have the same behavior as ObjectContext, but I can't seem to find a way to achieve this goal.  I've seen a couple of proposed solutions:

*

*Make the navigation properties public.  This had the same behavior, and isn't desirable as the public navigation properties can cause issues during serialization and aren't needed outside of my business layer.

*Make all properties public virtual and use DbSet.Create to ensure proxy creation.  This resulted in the same behavior, and isn't necessarily desirable as I have code dynamically creating instances (i.e. I don't have access to a DbSet at the time I am creating an entity instance).
Does anyone have any suggestions for a solution to this problem?

A: One solution would be to explicitly load the nested entity:
db.SaveChanges();
db.Entry(person).Reference(z => z.Category).Load();

The other option, when proxies are enabled, is indeed to call DbSet.Create<T>(). If you don't have access to the DbSet instance  at the time you create your entities, you might want to expose a public method in your repository interface that allows that. For example:
public interface IRepository<T>
{
    T Add(T entity);

    T GetById(...);

    void SaveChanges();

    ...

    T CreateInstance(); // Concrete implementation have access to DbSet and uses DbSet.Create<T>()
}


text:
Q: What is the difference between `autoload` and `autoload -U` in Zsh? What is the difference between autoload -U and plain autoload?
For instance, here it is recommended to run:
autoload -U run-help
autoload run-help-git
autoload run-help-svn
autoload run-help-svk
unalias run-help
alias help=run-help

Why is -U only in the first line?

A: Yes, you do see the recommendation for -U often, usually paired with -z. It's not documented in the run-help for autoload, but there is a section titled "AUTOLOADING FUNCTIONS" in the manpage for zshmisc.
There it states:

The  usual  alias  expansion during reading will be suppressed if the autoload
  builtin or its equivalent is given the option -U. This is recommended for  the
  use  of functions supplied with the zsh distribution.  Note that for functions
  precompiled with the zcompile builtin command the flag  -U  must  be  provided
  when  the  .zwc  file is created, as the corresponding information is compiled
  into the latter.

I read that as "disregard aliases". The -z seems to be to avoid Ksh-isms. I just memorize -Uz and usually add them to any autoload. Maybe a worthwhile alias: alias al='autoload -Uz'.
See also: https://stackoverflow.com/questions/12570749/zsh-completion-difference


text:
Q: How can I reverse py.test addopts? My py.test command is attached with extra options fixed. Everytime I run py.test the options are automatically attached.
py.test --cov=ner_brands --cov-report=term-missing --cov-config

How can I remove these attached options?

A: My guess is there is something specified in your conftest.py. See How to change command line options defaults.


text:
Q: using "would" instead of simple past I was watching "The Big Bang Theory" and in episode 07 of season 3, Leonard asked his girlfriend the following question

Penny: I hear you don't like my stuffed animals, my driving or my punctuality.
Leonard: What? Who would tell you something like that? Why would you tell her something like that?
Penny: It doesn't matter why he [Sheldon] told me. It's true, isn't it?

I'm wondering why he didn't use simple past: "Who told you something like that?"
What's the difference?
Source: Show Script

A: "who told you that?" means that someone certainly told you something and it is real because it happened in the past. "Who would tell you that?" doesn't mean someone told you something. It means that "I am wondering who was going to tell you that". Would + verb means that we imagine a situation that is not real, the one that didn't happen in the past. Just like in this sentence: I would love to have a race car, but the reality is I don't have it. There are many uses of "would" and it is just one of them.


text:
Q: How to create an object in javascript with illegal key name? I like to create an object using javascript/node.js with dash in the middle of the key's name.
Here is an array that I am using today that need to convert to an object.
var data = new Array();
data['__type'] = 'urn:inin.com:connection:icAuthConnectionRequestSettings';
data['applicationName'] = 'test';
data['userID'] = 'blah';
data['password'] = 'blah;
data['val-name'] = 'blah;

How to create an object with key like this val-name?

A: I've got a few spare minutes. So, code-review hat goes on.
var data = new Array();
data['__type'] = 'urn:inin.com:connection:icAuthConnectionRequestSettings';
data['applicationName'] = 'test';
data['userID'] = 'blah';
data['password'] = 'blah;
data['val-name'] = 'blah;

Firstly, I think you have some typographic errors in this code. The last two values have oddly paired quotes.
var data = new Array();
data['__type'] = 'urn:inin.com:connection:icAuthConnectionRequestSettings';
data['applicationName'] = 'test';
data['userID'] = 'blah';
data['password'] = 'blah';
data['val-name'] = 'blah';

Next, at the moment, you're assigning keys to an array. Which probably isn't what you mean (summary of the issue here; short version is that some collection methods will give you unexpected results). You likely mean to start an empty object as data.
var data = {};
data['__type'] = 'urn:inin.com:connection:icAuthConnectionRequestSettings';
data['applicationName'] = 'test';
data['userID'] = 'blah';
data['password'] = 'blah';
data['val-name'] = 'blah';

Finally, you can use data literals in JS, rather than serial assignment.
var data = {
    '__type': 'urn:inin.com:connection:icAuthConnectionRequestSettings',
    'applicationName': 'test',
    'userID': 'blah',
    'password': 'blah',
    'val-name': 'blah'
}

As part of this, you've created an object with a slot name that has a - in it. There's nothing illegal about this, but it does prevent you from accessing that slot with dot notation.
console> data['val-name']
'blah'
console> data.val-name
NaN

That has nothing to do with the key being illegal, and everything to do with the access being parsed as a subtraction. That is, data.val-name gets interpreted as "Subtract the value of name from the value of data.val" rather than "Access the slot val-name of the object data".


text:
Q: Complicated problem. Need help with regular expression replace I'm in the process of updating a program that fixes subtitles.
Till now I got away without using regular expressions, but the last problem that has come up might benefit by their use. (I've already solved it without regular expressions, but it's a very unoptimized method that slows my program significantly).
TL;DR;
I'm trying to make the following work:
I want all instances of:
"! ." , "!." and "! . "  to become: "!"
unless the dot is followed by another dot, in which case I want all instances of:
"!.." , "! .." , "! . . " and "!. ." to become: "!..."
I've tried this code:
the_str = Regex.Replace(the_str, "\\! \\. [^.]", "\\! [^.]");

that comes close to the first part of what I want to do, but I can't make the [^.] character of the replacement string to be the same character as the one in the original string... Please help!
I'm interested in both C# and PHP implementations...

A: $str = preg_replace('/!(?:\s*\.){2,3}/', '!...', $str);
$str = preg_replace('/!\s*\.(?!\s*\.)/', '!', $str);

This does the work in to PCREs. You probably could do some magic to merge it to one, but it wouldn't be readable anymore. The first PCRE is for !..., the second one for !. They are quite straightforward.

A: C#
s = Regex.Replace(s, @"!\s?\.\s?(\.?)\s?", "!$1$1$1");

PHP
$s = preg_replace('/!\s?\.\s?(\.?)\s?/', '!$1$1$1', $s);

The first dot is consumed but not captured; you're effectively throwing that one away.  Group #1 captures the second dot if there is one, or an empty string if not.  In either case, plugging it into the replacement string three times yields the desired result.
I used \s instead of literal spaces to make it more obvious what I was doing, and added the ? quantifier to make the spaces optional.  If you really need to restrict it to actual space characters (not tabs, newlines, etc.) you can change them back to spaces.  If you want to allow more than one space at a time, you can change ? to * where appropriate--e.g.:
@"!\s*\.\s*(\.?)\s*"

Also, notice the use of C#'s verbatim string literals--the antidote for backslashitis. ;)


text:
Q: how to find port number of android emulator to send sms i am developing android messaging application i need to know port number of emulator to test my application by sending SMS to that emulator where can i find port number?i am new to android

A: Use:
adb emu sms send 5551234 "text"

to send sms to emulator.

A: You can use the DDMS perspective in Eclipse to send an SMS to your emulator as well.
By default the window to send an SMS is on the left side of the screen in the middle.
Be sure to select your emulator in the window above if it is not already selected.


text: Q: How to inject Webpack bundle's file name into DefinePlugin `process.env` in Webpack config I am making two bundles one is for service worker and one is the application code using webpack and I want to inject the file name of service-worker.js file which contains a hash in the file name into the process.env variable so I can use the file name to load it using ajax in my code. Is there a way to pass the file name with the hash into the application code using one webpack config and one build process.


text:
Q: how to send multi args to Django custom templates from JS code inside HTML template I'm trying to use a custom template tag to run a specific function on a variable that I get in JS inside my HTML template.
here is a sample of what I tried :
python template tag
def calculate_km(value, arg):
    """
    Calculate the km from the source
    """
    args_list = eval(arg)
    layer_id = value
    return f"layer_id_is:{layer_id}, args_list:{args_list}"

then am using it inside my HTML js block like this :
const args_data = "[" + kmlEvent.featureData.id + "," + kmlEvent.latLng.lat + "," + kmlEvent.latLng.lng + "]";
console.log(`{{single_layer.id|calculate_km: ${args_data} }}`);

The problem here is in adding the JS variable inside the template tag , as you see using args_data inside the string that should return syntax for normal Django template so what is expected is that the console.log line renders as follows :
{{12|calculate_km:[12,Foo,123,456]}}

But the problem is that it is not reading the value of the variable args_data and it is being rendered as :
{{12|calculate_km: ${args_data}}}

and of course, that returns an error which is :
django.template.exceptions.TemplateSyntaxError: calculate_km requires 2 arguments, 1 provided

so it seems like not even reading the value of args_data

A: The Django template tag is rendered on the server side, before serving the HTTP response. What the browser receives in the response is just HTML and JavaScript.
The JavaScript executes on the client side, after all the Django template tags (and other nodes) have already been resolved and rendered.
Unfortunately you cannot pass JavaScript arguments to a Django template tag because the order of execution is incompatible. You'll need to rewrite your template tag as a JavaScript function. Since your code looks like it's being triggered by an event (based off your variable names) switching all the code to execute server-side likely isn't possible.


text:
Q: Put a file in a library with a File-Upload on sharepoint designer I work on SharePoint designer 2013 and I try to put a file(The file can be an image, a text file, a powerPoint, a videos or any type of file) in a library with a FileUpload.
I didn't find any code in JavaScript which allows to do that. But when I coded in C#, SharePoint returned an error message

"Les blocs de code ne sont autorisés dans ce fichier"

or in english

"Code blocks are not allowed in this file".

Can someone help me to find a solution to this problem ?

A: In sharepoint Designer you cant Use c#,im not clear how did you do it,you need to go for webpart solution for this or another way,simple answer is you cant do serverside code with SPD.
below links might help you.
https://msdn.microsoft.com/en-us/library/ee330921.aspx
https://msdn.microsoft.com/en-us/library/vstudio/ee330921%28v=vs.100%29.aspx?f=255&MSPPError=-2147217396


text:
Q: jqxGrid fails with error "Object [object Object] has no method 'jqGrid'" I am trying to embed jqxgrid into my HTML page.
This are the libraries that I import:
<script src="./wicket/resource/org.apache.wicket.resource.JQueryResourceReference/jquery/jquery-1.10.1-ver-1379671500000.js"></script>
<script src="./wicket/resource/org.apache.wicket.ajax.AbstractDefaultAjaxBehavior/res/js/wicket-event-jquery-ver-1379671500000.js"></script>
<script src="./wicket/resource/org.apache.wicket.ajax.AbstractDefaultAjaxBehavior/res/js/wicket-ajax-jquery-ver-1379671500000.js"></script>
<script src="/jquery/jquery-ui.min.js"></script>
<script src="/jqwidgets/jqxcore.js"></script>
<script src="/jqwidgets/jqxdata.js"></script>
<script src="/jqwidgets/jqxbuttons.js"></script>
<script src="/jqwidgets/jqxscrollbar.js"></script>
<script src="/jqwidgets/jqxmenu.js"></script>
<script src="/jqwidgets/jqxcheckbox.js"></script>
<script src="/jqwidgets/jqxlistbox.js"></script>
<script src="/jqwidgets/jqxdropdownlist.js"></script>
<script src="/jqwidgets/jqxgrid.js"></script>
<script src="/jqwidgets/jqxgrid.columnsresize.js"></script>
<script src="/jqwidgets/jqxgrid.edit.js"></script>
<script src="/jqwidgets/jqxgrid.filter.js"></script>
<script src="/jqwidgets/jqxgrid.pager.js"></script>
<script src="/jqwidgets/jqxgrid.selection.js"></script>
<script src="/jqwidgets/jqxgrid.sort.js"></script>

I omitted type="text/javascript" for simplicity reasons. As you can see the whole think is a wicket application, so I can't really influence the first three imports.
I implemented the jqxgrid as follows:
<script type="text/javascript">
    $(document).ready(function() {
        var theme = "smoothness";
        var dataAdapter = new $.jqx.dataAdapter(data);
        $("#jqxgrid").jqxGrid({
            width : "99%",
            autoheight: true,
            theme : theme,

            // many more configuration options

            columns: [ /* column declaration */ ]
        });

        // events
        $("#jqxgrid").on('cellendedit', function(event) {
            var args = event.args;

            $.post("EditResponse", {
                id: $('#jqxgrid').jqGrid('getCell',args.rowindex,'Name'),
                value: args.value
            });
        });
    });
</script>

Again I omitted (in my opinion) unnecessary details, as the initializaton of jqxgrid works fine, I see the table with every data I want it to show.
But when I edit a cell and end editing, the row
$('#jqxgrid').jqGrid('getCell',args.rowindex,'Name')

yields an error in the console:
TypeError: Object [object Object] has no method 'jqGrid'

I did some research but could not fine a clear explanation. Any experiences what could be wrong? Any import I forgot? Anything in the wrong order?

A: type Error, change
$('#jqxgrid').jqGrid(...

to
$('#jqxgrid').jqxGrid(...


text:
Q: Comparing hibernate-mapped dates? How can i map a date from a java object to a database with Hibernate? I try different approaches, but i am not happy with them. Why? Let me explain my issue. I have the following class [1] including the main method i invoke and with the following mapping [2]. The issue about this approach you can see, when you look at the console output.

false
false
1
-1
1224754335648
1224754335000
Thu Oct 23 11:32:15 CEST 2008
Clock@67064

As you can see the the to dates are not exactly equal, although they should, so it is hard to compare them without goofing around with  return value of getTime. I also tried java.sql.Date, Timestamp and date instead of timestamp in the mapping, but without success.
I wonder why the last three digits are zero and if this is a hibernate or a java issue or my own stupidity.
Thank you for reading.
[1]
public class Clock {

    int id;
    java.util.Date date;

    public static void main(String[] args) {
        HibernateUtil.init();
        HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();

        Clock clock = new Clock();
        clock.date = new java.util.Date();

        HibernateUtil.getSessionFactory().getCurrentSession().saveOrUpdate(clock);
        HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();

        HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();

        Clock fromDBClock = (Clock)HibernateUtil.getSessionFactory()
                        .getCurrentSession().get(Clock.class, 1);

        System.out.println(clock.date.equals(fromDBClock.date));
        System.out.println(fromDBClock.date.equals(clock.date));

        System.out.println(clock.date.compareTo(fromDBClock.date));
        System.out.println(fromDBClock.date.compareTo(clock.date));

        System.out.println(clock.date.getTime());
        System.out.println(fromDBClock.date.getTime());

        System.out.println(clock.date.toString());
        System.out.println(fromDBClock.toString());

        HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();

        HibernateUtil.end();
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public java.util.Date getDate() {
        return date;
    }

    public void setDate(java.util.Date date) {
        this.date = date;
    }

}

[2]
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

    <class name="Clock" table="CLOCK">
        <id name="id" column="CLOCK_ID">
            <generator class="native"/>
        </id>
        <property name="date" type="timestamp"/>

    </class>

</hibernate-mapping>

A: MySql DateTime precision is only to the second.  Java Date precision is to the millisecond.
That is why the last three digits are zeros after it has been put in the database.
Do this to your original Date:
date = date.setTime((date.getTime() / 1000) * 1000);
This will set it to the last exact second, and all your comparisons will then match.
(BTW,
  System.out.println(fromDBClock.toString());
should be
  System.out.println(fromDBClock.date.toString());

A: SQL Server stores datetime with a precision of 3 milliseconds which can definitely cause the problem you're seeing.  One fallout of this is that 23:59:59.999 in Java ends up being the next day in SQL Server.  I've never had a problem with Oracle, Informix, or MySQL, but other databases may have less precision also.  You can work around it by using Hibernate custom types. You have to round to something less precise than the underlying database precision when you write out the date values.  Search for UserType in the Hibernate documentation, you'll be changing the nullSafeSet method to do the rounding.

A: Apparently, TIMESTAMP type on your target RDBMS (what are you using, btw?) doesn't store milliseconds. Try to find another native type that does, or map your time onto something else, like long = ms-since-epoch.

A: Personnaly, I truncate every date I receive in my POJO object with the Apache commons lang package class named DateUtils.
See [Apache commons site][1]
[1]: http://commons.apache.org/lang/api/org/apache/commons/lang/time/DateUtils.html#truncate(java.util.Date, int)


text:
Q: What is the java Vector.element() C# equivalent Here is the java code i incompletely tried to translate
    static Enumeration enumerate()
    {
    Vector list = new Vector();
    Enumeration e = cache.keys();
    while (e.hasMoreElements())
    {
         Vector v = (Vector) cache.get(e.nextElement());
         for (int i = 0; i < v.size(); i++)
         {
         list.addElement(v.elementAt(i));
         }
    }
   return list.elements();
     }

This is the C# translation but not complete
    public static IEnumerable<Http> enumurate()
    {
        List<Http> list = new List<Http>();
        IEnumerator e = cache.Keys.GetEnumerator();
        while (e.MoveNext())/*While e has more element*/
        {
            var vector = (List<Http>)cache[e.Current];
            for (int i = 0; i < vector.Count; i++)
            {
                list.Add(vector.ElementAt<Http>(i));
            }
        }
        return //Something missing!!
    }

Any help please !

A: In C# List<Http> implements IEnumerable<Http> so you can simply return your list:
return list;

To convert the code to C# even more, you could just skip the adding of elements to the list and yield results directly:
public static IEnumerable<Http> enumerate()
{
    IEnumerator e = cache.Keys.GetEnumerator();
    while (e.MoveNext())/*While e has more element*/
    {
        var vector = (List<Http>)cache[e.Current];
        for (int i = 0; i < vector.Count; i++)
        {
            yield return vector.ElementAt<Http>(i);
        }
    }
}

Also, you can avoid using enumerators directly and make the code even more readable:
public static IEnumerable<Http> enumerate()
{
    foreach (var key in cache.Keys)
    {
        foreach (var http in (List<Http>)cache[key])
        {
            yield return http;
        }
    }
}

A: Just return the local list. List<T> implements IEnumerable<T>.

A: In C# you can use LINQ to simplify your code:
public static IEnumerable<Http> enumerate()
{ return cache.Keys.SelectMany(key => (List<Http>)cache[key]); }

Assuming cache is declared as Dictionary<..., List<Http>> you can avoid key lookup by using the Values property:
public static IEnumerable<Http> enumerate()
{ return cache.Values.SelectMany(list => list); }

One important difference between the above and the code that you have now is that the above is not evaluated until you actually try to iterate through the returned collection. If you want to evaluate results immediately, you can add a call to .ToList(). This is equivalent to your original code:
public static IEnumerable<Http> enumerate()
{ return cache.Keys.SelectMany(key => (List<Http>)cache[key]).ToList(); }


text:
Q: How can I achieve following using MVC scaffolding? I have an SQL Server 2008 database.
All tables having a GUID as the primary key, and they are NOT auto-generated. Rather, I want my code to generate it and pass it in INSERT operation.
Some of the tables are having one-to-one or one-to-many relations with other tables.
Is it easy to implement having CRUD operations for such kind of database, where the end-user will not need to worry about GUIDs and all? I searched for tutorials for this, but couldn't find. Can anyone guide me in right direction?
I have MVC 4 in Visual Studio 2010.


text:
Q: Is there a programming term that means property or field? I think this question can span multiple languages, but in C# specifically there is a clear distinction between a field (ex: private int a;) and a property (ex: private int b { get; set; }). While there is often good reason to choose one or the other, in many cases they can be used interchangeably and they serve the same purpose and choosing between them is just a matter of convention.
Is there an umbrella term that includes both of these distinct concepts? Something that means "property or field" without having to say "property or field"? The word "variable" could potentially work but that also includes function-scoped variables and I'm not even sure if it technically includes properties.
I want a word I can use when a value should be stored in a class-scoped data construct but it doesn't matter if it's a field or a property.

A: No, there is not, only the term "field" is describing correctly what you are after.
I think properties should be seen first and foremost as functions (a replacement for "getter" and "setter" pairs), not a direct replacement for fields.  Auto properties  (which were not part of the C# language before version 3.0) create an invisible private field under the hood, but it is still a field which stores the value.
The more general, language independent term from OO modeling is member variable. You can use that, if you prefer a more generic term than "field".

A: I've seen "class member" in the old OO books. Maybe if you post a sentence or paragraph from what you are writing it'll be easier to find the most suitable word.

A:
[...] in many case they [properties or fields] can be used interchangeably [...] and choosing between them is just a matter of convention.

It isn't "just a matter of convention".  In very few cases fields and properties are interchangeable.  The only case I can think of is when a public readonly (or a public const) may be interchangeable with a getter-only property.
Public properties support encapsulation.  You can check the new value in the setter and throw exceptions when it isn't acceptable.  Public fields don't let you do that.

Is there a programming term that means property or field?

It's called "property or field".  Short enough to be used as-is.  [Inspired by this comment.]
edit:
... or even shorter.  Here's an example sentence in which the term would be used:

"If you store the data in a property or field of your ChildDialog class, you'll be able to access that data in StartAsync."  [from O.P.'s comment under another answer]

This works even if you remove the details about the way the data is read from the object, the sentence keeps all of it's meaning and intent.  So, one might rewrite: "If you store the data [or state] in a ChildDialog class, you'll be able to access that data in StartAsync."  The sentence keeps its meaning an intent whether the data is accessed through a property, or a raw field1, or a getter method GetData(...).
1 Don't do that, please.  See above.

A: In python, which had similar distinction between fields and properties (although Python doesn't require any recompilation to switch between the two), the encompassing term is usually "attributes".

A:
While there is often good reason to choose one or the other, in many case they can be used interchangeably and they serve the same purpose and choosing between them is just a matter of convention.

I dispute this assertion. Fields are variables; they are state of an object. Properties are an encapsulation mechanism. Whilst in some simple use cases they can server the same purpose, the power of properties goes way beyond those simple cases.
Properties can be defined within interfaces; they can be defined as one of three states: read-only, read-write and write-only; those read and write states can have different accessibility levels; and they can execute code when used. None of above applies to fields.
Looking for a term to describe fields and properties, but that excludes other members, is to mistakenly assume they are equivalent and thus deserve a special common name. They aren't equivalent and thus they don't deserve a exclusive common name

A: "Value Member" seems appropriate to me. Fields and properties are both members, but they represent values unlike functions.

A: Properties don't store data, the hidden backing field behind the property stores data. Properties provide a way to access that field.
Because of the C# syntax, the distinction between a variable and a property fades. But properties and fields are two very different beasts. A property is more like a method then a it is like a variable.
In general, properties are part of the interface of the class and the fields are part of the state of the class.
That's the nice thing about the properties, you can change the getters and setters  and still have your external representation of your class the same.


text:
Q: Using NRF24L01+ RF chip and antenna I have an NRF24L01+ chip with its antenna. I have three questions on it:

*

*Is it possible to use its antenna without the chip on another board, for example?

*Is it possible to take the power amplifier and use it alone without a microcontroller?

*If the answers to (1) and (2) are 'no', can I use the chip without the need of an Arduino or other microcontroller?


text:
Q: Rails 6.1 Scope merge/join Can anyone point me to documentation that would explain how to do a merged scope in Rails 6.1?
Before 6.1 the following worked:
class Product < ApplicationRecord
  has_many :inventories, dependent: :destroy
  scope :available, -> { joins(:inventories).merge(Inventory.available).group('products.id') }

(giving all products with a positive inventory value)
class Inventory < ApplicationRecord
  belongs_to :product, touch: true
  scope :available, -> { where('number_available > 0') }

Now, I get the following error:
ArgumentError (wrong number of arguments (given 3, expected 2))
Any assistance would be greatly appreciated, thanks :)

A: I got a similar error while updating from Rails 6.0 to 6.1.
I solved it by upgrading the ransack gem to a version >= 2.4.0:
# Gemfile

gem 'ransack', '~> 2.4.0'

Older versions of ransack gem are incompatible with Rails 6.1. Here is the pull request that added support to Rails 6.1:
https://github.com/activerecord-hackery/ransack/pull/1172


text:
Q: SPFx with Office UI Fabric I am trying to create an SPFx solution with office ui Fabric/Fluent UI. I read somewhere that in higher versions of SPFx with react come with pre installed office ui fabric components with in them. So when I created the default SPFx with yeoman generator it created "office-ui-fabric-react": "7.156.0" in the package.json. but when I tried to import text boxes or buttons, it says that module'@fluentui/react/lib/TextField' not found. My SPFx version is 1.12.0. I created the entry of "@fluentui/react": "7.111.0", in my package.json and error was resolved, but when I run the SPFx it shows the component not found error. my node version is 10.18
My question is, is there any specifc version which I should use to run SPFx with office ui fabric?
is office UI fabric and fluent UI are same? Please guide me about the correct versions so that I can fluent ui controls.

A: You should use provided Office UI Fabric React package in SPFx 1.12.1, this is the way Microsoft supports now. Yes, Fluent UI and Office UI Fabric are the same.

Microsoft renamed Office UI Fabric to Fluent UI in early 2020

The primary Fluent UI React package, @fluentui/react, simply exports components from the office-ui-fabric-react package used in SharePoint Framework projects. At this time, you should continue to use the office-ui-fabric-react package in your SharePoint Framework projects.

More details here: Office UI Fabric React & Fluent UI React

A: Fluent UI version 7.178.1, would be supported by SPFX. Try installing the specific version it will solves the problem.


text:
Q: Import {} from location is not found in VS Code using TypeScript and Angular 2 I am trying out the new Angular 2 Forms. My import statements are as follows:
import {bootstrap, onChange, NgIf, Component, Directive, View, Ancestor} from 'angular2/angular2';
import {formDirectives, NgControl, Validators, NgForm} from 'angular2/forms';

import {RegExpWrapper, print, isPresent} from 'angular2/src/facade/lang';

import {reflector} from 'angular2/src/reflection/reflection';
import {ReflectionCapabilities} from 'angular2/src/reflection/reflection_capabilities';

The 'angular2/angular2' resolves fine, but none of the other "from" locations resolve. The error is:

Cannot find module 'angular2/forms'.

All of these components are currently in my node_modules directory. If I put in the full path:
import {formDirectives, ControlDirective, Validators, TemplateDrivenFormDirective} from 'C:/Users/Deb/node_modules/angular2/forms';

then it works. However, I should not need to use the full path. Am I missing something when I set up the tsconfig or is there something else wrong?

A: Problem was that the example application did not match with the version of Angular 2 currently available for download.
If anyone is interested, I now have a working example of Angular2 forms with TypeScript and Visual Studio Code here:
https://github.com/DeborahK/AngularU2015-Angular2Forms
Hope this helps anyone else standing on the "bleeding edge".


text:
Q: How to use multiple instances with the SageMaker XGBoost built-in algorithm? If we use multiple instances for training will the built-in algorithm automatically exploit it? For example, what if we used 2 instances for training using built-in XGBoost container and we used the same customer churn example? Will one instance be ignored?

A: Yes SageMaker XGBoost supports distributed training. If you set instance count > 1, SageMaker XGBoost will distribute the files from S3 to individual instances and perform distributed training. This, however, requires number of files on S3 >= number of instances. Otherwise, you will be charged for using two training instances without the benefit of using distributed training.
You can find an example here
https://github.com/aws/amazon-sagemaker-examples/blob/main/introduction_to_amazon_algorithms/xgboost_abalone/xgboost_abalone_dist_script_mode.ipynb


text:
Q: Is it possible to create flv player's wrapper using AS3 and FlashDevelop only? Is it possible to create flv player's(mainly YouTube Player's) wrapper using AS3 and FlashDevelop only? I am concerned about it because I don't have Flash authoring environment. I have seen many tutorials and in first step (in all of them) are asking to create a .fla file. If you know about it and if it is possible then please let me know. Any help in this regard would be highly appreciated otherwise I'm stuck.
Thanks a lot.

A: Absolutely - I've not used Flash Develop, but I assume it has the ability to compile built in, right?
You can even get more stripped down - all you need is a single ".as" file and you can manually run MXMLC (the Open Source AS3 compiler) to create your .swf. I dug up a tutorial for you here, this should help: http://www.senocular.com/flash/tutorials/as3withmxmlc/

A: Yes it's possible, you can create pure actionscript projects without the Flash IDE.
You can create a project with just .as files and compile the swf out of it.
You could load the graphics externally, for example loading jpg's runtime, or you can embed them. Or you could draw the interface with actionscript.


text:
Q: jQuery ajax always throws error I build a page for mobiles, but i have problem when i send a POST with jQuery.ajax on my phone. It's works on my PC but not on my phone.
I have this code when i make the post request:
        window.jQuery.ajax({
            type: "POST",
            url: "/Action/PageHandler.ashx?do=" + method,
            cache: false,
            data : postFormData,
            dataType: "json",
            success: function (data) {
                DataHandler.GetResult(data, callBack);
            },
            error: function (oXhr, status, msg) {
                callBack(false, msg);
            }
        });

The response when i use my phone is this:
HTTP/1.1 200 OK
Server: ASP.NET Development Server/11.0.0.0
Date: Wed, 25 Dec 2013 17:20:00 GMT
p3p: CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"
Cache-Control: private
Content-Type: application/json; charset=utf-8
Connection: Close
Content-Length: 69

{"ErrorMessage":"Wrong pasword or username!"}

When i run this code on my phone, the error function is called, status = error and msg is empty. I use jQuery mobile.
What's wrong with my code?


text:
Q: Traefik on Swarm Mode in the same host I'm using Traefik as my reverse proxy and it's working perfectly, but I have some concerns about traefik on Swarm mode, because the reverse proxy is in the same host of swarm manager (according to the documentation https://docs.traefik.io/user-guide/swarm-mode/).
Please, could you highlight some problems I can face doing that when I go to Production? Is it really bad having the reverse proxy and swarm manager in the same host? What are the alternatives I have?
Best regards,
M


text:
Q: How to show update messages in PHP? Building a simple login page. If the user types in a password and password confirmation that don't match, I want to reset the registration form and print an message. Currently, the message does not print, but carries on through the script. This is what I've tried, by way of setting a SESSION variable when the error occurs, and showing this variable upon reload:
registration.php:
<?php
    session_start();
    if (isset($_SESSION['errmsg'])) {
        print($_SESSION['errmsg']);
        unset($_SESSION['errmsg']);
    }
?>

<form name="register" action="register.php" method="post">
    Username<input type="text" name="username" maxlength="20" />
    Password<input type="password" name="pass" />
    Password Again<input type="password" name="pass_confirm" />
    <input type="submit" value="Register" />
</form>

register.php:
<?php
function create_salt() {
    $string = md5(uniqid(rand(), true));
    return substr($string, 0, 3);
}

session_start();
$username = $_POST['username'];
$pass = $_POST['pass'];
$pass_confirm = $_POST['pass_confirm'];

if ($pass != $pass_confirm) {
    $_SESSION['errmsg'] = "Passwords do not match.";
    header('Location: registration.php');
}

if (strlen($username) > 20) {
    header('Location: registration.php');
}

$hash = hash('sha256', $pass);
$salt = create_salt();
$hash = hash('sha256', $salt . $hash);

$conn = mysql_connect('localhost', 'test4', 'test4');
mysql_select_db('test4', $conn);

$username = mysql_real_escape_string($username);

$query = "INSERT INTO users (username, password, salt) VALUES ('$username', '$hash', '$salt');";

mysql_query($query);
mysql_close();
header('Location: index.php');
?>

The important part is the line if ($pass != $pass_confirm) { .... Currently if the passwords do not match this condition is met, but it will carry on through the script rather than reloading via header(Location: registration.php). I am aware that header() cannot be invoked after data has been sent, which is probably causing the problem.
If so, is there a better way to do this in PHP or should I be looking at alternatives?

A: If you need to output some data and then possibly choose to redirect, you can use output buffering. This causes the output you've generated to be placed in a buffer instead of being sent to the user.  If you need to redirect, it works because there's no data sent yet.  If you don't redirect, you make use of what's in the buffer and output once the script is done.
See this PHP Manual page to lean much more about PHP output buffering:
http://www.php.net/manual/en/intro.outcontrol.php
Also, note that you're calling header() twice if you have the error - the second header call with the 'location' type will overwrite the first and send you to index.php.
Please see @talereader's answer above - the key is to determine that you're in the error state and call the header (which you do) and then terminate the script immediately.

A: A die(); or exit; solves the problem.
header('Location: registration.php');
die();

A: Why not do all your checking and set a flag if something fails. i.e $failed = true; then before you do any actual processing do if (!$failed) { //process }.


text:
Q: cannot access object user from another php page I'm trying to learn MVC pattern but,even if I'm trying hard, it seems I still got big issues.
I have got a controller,named baseController that do the following:
class baseController {

    public $model;
    public $user;
        ...
        $activeuser = $this->model->getlogin();
        if ($activeuser != 'invalid user' && $activeuser != "") {
                            $this->user=$activeuser;
            header("Location:home.php");
        }

I have got a model.php file which contains the getlogin() function:
public function getlogin() {

    if (isset($_REQUEST['username']) && isset($_REQUEST['password'])) {
        $username = mysql_real_escape_string($_REQUEST['username']);
        $pwd = mysql_real_escape_string($_REQUEST['password']);
        $pwd = md5($pwd);
        $query = mysql_query("SELECT * FROM users WHERE username='$username' AND password ='$pwd' AND attivato =1;");

        if (mysql_num_rows($query) == 1) {
                        require_once 'User.php';
                        $sql=mysql_fetch_array($query);
                        $activeuser = new User();
                        $activeuser->username=$sql['username'];
                        $activeuser->email=$sql['email'];
            return $activeuser;
        } else {
            return 'invalid user'; //TO-DO
        }
    }
}

The home.php create a new homeController and calls its invoke() function.The homeController file include the view page,that's called afterlogin.php.
In the afterlogin.php I've got the "ERROR":
    if (isset($activeuser)){
    echo "
Utente ".$activeuser->username."
";
    echo "
Email ".$activeuser->email."
";}
    //echo "
Pass ".$activeuser->pwd."
";
    echo"
 HOMEPAGE, LOGIN OK
";

It seems the homeController,and so the afterlogin page cannot access the user created in the baseController file. If I try an echo inside the baseController of $this->user->username everything is working. What should I do?? HELP!!

A: The client-server lifecycle is effectively stateless; on every page load, your variables and objects are wiped out.
There are the client-sourced $_POST and $_GET superglobals, which is part of the standard form submission and url query processes.
The server has databases, file writing (sketchy from a security POV) and the $_SESSION superglobal. These are the ways the server can manage a data state between pageloads.
Understand that if you're using objects, you need to have them instantiated on every page load for them to work. You can store your user_ID in $_SESSION['user_ID'] and instantiate the user object from it every time, making appropriate changes according to how the data changes.


text:
Q: What does the output Object[...] in Firebug mean? I am currently logging an object in an AngularJS directive, particularly the parameters of the link() function of the directive. This is the part:
link: function(scope, element, attrs) {
  console.log(attrs)
}

In the console I'll then see this logged:
Object[my-customer.ng-isolate-scope]

When I click the link to more information of the object, it switches from the Console panel to the DOM panel:

So how to read that output? Is it an array of objects?

A: Firebug displays array-like objects like this:
Object[...]

Array-like objects are objects that can be iterated over like arrays, i.e. have indexes. I've created a list of values displayed within the DOM panel.
In this case it is an array-like object that contains the DOM node my-customer.ng-isolate-scope.


text:
Q: Spring Roo How add an empty option to a combo Adding an empty option  is very easy to do in normal HTML/JSP page. But I am using spring roo and the GUI tag libraries it offers.
I need to add an empty option to the combox and be able to validate if a user has slected a non empty  option in this combo box or not. The code generated by Spring roo doesn't have this and first option of my combo box appears to be a non empty option.
Any idea how to extend this behavior and how to do the validation or client and server sides?

A: Spring roo by default creates a combo box with widgetType "dijit.form.FilteringSelect" applied on it , this combo box doesn't contain an empty option.
To add an empty option to it please follow the below steps
In your java code when you are preparing a List for that combo box try to add first option with
code =0 and value = -- Not Selected
and then add all the other options in that list.
A simple java code snipet I am using is
ComboDTO comboDTO=new ComboDTO();
comboDTO.setCode("0");
comboDTO.setDescription("--Not Selected--");
list.add(comboDTO); //This is the list which will be used to populate values in combo box

The option having the code = 0 will be shown as the first element in your combo box. Now if you want it to be mendatory field implement your Validator in and check if the option slected in combo has code=0 send an error back
Sample code for checking the value and sending error back from validator is like below
if(myObject.getFieldCode().equals("0")){
 errors.rejectValue("fieldCode", "required.fieldCode");
}

This way you can have a combo box with an empty option and can check the validity at server side.
Unfortunatly I couldn't find a way to show dojo type notification at client end if the user has not selected a valid option in the combo box. But this is working for me now.


text:
Q: C for loop runs good first iteration only the next iteration it ignores scanf in loop I'm trying to write calculator code in C for loop. The problem it runs good at first iteration only. the next iterations it ignores scanf command so it gives wrong output.
#include <stdio.h>
#include <stdlib.h>

int main(){
int i ;
char operator_;
double x, y;
for (i = 1; i <= 3; ++i)
{
printf("Enter an operator (+, -, *,/): ");
scanf("%c",&operator_);
printf("\nEnter the first number: ");
scanf("%lf",&x);
printf("Enter the second number: ");
scanf("%lf",&y);
switch (operator_) {
case '+':
printf("The sum equals to %lf + %lf = %lf\n\n\n", x, y, x + y);
break;
case '-':
printf("The difference equals to %lf - %lf = %lf\n\n\n", x, y, x - y);
break;
case '*':
printf("The product equals to %lf * %lf = %lf\n\n\n", x, y, x * y);
break;
case '/':
printf("The quotient equals to %lf / %lf = %lf\n\n\n", x, y, x / y);
break;
default:
printf("Error! operator is not correct\n\n\n");
}
}
printf("\nyour trial period has ended\n\n\n");
return 0;

}


text:
Q: Laravel relationship hasMany not working I want to print the name of the user by finding it with 'finished_by' column where id of user is stored. but i get this error:

Trying to get property 'name' of non-object

Inventory model has finished_by which has user ID.
This is mine blade.php
@foreach($inventories as $inventory)

      {{$inventory['id']}}
      {{$inventory->user->name}}

@enforeach

and my index method
$company_id = Auth::user()->company_id;
$inventories = Inventory::where('company_id',$company_id)->get();

return view('inventories', compact('inventories', 'companies'));

And mine relationships
Inventory.php
public function users(){
    return $this->belongsTo(User::class, 'finished_by');
}

User.php
public function inventories(){
    return $this->hasMany(Inventory::class, 'finished_by');
}

A: First change your relationship
Inventory.php
public function user(){
    return $this->belongsTo("App\User", 'finished_by');
}

User.php
public function inventories(){
    return $this->hasMany("App\Inventory", 'finished_by');
}

You need to add user relationship in eager loading
$inventories = Inventory::where('company_id',$company_id)->with('user')->get();

Now Template Rendering

@foreach($inventories as $inventory)

        {{$inventory->id}}

           @if($inventory->user)
              {{$inventory->user->name}}
           @else
              'No User'
           @endif

@enforeach

A: I do not know exactly what fields you have but test this code :
@foreach($inventories as $inventory)

        id : {{$inventory['id']}}
        name : {{$inventory->users->toArray()['name']}}

@endforeach

A: That's because you've defined users in Inventory model but you've called user in your blade file so you must change your function to:
public function user(){
    return $this->belongsTo(User::class, 'finished_by');
}

A: Update the code of controller // you need to add the relationship
$inventories = Inventory::where('company_id',$company_id)->with('user')->get();

A: $company_id = Auth::user()->company_id;
$inventories = Inventory::where('company_id',$company_id)->get();

return view('inventories', compact('inventories', 'companies'));


text:
Q: Can xtext be used as an expression language within Java? We are considering using xtext to develop a DSL that could be used to simplify some complex logic and query operations, but would like to use it in-place, within a Java class. Can this be done?
What we want is to use it to develop something almost like LINQ, but useable within Java. All examples that I have seen of xtext generate .java classes from the DSL, which is great, but not exactly what we want here.
So, something like:
List<ICreature> dragons = dataEngine.parse(get Monster where Type = Dragon and HitPoints > 1000);
I believe we could do this if the queries were pre-written in a separate query file, and then compiled via the xtext generator into a form that could be passed to our data management layer, but we want something more flexible than that.
xText looked promising, but it seems likely we'll end up using jOOQ or something like it instead of a true DSL.

A:
but it seems likely we'll end up using jOOQ or something like it instead of a true DSL.

jOOQ is a true DSL :-) A true internal domain specific language, as opposed to an external DSL. As a matter of fact, I've been looking into Xtend / Xtext recently to see if jOOQ itself could be enhanced to make it look less like Java and more like SQL, by defining an actual grammar for parsing SQL statements and transforming them into jOOQ calls.
This seems to be possible with a technology called Xbase, created by the same guys as the aforementioned Xtend and Xtext. In fact, the Xtend language is based on Xbase. According to their documentation, this will allow you to integrate your own grammar into something that almost looks like Java, and thus to define interaction patterns between Java and your own DSL.
I didn't succeed in understanding their documentation so far, but maybe you could get some help on their forum?

A: No, unfortunately neither Eclipse's Java editor nor the java parser and compiler allow to hook in such that this would be possible. With Xbase you can embed Java-like expressions and statements in your DSL, but the other way round is not supported.


text:
Q: Create tablespace "error in creating database file, access denied (OS 5)" I try to create a database file. I've checked the route and everything, I've tried several times to create the tablespace (I've changed to capital letter, the ' for "...) like this...
create tablespace uinstitucion datafile 'C:\app\uinstitucion\oradata\uinstitucion\uinstitucion.dbf' size 500M ;

file create error, unable to create file", "unable to open file", "(OS 5) access denied" (but I am logged as SYSTEM!)

... as you can see, I was just lead to several errors. What can I do? What am I doing wrong? I'm desperate since yesterday, and my teacher does not seem to notice the exact error.
I've also tried the order like
CREATE TABLESPACE lmtbsb DATAFILE 'file_path/lmtbsb01.dbf' SIZE 50M
EXTENT MANAGEMENT LOCAL AUTOALLOCATE;

but it leads me to the same error.
I'm sorry I cannot post a picture, it would be more descriptive, but I am not allowed yet.

A: Please run your SQLplus as an administrator and then connect and try to execute it.
You error says that you have no privileges to create file. This comes from operating system. Path looks for Windows so please try right click on SQLplus (or any other client you're using), choose run as administrator and then continue.


text:
Q: $f(x,y) = \frac{x^2y}{x^2+y^2}$, $x^2+y^2>0, f(0,0) = 0$, then for all every path differentiable at $0$, $(f\circ \lambda)'(0)$ exists
Suppose $f:\mathbb{R}^2\to\mathbb{R}$ defined by $f(x,y) =
 \frac{x^2y}{x^2+y^2}$, such that $x^2+y^2>0$ and $f(0,0) = 0$. Show
  that for every path $\lambda:(-\epsilon,\epsilon)\to\mathbb{R}^2$
  differentiable at $0$, with $\lambda(0)=(0,0)$, $(f\circ \lambda)'(0)$
  exists

For me, this question was just about using the chain rule:
$$(f\circ \lambda)'(0) = f'(\lambda(0))\lambda'(0)$$
Since $\lambda(0)=0$ exists and also $\lambda'(0)$, I should just show that $f$ is differentiable.
I'd first take the partials at $x$ and $y$:
$$\frac{\partial f}{\partial x} = \frac{2xy}{x^2+y^2} - \frac{x^2y}{(x^2+y^2)^2}$$
$$\frac{\partial f}{\partial y} = \frac{x^2}{x^2+y^2} - \frac{x^2y}{(x^2+y^2)^2}$$
Now remember that a function $f:\mathbb{R}^2\to\mathbb{R}$ is differentiable if there exists $r(v)$ such that
$$f(a+v) = f(a) + \frac{\partial f}{\partial x}v_1 + \frac{\partial f}{\partial y}v_2 + r(v)$$
where $\frac{r(v)}{|v|}\to 0$
So solving for $r(v)$:
$$r(v) = f(a+v)-f(a) - \frac{\partial f}{\partial x}(a)v_1 - \frac{\partial f}{\partial y}(a)v_2$$
*where $v = (v_1,v_2)$
So:
$$\frac{r(v)}{|v|} = \frac{f(a+v)-f(a) - \frac{\partial f}{\partial x}(a)v_1 - \frac{\partial f}{\partial y}(a)v_2}{\sqrt{v_1^2+v_2^2}} $$
But the partial derivatives are not defined on $0$, what should I do here?
If the limit of that thing goes to $0$ when $v\to 0$, $f$ is differentiable.
UPDATE:
By the comment below, the partials at $0$ are $0$, so we end with the following limit:
$$\lim_{v\to 0}\frac{r(v)}{|v|} = \frac{f(a+v)-f(a)}{\sqrt{v_1^2+v_2^2}} =$$
$$\lim_{(v_1,v_2)\to (0,0)} \frac{v_1^2v_2}{\sqrt{v_1^2+v_2^2}}$$

A: Set $\lambda(t) = (\mu(t),\nu(t))$. For now, assume one of $\mu'(0)$ and $\nu'(0)$ is nonzero.
\begin{align*}
(f\circ \lambda)'(0)
&=\lim\limits_{h\to 0} \frac{f(\lambda(h))-f(\lambda(0))}{h}\\
&= \lim\limits_{h\to 0}\frac{\mu^2(h)\nu(h)}{h(\mu^2(h)+\nu^2(h))}\\
&=\lim\limits_{h\to 0}\frac{\mu(h)}{h}\frac{\mu(h)\nu(h)}{\mu^2(h)+\nu^2(h)}\\
&=\lim\limits_{h\to 0}\frac{\mu(h)}{h}\frac{\left(\frac{\mu(h)}{h}\right)\left(\frac{\nu(h)}{h}\right)}{\left(\frac{\mu(h)}{h}\right)^2+\left(\frac{\nu(h)}{h}\right)^2}
=\mu'(0)\frac{\mu'(0)\nu'(0)}{\mu'^2(0)+\nu'^2(0)}.
\end{align*}
If $\lambda'(0) = 0$, then $\lim\limits_{h\to 0}\frac{\mu(h)}{h} = 0$ and $\left|\frac{\mu(h)\nu(h)}{\mu^2(h)+\nu^2(h)}\right|\leq\frac12$ is bounded, so $(f\circ\lambda)'(0)=0$. In any case, $(f\circ\lambda)'(0)$ always exists.
If $f$ were differentiable, then applying the chain rule $(f\circ\lambda)'(0) = f'(\lambda(0))\lambda'(0) = 0$ for every $\lambda$. However, if we take $\lambda(h) = (h,h)$, we have $(f\circ\lambda)'(0)=1/2$. This means that $f$ is not differentiable.
The point of this exercise is to show you that even if $f:\mathbb R^2\to\mathbb R$ is differentiable in every direction (the direction if $\lambda'(0)$ for every $\lambda$, in this case) it  might not be differentiable in the linear map sense. You cannot use the chain rule if you don't know $f$ is differentiable to begin with.


text:
Q: Request doesn't use saved cookies in PersistentCookieStore I fixed the crash and error in my app when I declared a cookie store, but it doesn't save the cookies or something went wrong at an other position.
At first I call these 2 lines:
AsyncHttpClient client = new AsyncHttpClient();
PersistentCookieStore myCookieStore;

And then I have a POST:
public void postRequestLogin(String url, RequestParams params) {
    myCookieStore = new PersistentCookieStore(this);
    client.post(url, params, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(String response) {
            client.setCookieStore(myCookieStore);
            System.out.println(response);

            if(response.contains("Login successful!")) {
                TextView lblStatus = (TextView)findViewById(R.id.lblStatus);
                lblStatus.setText("Login successful!");
                getRequest("url");
            } else {
                TextView lblStatus = (TextView)findViewById(R.id.lblStatus);
                lblStatus.setText("Login failed!");
                TextView source = (TextView)findViewById(R.id.response_request);
                source.setText(response);
            }
        }
    });

}

Then it should save the Logincookies and use it for the GET Request:
public void getRequest(String url) {
    myCookieStore = new PersistentCookieStore(this);
    client.get(url, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(String response) {
            client.setCookieStore(myCookieStore);
            System.out.println(response);
            TextView responseview = (TextView) findViewById(R.id.response_request);
            responseview.setText(response);
        }
    });
}

But it doesn't use the cookies. When I do the GET Request I'm already logged out.
Edit: I forgot to say that I use a lib from this tutorial: http://loopj.com/android-async-http/

A: I think the problem is that you set the cookie store after the request has already completed (in the onSuccess method). Try setting it before you make that request:
myCookieStore = new PersistentCookieStore(this);
client.setCookieStore(myCookieStore);
client.post(url, params, new AsyncHttpResponseHandler() {

You're also creating a new cookie store on every request. What happens if you do more than one request? It will create a new cookie store and use it (and the new cookie store won't have your cookies). Try moving this part of the code to your constructor:
myCookieStore = new PersistentCookieStore(this);
client.setCookieStore(myCookieStore);

Then remove it from the other functions.


text:
Q: Don't put the searched tags on top of Stack Overflow I don't like the new layout. This is how Stack Overflow welcomed me today with my usual tag-search list which I have been using for the past many years (saved in a bookmark). I don't want to see this at the top:

Suggestion: maybe you could implement a feature to store searches and give them a name.

A: This is fixed.
The design didn't really consider pages with multiple tags.  It was really intended for things like:

Public Questions tagged [asp.net]

You can really tell because your header has [asp.net or vb.net or ...] instead of the correct format, [asp.net] or [vb.net] or ....
I've restructured the header for the tags page so if two or more tags are present, the header will more closely resemble the search results header with a short fixed heading followed by a normal sized blurb listing all the tags:

Ironically, this isn't that much shorter than the previous header, but it's a lot prettier, more useful, and consistent with the search results page.


text:
Q: Detection of inverted color mode in a browser do you think there is a way to detect inverted color mode in the browser? There is one thread How to detect MAC OS' inverted color mode in javascript / css?, which is saying it's not possible via CSS or JavaScript.
I have been thinking about rendering pixel in WebGL and then reading it's color value. Not sure how exactly inverted color mode works though.
Any thoughts about this?


text:
Q: как правильно выбрать и вывести ассоциативный массив из связанных таблиц?

Связанные таблицы по skills_id, нужно вывести ассоциативный массив в php ,я делаю так :
db = Db::getconnection();

  $skillslist = [];

  $result = $db->query('SELECT * FROM skills LEFT OUTER JOIN about ON skills.skills_id = about.skills_id');

  $result -> execute();

  while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
    $skillslist[$row['skill_name']][] =$row;

  }
  //$row = $result->FETCHALL(PDO::FETCH_COLUMN|PDO::FETCH_GROUP);

  return $skillslist;


text:
Q: Top and bottom page borders I would like to add some borders to my document similar to the image attached -
one is at the top of the page and the other is around the page number. Can I have some recommendations please?
I attach code containing features similar to what I'm working with. I would like the borders to remain in the same position on each page.
    \documentclass[a4paper,11pt]{article}
\usepackage{tabularx}
\usepackage{booktabs,caption, makecell}
\usepackage{pdflscape,afterpage}
\usepackage{graphicx}
\renewcommand{\theadfont}{\normalsize\bfseries}

\begin{document}
\section{Test}
Video provides a powerful way to help you prove your point. When you click Online Video, you can paste in the embed code for the video you want to add. You can also type a keyword to search online for the video that best fits your document.

To make your document look professionally produced, Word provides header, footer, cover page, and text box designs that complement each other. For example, you can add a matching cover page, header, and sidebar. Click Insert and then choose the elements you want from the different galleries.
Themes and styles also help keep your document coordinated. When you click Design and choose a new Theme, the pictures, charts, and SmartArt graphics change to match your new theme. When you apply styles, your headings change to match the new theme.

\section{Test}
\begin{figure}[h]
\centering
\includegraphics[width=1\textwidth]{Example_figure}
\caption{Test}
\end{figure}

Video provides a powerful way to help you prove your point. When you click Online Video, you can paste in the embed code for the video you want to add. You can also type a keyword to search online for the video that best fits your document.

\begin{landscape}% Landscape page
\begin{table}[ht]
\caption{Table test - contents of table exceeds page width}
\centering
  \small
\begin{tabularx}{\linewidth}{@{}l*{3}{>{\arraybackslash}X}}
\toprule\midrule[0.5pt]
 & \thead{Column 1} & \thead{Column 2} & \thead{Column 3} \\
\midrule
Item 1 & item 1, item 1, item 1, item 1, item 1, item 1, item 1, item 1, item 1 & item 1, item 1, item 1, item 1, item 1,item 1, item 1, item 1, item 1, item 1, item 1 & item 1, item 1, item 1, item 1, item 1, item 1, item 1, item 1 \\
\addlinespace
Item 1 & item 1, item 1, item 1, item 1, item 1, item 1, item 1, item 1, item 1 & item 1, item 1, item 1, item 1, item 1,item 1, item 1, item 1, item 1, item 1, item 1 & item 1, item 1, item 1, item 1 \\
\addlinespace
Item 1 & item 1, item 1, item 1, item 1, item 1, item 1, item 1, item 1, item 1 & item 1, item 1, item 1, item 1, item 1,item 1, item 1, item 1, item 1, item 1, item 1 & item 1, item 1, item 1, item 1 \\
\addlinespace
Item 1 & item 1, item 1, item 1, item 1, item 1, item 1, item 1, item 1, item 1 & item 1, item 1, item 1, item 1, item 1,item 1, item 1, item 1, item 1, item 1, item 1 & item 1, item 1, item 1, item 1 \\
\bottomrule
 \end{tabularx}%
    \hspace*{-12mm}%
\label{table:comparison of techniques}
\end{table}
\end{landscape}

\end{document}

Thanks in advance!

A: Here is  an easy way with titleps, which comes with titlesec, but can be used independently:
\documentclass[a4paper, twoside, 11pt]{article}
\usepackage{tabularx}
\usepackage{booktabs,caption, makecell}
\usepackage{pdflscape,afterpage}
\usepackage{graphicx}
\usepackage{xcolor}
\renewcommand{\theadfont}{\normalsize\bfseries}
\usepackage{titleps}

\newpagestyle{mystyle}{%
\widenhead[\marginparwidth][0pt]{0pt}{\marginparwidth}
\headrule
\sethead[~\color{blue}\thesection\enspace\sectiontitle][][]{}{}{\color{blue}\thesection\enspace\sectiontitle~}
\setfoot[{\makebox[\marginparwidth][r]{\thepage~}\smash{\rule[-20ex]{0.6pt}{22ex}}}][][]{}{}{\smash{\rule[-20ex]{0.6pt}{22ex}}\makebox[\marginparwidth][l]{~\thepage}
}
}%
\pagestyle{mystyle}

\begin{document}

\section{A First Test}
Video provides a powerful way to help you prove your point. When you click Online Video, you can paste in the embed code for the video you want to add. You can also type a keyword to search online for the video that best fits your document.

To make your document look professionally produced, Word provides header, footer, cover page, and text box designs that complement each other. For example, you can add a matching cover page, header, and sidebar. Click Insert and then choose the elements you want from the different galleries.
Themes and styles also help keep your document coordinated. When you click Design and choose a new Theme, the pictures, charts, and SmartArt graphics change to match your new theme. When you apply styles, your headings change to match the new theme.

\section{Another Test}

\begin{figure}[h]
\centering
\includegraphics[width=1\textwidth]{Example-image}
\caption{Test}
\end{figure}

Video provides a powerful way to help you prove your point. When you click Online Video, you can paste in the embed code for the video you want to add. You can also type a keyword to search online for the video that best fits your document.

\begin{landscape}% Landscape page
\begin{table}[ht]
\caption{Table test - contents of table exceeds page width}
\centering
  \small
\begin{tabularx}{\linewidth}{@{}l*{3}{>{\arraybackslash}X}}
\toprule\midrule[0.5pt]
 & \thead{Column 1} & \thead{Column 2} & \thead{Column 3} \\
\midrule
Item 1 & item 1, item 1, item 1, item 1, item 1, item 1, item 1, item 1, item 1 & item 1, item 1, item 1, item 1, item 1,item 1, item 1, item 1, item 1, item 1, item 1 & item 1, item 1, item 1, item 1, item 1, item 1, item 1, item 1 \\
\addlinespace
Item 1 & item 1, item 1, item 1, item 1, item 1, item 1, item 1, item 1, item 1 & item 1, item 1, item 1, item 1, item 1,item 1, item 1, item 1, item 1, item 1, item 1 & item 1, item 1, item 1, item 1 \\
\addlinespace
Item 1 & item 1, item 1, item 1, item 1, item 1, item 1, item 1, item 1, item 1 & item 1, item 1, item 1, item 1, item 1,item 1, item 1, item 1, item 1, item 1, item 1 & item 1, item 1, item 1, item 1 \\
\addlinespace
Item 1 & item 1, item 1, item 1, item 1, item 1, item 1, item 1, item 1, item 1 & item 1, item 1, item 1, item 1, item 1,item 1, item 1, item 1, item 1, item 1, item 1 & item 1, item 1, item 1, item 1 \\
\bottomrule
 \end{tabularx}%
    \hspace*{-12mm}%
\label{table:comparison of techniques}
\end{table}
\end{landscape}

\end{document}

A: Instead of reinventing the wheel, you could simply use the template which was used to create the image you show in your question.
The template can be found at https://bedienhaptik.de/latex-template/
For more information also see Showcase of beautiful typography done in TeX & friends


text:
Q: counting the number of images using php I want to images as a one result.But,when I count it, it didn't get total result.It is showing "count image is->1,count image is->,etc" like this.I want to as a result count image is->2 because I want to check it using if loop."$my_img_url" is total images.
Here is my code
$snd_count+=count($my_img_url);
echo "count image is->" .$snd_count.'<br>';
    if($snd_count >3){....}

A: If your $my_img_url is an array , then count function will give the total number of indexes inside it. You do not need to  use the post increment counter.
$snd_count =count($my_img_url); should do the work itself.
I would suggest you to print what is there in $my_img_url.


text:
Q: How to restart async.operations.all after deleting a product? I'm importing products in bulk. I followed the tutorial at https://devdocs.magento.com/guides/v2.3/rest/tutorials/bulk-configurable-product/config-product-intro.html with our own data.
My scenario is to create the configurable product with all its simple products, then add configurable options and join these simple products with the configurable. Basically, step 2 and 3 from the tutorial.
Everything is running good. I have the RabbitMQ installed and bin/magento queue:consumers:start async.operations.all running. I run it manually.
After the first import, I deleted all the products and reimported them (while async.operations.all console script was still running). The products were created, also the configurable options, but when linking the products, I found this error in magento_operation table "The product was unable to be saved. Please try again."
I set up some logs and I found out this is the problem.
Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (catalog_product_super_attribute, CONSTRAINT CAT_PRD_SPR_ATTR_PRD_ID_CAT_PRD_ENTT_ENTT_ID FOREIGN KEY (product_id) REFERENCES catalog_product_entity (entity), query was: INSERT INTO catalog_product_super_attribute (product_id, attribute_id, position`) VALUES (?, ?, ?)
The problem is that, somehow, the console script thinks the old (deleted) product still exists (in memory???) and is trying to add the old product id in this table, resulting in this error.
When I terminate the console script and start it again, and after deleting the product, everything runs good again.
So my question is. How do I tell Magento to restart this script when I delete a product from admin? Or is there some other way?
I tried to create an observer on "catalog_product_delete_after_done" event with
$this->_pillPut->put() ($this->_pullPut being \Magento\Framework\MessageQueue\PoisonPill\PoisonPillPutInterface), but that doesn't work.
Any help is appreciated.

A: So it turned out that after I enabled the cronjob, it starts and ends the consumers script by itself.


text:
Q: Reading Oracle Java 8 gc logs I have enabled GC logging for one of my application. Here is a part of the log. I have searched around to learn how to read this but it appears a bit different to old articles written ofr java 7 or older. I am specifically interested in the value in marked withh **. Why the value is close but diffferent in each line
GC parameters as printed in log
Java HotSpot(TM) 64-Bit Server VM (25.5-b02) for linux-amd64 JRE (1.8.0_05-b13), built on Mar 18 2014 00:29:27 by "java_re" with gcc 4.3.0 20080428 (Red Hat 4.3.0-8)
Memory: 4k page, physical 8061636k(1507688k free), swap 8355832k(5938840k free)
CommandLine flags: -XX:InitialHeapSize=268435456 -XX:+ManagementServer -XX:MaxHeapSize=268435456 -XX:+PrintGC -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:+UseParallelGC

85.003: [GC (Allocation Failure) [PSYoungGen: 74018K->350K(81408K)] 236281K->162693K(**256512K**), 0.0158446 secs] [Times: user=0.03 sys=0.00, real=0.02 secs]
85.200: [GC (Allocation Failure) [PSYoungGen: 75598K->406K(80896K)] 237941K->162843K(**256000K**), 0.0177163 secs] [Times: user=0.03 sys=0.00, real=0.02 secs]
85.405: [GC (Allocation Failure) [PSYoungGen: 75654K->390K(81920K)] 238092K->162915K(**257024K**), 0.0237740 secs] [Times: user=0.04 sys=0.00, real=0.03 secs]
86.921: [GC (Allocation Failure) [PSYoungGen: 77173K->2579K(81920K)] 239698K->165199K(**257024K**), 0.0315362 secs] [Times: user=0.06 sys=0.00, real=0.03 secs]
87.225: [GC (Allocation Failure) [PSYoungGen: 79373K->512K(81920K)] 241993K->163869K(**257024K**), 0.0306456 secs] [Times: user=0.05 sys=0.01, real=0.03 secs]
87.551: [GC (Metadata GC Threshold) [PSYoungGen: 42769K->594K(81920K)] 206126K->164086K(257024K), 0.0229454 secs] [Times: user=0.04 sys=0.00, real=0.02 secs]
87.574: [Full GC (Metadata GC Threshold) [PSYoungGen: 594K->0K(81920K)] [ParOldGen: 163492K->47257K(**175104K**)] 164086K->47257K(**257024K**), [Metaspace: 53346K->53346K(1099776K)], 0.9669507 secs] [Times: user=1.77 sys=0.01, real=0.97 secs]
89.126: [GC (Allocation Failure) [PSYoungGen: 76792K->1157K(82432K)] 124050K->48423K(257536K), 0.0158828 secs] [Times: user=0.03 sys=0.00, real=0.02 secs]

A: Rather than viewing the log files directly, tools such as "Garbage Collection and Memory Visualizer (GCMV)" will graph the data and provide statistical analysis.


text:
Q: Understanding Pointer to constant pointer to integer constant (const int * const * variable) Given an example
const int limit = 500;
const int * const cpci = &limit;
const int * const * pcpci = &cpci;

I am having difficulty understanding what the last line means.
Basically in array terms the value pcpci it's just an array of (const int * const)'s. But i can't seem to make multiple copies inside pcpci since it is not supposed to be a constant pointer.
For Example
const int limit = 500;
const int * const cpci = &limit;
const int * const * pcpci = &cpci;
const int limit2 = 600;
const int * const cpci2 = &limit2;
*(pcpci+1) = &cpci2;

In the last line of the above code i got "error lvalue must be modifiable". But i was wondering why is this happening since pcpci is not a constant pointer and only it's elements should be constant and non modifiable.

A: First of all this statement
*(pcpci+1) = &cpci;

has undefined behaviour because you may not dereference  a pointer that does not points to an object. You could use this construction if pcpci would point to an element of an array and pcpci + 1 also point to the next element of the same array.
So it would be more coorectly to write
*(pcpci) = &cpci;

However the object pointed to by pcpci is a constant object with type T const where T is const int *  so it may not be reassigned.
That it would be more clear you can rewrite definition
const int * const * pcpci = &cpci;

the following way
typedef const int * const ConstPointerToConstObject;

ConstPointerToConstObject * pcpci = &cpci;

So if to derefernce pcpci you will get an object of type ConstPointerToConstObject that may not be changed because it is a constant pointer to constant object.

A:
But i was wondering why is this happening since pcpci is not a constant pointer

No, but *(pcpci+1) is. It has type const int* const. Obviously you can't assign anything to that.


text:
Q: Loading session needed external website, other than by iFrame I wrote a reservation script that needs users to be logged in first. Works fine. Now I want to embed this scrip on another website, that is running on another server via an iFrame. The problem oembeddccuring is that logged in users lose their session when they are redirected to another page. I found out that this is caused by modern browsers, and has something  to do with security. If you have an session id on one page, and are redirected to another page, you will lose your session id. I found several fixes for this, but all those fixes are not working anymore.
I tried embed and also object calling this external URL, but it is still losing the session. Then I was thinking to rebuild my script, so it is running like an API. The external server loads a JavaScript, and in that JavaScript, ajax is calling all that is necessary.
When a user is logged in, the ajax response send back to the external server contains the session ID. Every time, a paged is requested, this ID should be send along via ajax.Reservetions script picks this up, and treats it like session ID.
My concern, is this going to work or should I use another technique?


text:
Q: The toolbar hides no matter which RecyclerView scrolls I have in layout normal a RecyclerView and in my BottomSheet and the toolbar also hides when the RecyclerView in my BottomSheet scrolls, even if it doesn't have the app:layout_behavior attribute. How can I solve this problem?
<androidx.coordinatorlayout.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android/white"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white"
        app:elevation="0dp">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_scrollFlags="scroll|enterAlways">

            <TextView
                android:id="@+id/titleTextView"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="32dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="32dp"
                android:layout_marginBottom="16dp"
                android:text="Title"
                android:textColor="@android:color/black"
                android:textSize="30sp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"

                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

        </androidx.constraintlayout.widget.ConstraintLayout>
    </com.google.android.material.appbar.AppBarLayout>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/itemRecyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="90dp"
            android:fastScrollEnabled="true"
            android:overScrollMode="never"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </FrameLayout>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/bottomSheet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"

        app:behavior_hideable="false"
        app:behavior_peekHeight="88dp"

        app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">

        <View
            android:id="@+id/bottomSheetShadow"
            android:layout_width="match_parent"
            android:layout_height="4dp"
            android:background="@drawable/bottom_sheet_shadow"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/bottomSheetLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/white"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/bottomSheetShadow">

            <View
                android:id="@+id/bottomSheetSliderView"
                android:layout_width="24dp"
                android:layout_height="4dp"
                android:layout_marginTop="8dp"
                android:background="@drawable/bottom_sheet_slider"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@+id/bottomSheetTitleTextView"
                android:layout_width="match_parent"
                android:layout_height="42dp"
                android:layout_marginStart="16dp"
                android:layout_marginTop="8dp"
                android:layout_marginEnd="16dp"
                android:text="BottomSheetTitle"
                android:textColor="@android:color/black"
                android:textSize="30sp"
                app:layout_constraintEnd_toEndOf="parent"

                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/bottomSheetSliderView" />

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/navRecyclerView"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_marginTop="32dp"
                android:overScrollMode="never"
                app:elevation="0dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHeight_default="wrap"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/bottomSheetTitleTextView" />
        </androidx.constraintlayout.widget.ConstraintLayout>
    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

A: Please use the third flag - snap, to layout_scrollFlags property. It will fix your issue.
  <Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:elevation="5dp"
        app:layout_scrollFlags="scroll|enterAlways|snap" />

This option will determine what to do when a view only has been partially reduced. If scrolling ends and the view size has been reduced to less than 50% of its original, then this view to return to its original size. If the size is greater than 50% of its size, it will disappear completely.

A: AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
params.setScrollFlags(0);

not sure, maybe helps :) if  not please share your xml