text:
Q: CGLContextObj to NSOpenGLView I am tinkering around with FxPlug recently, and I am wondering if it's possible to assign Motion 5/Final Cut Pro X's OpenGL rendering context to an NSOpenGLView loaded from a .xib file. My goal is to draw the current texture drawn in Final Cut's rendering context to my view and use that texture in OpenCV for image processing (via glReadPixels and other assorted jazz).
According to Apple's documentation, I can retrieve an FxRenderInfo struct that contains a CGLContextObj as a shared context. However, I am currently clueless on OpenGL context sharing, I mainly come from an OpenCV background, and most of the documentation in Apple's website is melting my brain at the moment. Is there a set of steps I can reference to in order to get my NSOpenGLView to access another rendering context's resources to draw in it's own context?

A: Create a filter FxPlug and then in FCPX, apply that to the video track you're interested in. That filter will be handed a reference to the current frame (in VRAM if you declare that you support hardware and not software rendering), and you can then do whatever you want with its contents.
By the way, I'd recommend the fxplug mail list. (It's called a Pro Apps Dev list but really it's 99% FxPlug.)
https://lists.apple.com/mailman/listinfo/pro-apps-dev
Despite Apple's notorious secrecy, engineers on the Motion team are allowed to discuss, and are generally very helpful.


text:
Q: ArrayList to ProximityAlert methode onReceive - fatal error I'm trying to receive array in proximity alert. The only thing I could send is one Long. This is how I set proximity alert:
private void setProximityAlert(double lat, double lon, final long eventID, int requestCode)
{
    float radius = 30f;
    LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    Intent intent = new Intent(PROXIMITY_INTENT_ACTION);
    intent.putExtra(ProximityAlert.EVENT_ID_INTENT_EXTRA, eventID);
    intent.putExtra("pole", mPositions);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), requestCode, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    locManager.addProximityAlert(lat, lon, radius, -1, pendingIntent);
}

It doesn't crash when i comment "intent.putExtra("pole", mPositions);".
This is the array:

private ArrayList<LatLonPair> mPositions;

And this is receiver:
public class ProximityAlert extends BroadcastReceiver {

public static final String EVENT_ID_INTENT_EXTRA = "EventIDIntentExtraKey";

@Override
public void onReceive(Context context, Intent intent) {
    long eventID = intent.getLongExtra(EVENT_ID_INTENT_EXTRA, -1);
    ArrayList<LatLonPair> list = (ArrayList<LatLonPair>) intent.getSerializableExtra("list");
    Toast.makeText(context, "Event: " + eventID, Toast.LENGTH_SHORT).show();
}
}

Without the one putExtra it's working, but i need that array. So this is not working for me:
Array List of objects via intent
LogCat error:
FATAL EXCEPTION: main
 java.lang.RuntimeException: Unable to start activity ComponentInfo{co.uk.gauntface.android.proximityalerts/co.uk.gauntface.android.proximityalerts.ProximityDisplay}: java.lang.RuntimeException: Parcel: unable to marshal value co.uk.gauntface.android.proximityalerts.models.LatLonPair@44fb61f0
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
    at android.app.ActivityThread.access$2300(ActivityThread.java:125)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:123)
    at android.app.ActivityThread.main(ActivityThread.java:4627)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:521)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
    at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.RuntimeException: Parcel: unable to marshal value co.uk.gauntface.android.proximityalerts.models.LatLonPair@44fb61f0
    at android.os.Parcel.writeValue(Parcel.java:1116)
    at android.os.Parcel.writeList(Parcel.java:510)
    at android.os.Parcel.writeValue(Parcel.java:1076)
    at android.os.Parcel.writeMapInternal(Parcel.java:479)
    at android.os.Bundle.writeToParcel(Bundle.java:1552)
    at android.os.Parcel.writeBundle(Parcel.java:493)
    at android.content.Intent.writeToParcel(Intent.java:5438)
    at android.app.ActivityManagerProxy.getIntentSender(ActivityManagerNative.java:2206)
    at android.app.PendingIntent.getBroadcast(PendingIntent.java:230)
    at co.uk.gauntface.android.proximityalerts.ProximityDisplay.setProximityAlert(ProximityDisplay.java:91)
    at co.uk.gauntface.android.proximityalerts.ProximityDisplay.registerIntents(ProximityDisplay.java:79)
    at co.uk.gauntface.android.proximityalerts.ProximityDisplay.onCreate(ProximityDisplay.java:43)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
    ... 11 more

This is LatLonPair Class:
package co.uk.gauntface.android.proximityalerts.models;

import android.os.Parcel;
import android.os.Parcelable;

import com.google.android.maps.GeoPoint;

public class LatLonPair implements Parcelable{
private double mLatitude;
private double mLongitude;
private String popis;
private String nadpis;

public LatLonPair() {
    mLatitude = -2.60312596534349;
    mLongitude = 51.4558140934651;
    popis = "Nezadany popis";
    nadpis = "Nezadany nadpis";
}

public LatLonPair(double latitude, double longitude, String popis, String nadpis) {
    mLatitude = latitude;
    mLongitude = longitude;
    this.popis = popis;
    this.nadpis = nadpis;
}

public static boolean isValid(double lat, double lon) {

    if((lon >= -180 && lon <= 180) && (lat >= -90 && lat <= 90)) {
        return true;
    }

    return false;
}

public String getPopis() {
    return popis;
}

public String getNadpis() {
    return nadpis;
}

public void setLatitude(double latitude) {
    mLatitude = latitude;
}

public double getLatitude() {
    return mLatitude;
}

public void setLongitude(double longitude) {
    mLongitude = longitude;
}

public double getLongitude() {
    return mLongitude;
}

public GeoPoint getGeoPoint() {
    return new GeoPoint((int) (mLatitude * 1E6), (int) (mLongitude * 1E6));
}

@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    // TODO Auto-generated method stub

}

}

A: Try calling super(dest,flags) in the overridden writeToParcel method in LatLonPair class

A: Problem was I didn't have implements Parceable and after that it didn't have CREATE. After that it wasn't crashing and the array lenght was OK, but items had default value. I guess problem was with bad implementation of saving variables in Parceable - it reseted itself. So I  gave up and send to broadcastreceiver just few strings I needed there. Thank you all for help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get top 10 user is based on user meta value I'm trying to get top 10 users in my wordpress blog based on user meta value.
I've tried few methods & finally able to get just top one user using below wpdb query. But clueless, how we can get top 10 users.
$top10alltime = $wpdb->get_row( "SELECT MAX( CAST( meta_value AS UNSIGNED ) ) AS top_user FROM $wpdb->usermeta WHERE meta_key = 'alltimeusers'" );

echo $top10alltime->top_user;

Is $wpdb is right for this purpose? Or is there any other solution to get this done? using WP_User_Query?
I've tried something with WP_User_Query.
foreach ( $users as $var => $order ) {
$query->query(
    array(
        'count_total' => false,
        'meta_key' => 'todayuserclicks',
        'orderby' => 'meta_value',
        'fields' => 'ID',
        'number' => 10,
        'order' => $order,
    )
);

I can't get this done after this .. how can we do this?

A: By using get_users() I meant something along the lines of the following:
$args = array(
  'meta_query' => array(
      array(
          'key'     => 'todayuserclicks',
          'compare' => 'EXISTS'
      )
   ),
  'orderby'    => 'meta_value_num',
  'order'      => 'DESC',
  'number'     => '10',
  'fields'     => 'all_with_meta', // does NOT return meta, see below note
);
$todayuserclicks_top_10 = get_users( $args );

Note:
Even with the parameter fields set to all_with_meta no post meta values are included to the result. The documentation for WP_User_Query - Return Fields Parameter it says to this:

'all_with_meta' currently returns the same fields as 'all' which does not include user fields stored in wp_usermeta. You must create a second query to get the user meta fields by ID or use the __get PHP magic method to get the values of these fields.

A: I guess you can do with get_users, something like:
$topusers = get_users( array (
    'meta_key'     => 'todayuserclicks',
    'meta_value'   => '',
    'meta_compare' => '!=',
    'orderby'      => 'meta_value',
    'order'        => 'DESC',
    'number'       => '10',
) );


text:
Q: What is the point of a body tag if divs exist From what I can tell,  tags and
 tags are exactly the same  with one key difference. You can only have one valid body tag in a document. what is the logic of using a body tag if you can use
 instead?

A: In your question, you're overlooking the history. When TBL developed HTML out of the SGML spec (which itself was the ISO's standardized form of ANSI's GCA that developed out of IBM's own in-house GML)... putting content onto a screen was only part of the job.
TBL is also the guy who figured out using text domain names and TLD extensions to stand-in for the numeric IP addresses of servers on the net. He then had to figure out how to give a vast array of different machines, from different manufacturers, running disparate OSs, the ability to display the information as similarly as possible. See how far back this subject must reach?
Anyway, TBL had to break down the protocol communications that occurred between the server and the client, resulting in the creation of (among many other things):
The DOCTYPE
The META tags
The TITLE tag
LINK tags and SCRIPT tags
Along with the content formatting tags like  tags,
 tags,

<h etc> tags,
s, etc
To compartmentalize the document content from the protocol information, TBL separated the  of an HTML document from the  - and he used these words so they would be easily understood as to their purpose.
So yes, perhaps a
 tag could have been used in place of the  tag, and another
 tag could probably even replace the  tag - but that is today, with our current knowledge and understanding of how HTML documents are used. But when they were first being developed, in an age when computers were only beginning to talk to each other, it was a different story. Consider how much the simple DOCTYPE tag has evolved.
Here are some links with some fascinating reading:
A history of HTML
Global structure of an HTML document
HTML Living Standard
HTML Standard FAQ Interesting!


text:
Q: Jquery scrollbar selector I'm working on image gallery project, my problem is when an image is displayed i want to hide it when i click outside the image container.
I use this code to do that, but my is when i click on scrollbar the image is hidden, and i don't want that. i want to add body scrollbar to the code so when i click on it the image doesn't hide.
$(document).mouseup(function (e) {
  var container = $("#overlay_info");
  if (!container.is(e.target) && container.has(e.target).length === 0)
  {
    container.hide();
  }
});

A: There is no such selector, because scrollbars are not part of website, but of browser interface. You can't select it with JavaScript or jQuery for the same reason you can't access browser window's close button.


text:
Q: How to collect the "victory resource" in Catacomb Snatch? I've bombed my way to the pink... liquid in the middle of the catacomb, I've connected it through rails to my base... but nothing seems to happen. Shooting at it doesn't do anything either, although turrets do target it... Bombing does nothing...
What am I supposed to do with it?

A: You must press the railway bulding/removing key on the very first piece of rail, one tile above/below your flag. That creates a (rather dumb) bot for 100 coins that can collect 2% of the "victory resource" for you.
These robots aren't too smart, so don't throw anything too complicated at them. The rails just need to go from your base to the center and back.


text:
Q: How to determine at which temperature does iron in stainless steel undergoes spontaneous oxidation? It is my understanding that iron oxidation in stainless steel is prevented by adding chromium, which creates chromium oxides at the surface that shield the bulk of the material from further oxidation.
I have some stainless steel samples that I heated up to 400°C, and they came out of the oven with signs of oxidation. How can I determine at which temperate will iron start oxidation despite this protective chromium oxide layer? Note that I do not have enough samples to conduct an experiment to find the temperature, I'm looking for a theoretical approach.

A: There is no real, discrete temperature at which an oxidation reaction (or any other chemical reaction for that matter) starts.
Instead reaction rates are dependent on absolute temperature and follow the Arrhenius equation.
In short this means that at low temperatures (e.g. close to room temperature) reaction rates are usually (but not always) almost infinitesimally small and then increase as temperature is increased. There is however no discrete temperature at which the reaction can be said to 'start'.
To get a better idea of this rate/temperature dependence, chemists will usually perform an Arrhenius plot.

A: Stainless steels are indeed protected by an extremely tightly-adherent, conformal coating of chromium oxide which forms the instant that the part is first exposed to air. This coating is optically transparent because of its thinness- only a few tens of atoms thick- but it protects the material underneath it because the rate at which oxygen can diffuse through it is extremely slow.
When it is heated as in your furnace, the diffusion rate is increased and so the creation of chrome oxide is "turned on" again until such time as the thickened oxide begins to choke off the diffusion of oxygen again, and the thickness of the oxide stabilizes.
This temperature-dependent, diffusion-limited and self-limiting pattern of behavior is called self-passivation and greatly complicates the dynamics of high-temperature corrosion.
As the oxide layer thickens, it begins to show optical interference effects between the front and back surfaces of the layer- and instead of appearing perfectly colorless, the film gets colored- first a light yellow which darkens into orange and then a brilliant blue as the film thickens. This color pattern then fades out and repeats; by counting these "fringes" you can accurately estimate the total thickness of the oxide.


text:
Q: How can i tell if this repository is using python3 or 2? https://github.com/tekno45/dndchar
I forked this repository and i'd like to work on it at work. Is there a way to tell if it's written in 3 or 2?

A: It's written in Python 2.
The biggest hint is that print is a statement there, not a function.


text:
Q: Is it possible to upload a "FlatFile Source" into "CosmosDB" using "SSIS"? (CoreSQL) always get this error My Account of Cosmos DB is CORE (SQL), i've been trying what seems an easy test, upload a flat file source into a container in CosmosDB using SSIS.
My CosmosDB Container is called test, only has one item and the schema is the following
"id"= which is the required field to create an item
"_*"= non required fields created by CosmosDB

*

*I have a flat file with only one string and i set it as column "id".

*Downloaded the ODCB Driver and proceed to configure the connection using the Keys provided by Azure CosmosDB which they return an OK when testing them.

*Mapped the column from the flat file source into the column from the destination
both as DT_WSTR and press run.
always return this error, if i try with numbers only changes the first number

*

*With only string

[ODBC Destination [15]] Error: Open Database Connectivity (ODBC) error occurred. SQLExecute returned error while inserting row 1

*

*With only numbers

[ODBC Destination [42]] Error: Open Database Connectivity (ODBC) error occurred. SQLExecute returned error while inserting row 1

Is it even possible to upload a flat file source into CosmosDB?
thanks

A: Well after struggling for a few days there's a way to upload a flat file into CosmosDB using SSIS.
When you create a container into CosmosDB you also add a partitionKey this partitionKey name NEEDS to be inside the flat file even if it doesnt appear in the schema or it seems to be required IT IS REQUIRED
So lets say your container looks like this  id, Zipcode (partitionKey)
your file should contain the ID and the Zipcode for it to map it into the CosmosDB
ID AND PARTITION KEY ARE ALWAYS DT_WSTR


text: Q: Возможно ли передавать данные с веб-страницы(использую JavaScript) Windows приложению? Пример: Есть web-страница, при её открытии в браузере нужно передать windows приложению информацию, допустим исходный код страницы, и всё это(передачу данных) нужно сделать с помощью JavaScript. Возможно ли это? Если да, то как?


text:
Q: Was the text on the magazine cover intentional? The 1985 film Weird Science shows two teenage boys (Gary and Wyatt) creating a woman with their computer.  In the process of creating the perfect woman, they insert several photos into their computer for data.
One particular photo that they insert shows what looks like a magazine cover with a photo of Kelly LeBrock who is the actress portraying "Lisa" (the girl that the two boys ultimately create)
There appears to be what looks like the words "Lisa" and "Talks" to the right of the photograph.

Later in the movie, Gary suggests the name "Lisa" to be given to her as her name.
Out of universe, Kelly LeBrock was a model before becoming an actress and was on the cover of several magazines.
Is there any evidence that this magazine cover existed out of universe?  Did filmmakers choose to name the character based on the text that was on the magazine or was this simply created for the film with those specific words on it?

A: My guess is that's it was a mock up made for the movie, so the text would be deliberate. It doesn't match any of her covers I've found posted on the web. I did find this scan of a magazine page that appears to use the same photograph, although I haven't been able to source it.


text:
Q: Why does 'abc'[-1] result in 'c' rather than 'b'? I thought that it started counting backwards from the start, so A is 0, B is -1 and C is -2.

A: As Henry pointed out, negative indices indicate counting from the right.
Naturally, A is 0, B is 1 and C is 2, when counting from the left:
->  ->  ->

A | B | C

0 | 1 | 2

When going backwards, -1 is the end of the array, like so:
<- <- <-
A | B| C
-3|-2|-1

For more context, look at it like this, as if two copies were lined up:
A | B | C | A | B | C
-3| -2| -1| 0 | 1 | 2

According to the documentation String and List objects support negative indices, but Range objects to not.

A: A negative index means "start counting from the right".

Put another way: sequence[0] is the start of the sequence, why would you expect sequence[-1] to be anything other than the end of the sequence?
 0    1    2
 a    b    c

-3   -2   -1
 a    b    c


text:
Q: Django ORM filter records between last month 15th date to current month 15th date I want to filter the queryset records from the previous month's 15th date to the current month 15th.
Does someone have any idea how to do it?

Models.py

class Book(models.Model):
    name = models.CharField(max_length=100, null=True)
    author = models.CharField(max_length=100, null=True)
    created_on = models.DateTimeField(auto_now_add=True)

Views.py

class BookView(View):
    def get(self, *args, **kwags):
        start_date = '15th_of_previous_month'
        end_date = '15th_of_current_month'
        qs = Book.objects.filter(created_on__gte=start_date,created_on__lt=end_date)
        ...

A: You can obtain the 15th of the current month with:
from django.utils.timezone import now

this_month_15 = now().date().replace(day=15)
Calculating the previous month can be done by subtracting 15 days, and then again replace the day parameter with 15:
from datetime import timedelta

prev_month_15 = (this_month_15 - timedelta(days=15)).replace(day=15)

A:
This is how I try to solve it:

import datetime

today = datetime.date.today()
first = today.replace(day=1)  # first date of current month
previous_month_date = first - datetime.timedelta(days=1)  # this will be the last day of previous month
start_date = datetime.datetime.strptime(str(previous_month_date.year) + '-' + str(previous_month_date.month) + '-15', '%Y-%m-%d')
end_date = first + datetime.timedelta(days=15)
qs = Book.objects.filter(created_on__gte=start_date,created_on__lt=end_date)


text:
Q: Python Value error I'm getting an error when trying to split a piped output into python.
Error is need more than 3 values to unpack although I'm using 8 values
import subprocess, sys

from datetime import datetime

from time import sleep as sleep

multimon_ng = subprocess.Popen("multimon-ng -a FLEX -t wav flex.wav",
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    shell=True)

while True:
        nextline = multimon_ng.stdout.readline()
        flex, mdate, mtime, bitrate, other, capcode, o2, msg  = nextline.split(" ", 7)      # error here
        if nextline is " ":
            print "napping"
        else:
            print mdate + " " + mtime + " " + capcode + " " + msg

        multimon_ng.poll()
        sys.stdout.flush()

any help would be great

A: 3 in error message indicated length of iterable in right hand side argument.
Minimal wrong examples:
a, = []  # ValueError: need more than 0 values to unpack
a, b = [1]  # ValueError: need more than 1 value to unpack
a, b, c = [1, 2]  # ValueError: need more than 2 values to unpack
# etc ...

Minimal correct examples:
a, = [1]
a, b = [1, 2]
a, b, c = [1, 2, 3]

Smallest change to fix and expose issue would be to wrap unpacking iterable in try-except block.
while True:
    nextline = multimon_ng.stdout.readline()

    if not nextline:
        print "napping"
    else:
        try:
            flex, mdate, mtime, bitrate, other, capcode, o2, msg  = nextline.split(" ", 7)
        except ValueError:
            print "invalid line", nextline
        else:
            print mdate + " " + mtime + " " + capcode + " " + msg

    multimon_ng.poll()
    sys.stdout.flush()

As you can see, I also moved check for empty line before unpacking. If line is empty, unpacking would also fail.


text:
Q: indexing multiple keys for random queries in different combinations of keys I'm building an application that stores lots of data per user (possibly in gigabytes).
Something like a request log, so lets say you have the following fields for every record:
customer_id
date
hostname
environment
pid
ip
user_agent
account_id
user_id
module
action
id
response code
response time (range)

and possibly some more.
The good thing is that the usage will be mostly write only, but when there are reads
I'd like to be able to answer then quickly in near real time.
Another prediction about the usage pattern is that most of the time people will be looking at the most recent data,
and infrequently query for the past, aggregate etc, so my guess is that the working set will be much smaller then
the whole database, i.e. recent data for most users and ranges of history for some users that are doing analytics right now.
for the later case I suppose its ok for first query to be slower until it gets the range into memory.
But the problem is that Im not quite sure how to effectively index the data.
The start of the index is clear, its customer_id and date. but the rest can be
used in any combination and I can't predict the most common ones, at least not with any degree of certainty.
We are currently prototyping this with mongo. Is there a way to do it in mongo (storage/cpu/cost) effectively?
The only thing that comes to mind is to try to predict a couple of frequent queries and index them and just massively shard the data
and ensure that each customer's data is spread evenly over the shards to allow fast table scan over just the 'customer, date' index for the rest
of the queries.
P.S. I'm also open to suggestions about db alternatives.

A: with this limited number of fields, you could potentially just have an index on each of them, or perhaps in combination with customer_id. MongoDB is clever enough to pick the fastest index for each case then. If you can fit your whole data set in memory (a few GB is not a lot of data!), then this all really doesn't matter.
You're saying you have a GB per user, but that still means you can have an index on the fields as there are only about a dozen. And with that much data, you want sharding anyway at some point soon.
cheers,
Derick

A: I think, your requirements don't really mix well together. You can't have lots of data and instantaneous ad-hoc queries.
If you use a lot of indexes, then your writes will be slow, and you'll need much more RAM.
May I suggest this:
Keep your index on customer id and date to serve recent data to users and relax your requirements to either real-timeliness or accuracy of aggregate queries.
If you sacrifice accuracy, you will be firing map-reduce jobs every once in a while to precompute queries. Users then may see slightly stale data (or may not, it's historical immutable data, after all).
If you sacrifice speed, then you'll run map-reduce each time (right now it's the only sane way of calculating aggregates in a mongodb cluster).
Hope this helps :)


text:
Q: Reduce the time complexity of the code to find duplicates in an Array from N*N I was recently asked in an interview to write code to determine if an array of integers contains duplicates simple as it was i confidently told him that i would iterate the elements  and add each one to an new array if the array doesn't contain  the element already if it does i return true else return false  complexity
the code would be like this
//complexity is N*N
    public static boolean findIfArrayHasDuplicates(int[] array){

        int[] newArr = new int[array.length];
        List<Integer> intList = new ArrayList<Integer>();

        for (int var: array){
            if(intList.contains(var)){
                return true;
            }else{
                intList.add(var);
            }
        }
        return false;
    }
}

He asked me to calculate the time complexity of the code i have written
I answered
N for iteration of the loop
N(N+1)/2 for finding if the element exists in in new list
N for adding the elements in the list
total N +N + N*N/2 + N/2  in O() notation multiplying by 2 and simplifying as N tends to infinity this can be simplified O(N^2)
he went on to ask me if there is any better way i answered add the elements to a set and compare the size if the size of set is less than than of the array it contains duplicates , asked what is the complexity of it guess what its still O(N^2) because of the code that adds elements to the set will have to first see if its in the set already .
How can I reduce the complexity from O(N^2) using as much as memory needed.
Any ideas how this can be done ?

A:
he went on to ask me if there is any better way i answered add the elements to a set and compare the size if the size of set is less than than of the array it contains duplicates , asked what is the complexity of it guess what its still NN because of the code that adds elements to the set will have to first see if its in the set already

That's wrong. If you are adding the elements to a HashSet, it takes expected O(1) time to add each element (which includes checking if the element is already present), since all you have to do is compute the hashCode to locate the bin that may contain the element (takes constant time), and then search the elements stored in that bin (which also takes expected constant time, assuming the average number of elements in each bin is bound by a constant).
Therefore the total running time is O(N), and there's nothing to improve (you can't find duplicates in less than O(N)).

A: I think it would be useful if you would look at basic working mechanisms of a HashSet. A HashSet is internally an array, but data accesses, such as "checking if an element exists", or "adding/deleting an element", is of time complexity O(1), because it takes on a mapping mechanism to map an object to the index storing it. For example, if you have a HashSet and an integer and you do a hashSet.contains(integer), the program will first take the integer and calculate the hash code of it, and then use the mapping mechanism (differs from implementation to implementation) to find the index storing it. Say we have a hash code of 4, and we map to an index of 4 using the simplest mapping mechanism, then we will check if the 4th element of the underlying array is empty. If it is, hashSet.contains(integer) will return true, otherwise false.

A: The complexity of code provided is O(N^2). However, the code given follows is complexity O(N). It uses HashSet, which required O(1) operation to insert and search.
    public static boolean findIfArrayHasDuplicates(int[] array){

            HashSet<Integer> set = new HashSet<Integer>();
            set.add(array[0]);

            for (int index = 1; index < array.length; index++) {
                    if(!set.add(array[index]))
                            return true;
            }

            return false;
     }


text:
Q: How to see the connectivity status for each device directly from UI in zenoss monitoring This question is related to zenoss monitoring.
I want to know how to see the connectivity status for each device directly from zenoss UI page instead from terminal.

A: Open your device and DEVICE STATUS is result of last Zenoss "ping" check. Or you can run "Commands" -> "ping", if it's available:


text:
Q: Cannot Use Pip Within Venv I'm aware there are many similar questions but I have been through them all to no avail.
On Ubuntu 18.04, I have Python 2 and Python 3.6.  I create a venv using the command below and attempt to install a package using pip.  However, it attempts to install on the global system and not in the venv.
python3 -m venv v1
When I run 'which python' it correctly picks the python within the venv.  I have checked he v1/bin folder and pip is installed.  The path within the pip script is correctly pointed to toward python in the venv.
I have tried reinstalling python3 and venv, destroying and recreating the virtual environment and many other things.  Wondering is there some rational way to understand and solve this.

A: The problem in my case was that the mounted drive I was working on was not mounted as executable.  So pip couldn't be executed from within the venv on the mount.
This was confirmed because I was able to get a pip install using 'python -m pip install numpy' but when importing libraries, e.g. 'import numpy', was then faced with further error of:
multiarray_umath.cpython-36m-x86_64-linux-gnu.so: failed to map segment from shared object
which led back to the permissions issue as per github issue below.  Fix for that by dvdabelle in comments then fixes dependent and original issue.
https://github.com/numpy/numpy/issues/15102
In his case, he could just switch drive. I have to use this drive.  So the fix was to unmount my /data disk where I was working and remount it with exec option!
sudo umount /data
sudo mount -o exec /dev/sda4 /data
'which pip' now points to the pip in the venv correctly
Note: to make it permanent add the exec switch to the line for the drive in fstab  as per https://download.tuxfamily.org/linuxvillage/Informatique/Fstab/fstab.html (make exec the last parameter in the options or user will override it) E.g.
UUID=1332d6c6-da31-4b0a-ac48-a87a39af7fec    /data  auto    rw,user,auto,exec    0    0


text:
Q: How to disable omnifunc autowrite suggestions I am new to vim and I installed vim-go today. I set up auto completion with gopls with omnifunc set as go#complete#Complete. It works as expected but it always writes the current suggestion automatically. this is very annoying since it always writes the suggestion without me accepting it.

A: It turns out the problem was the default value of completeopt option in vim. editing it to have the value noinsert solved the problem. add the following line in ~/.vimrc
set completeopt=menuone,popup,noinsert
The above is just an example. the values except noinsert are just my own preferences.


text:
Q: How do I run a node container on AWS ECS without exiting I'm struggling to keep my node.js container running on ECS. It runs fine when I run it locally with docker compose, but on ECS it runs for a 2-3 mins and handles a few connections (2-3 health checks from the load balancer), then closes down. And I can't work out why.
My Dockerfile -
FROM node:6.10

RUN npm install -g nodemon \
    && npm install forever-monitor \
    winston \
    express-winston

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

COPY package.json /usr/src/app/
RUN npm install

COPY . /usr/src/app

EXPOSE 3000

CMD [ "npm", "start" ]

Then in my package.json -
{
  ...
  "main": "forever.js",
  "dependencies": {
    "mongodb": "~2.0",
    "abbajs": ">=0.1.4",
    "express": ">=4.15.2"
  }
  ...
}

In my docker-compose.yml I run with nodemon -
node:
  ...
  command: nodemon

In my cloudWatch logs I can see everything start -
14:20:24  npm info lifecycle my_app@1.0.0~start: my_app@1.0.0

Then I see the health check requests (all with http 200's), then a bit later it all wraps up -
14:23:00  npm info lifecycle mapov_reporting@1.0.0~poststart: mapov_reporting@1.0.0
14:23:00  npm info ok

I've tried wrapping my start.js script in forever-monitor, but that doesn't seem to be making any difference.
UPDATE
My ECS task definition -
{
  "requiresAttributes": [
    {
      "value": null,
      "name": "com.amazonaws.ecs.capability.ecr-auth",
      "targetId": null,
      "targetType": null
    },
    {
      "value": null,
      "name": "com.amazonaws.ecs.capability.logging-driver.awslogs",
      "targetId": null,
      "targetType": null
    },
    {
      "value": null,
      "name": "com.amazonaws.ecs.capability.docker-remote-api.1.19",
      "targetId": null,
      "targetType": null
    }
  ],
  "taskDefinitionArn": "arn:aws:ecs:us-east-1:562155596068:task-definition/node:12",
  "networkMode": "bridge",
  "status": "ACTIVE",
  "revision": 12,
  "taskRoleArn": null,
  "containerDefinitions": [
    {
      "volumesFrom": [],
      "memory": 128,
      "extraHosts": null,
      "dnsServers": null,
      "disableNetworking": null,
      "dnsSearchDomains": null,
      "portMappings": [
        {
          "hostPort": 0,
          "containerPort": 3000,
          "protocol": "tcp"
        }
      ],
      "hostname": null,
      "essential": true,
      "entryPoint": null,
      "mountPoints": [],
      "name": "node",
      "ulimits": null,
      "dockerSecurityOptions": null,
      "environment": [
        {
          "name": "awslogs-group",
          "value": "node_logs"
        },
        {
          "name": "awslogs-region",
          "value": "us-east-1"
        },
        {
          "name": "NODE_ENV",
          "value": "production"
        }
      ],
      "links": null,
      "workingDirectory": null,
      "readonlyRootFilesystem": null,
      "image": "562155596068.dkr.ecr.us-east-1.amazonaws.com/node:06b5a3700df163c8563865c2f23947c2685edd7b",
      "command": null,
      "user": null,
      "dockerLabels": null,
      "logConfiguration": {
        "logDriver": "awslogs",
        "options": {
          "awslogs-group": "node_logs",
          "awslogs-region": "us-east-1"
        }
      },
      "cpu": 1,
      "privileged": null,
      "memoryReservation": null
    }
  ],
  "placementConstraints": [],
  "volumes": [],
  "family": "node"
}

Tasks are all stopped with the status Task failed ELB health checks in (target-group .... Health checks pass 2 or 3 times before they start failing. And there's no record of anything other than an http 200 in the logs.

A: I was using an old version of the mongo driver ~2.0, and keeping connections to more than one db. When I upgraded the driver, the issue went away.
  "dependencies": {
    "mongodb": ">=2.2"
  }

I can only assume that there was a bug in the driver.


text:
Q: Defining a sphere Let $c$ be a number, and let $a$ and $b$ be vectors in $R^3$. Let x = $(x, y, z)$. Show that the equation (x$-a)\cdot($x$-b)=c^2$ defines a sphere with centre whose position vector is $1/2(a+b)$ and radius $[c^2+|1/2(a-b)|^2]^{1/2}$.
My working:
Letting x = $(x, y, z)$, $b = (b_1, b_2, b_3)$, $a = (a_1, a_2, a_3)$,
(x$-a)\cdot($x$-b)=c^2$
$|x|^2 - b \cdot x - a \cdot x+a \cdot b=c^2$
$x^2+y^2+z^2-(b_1x+b_2y+b_3z)-(a_1x+a_2y+a_3z)+(b_1a_1+b_2a_2+b_3a_3)-c^2=0$
$x^2+y^2+z^2+b_1a_1(1-x)+b_2a_2(1-y)+b_3a_3(1-z)-c^2=0$
After simplification, I get
$(x-\frac{b_1a_1}{2})^2+(y-\frac{b_2a_2}{2})^2+(z-\frac{b_3a_3}{2})^2=c^2-a \cdot b+\frac{(b_1)^2(a_1)^2}{4}+\frac{(b_2)^2(a_2)^2}{4}+\frac{(b_3)^2(a_3)^2}{4}$
From here, I am unsure of how to further simpify to prove the given position vector and radius, may I have some help please?

A: You can do it like this. For $r \in \mathbb{R}^3$ let us write $r^2 = r \cdot r = \lvert r  \rvert^2$. Moreover, let us write $p = (x,y,z)$ instead of x. Then
$$c^2 = (p -a) \cdot (p - b) = p^2 -(a + b) \cdot p + a \cdot b \\
=  p^2 -(a + b) \cdot p + \left((-\frac{1}{2})(a + b)\right)^2 - \left((-\frac{1}{2})(a + b)\right)^2 + a \cdot b \\
= \left(p -\frac{1}{2}(a + b) \right)^2 - \left(\frac{1}{2}(a - b) \right)^2  \\
$$
and we are done.

A: Probably simpler to work backwards. If $\vec x$ lies on a sphere with centre $\vec{O}$ and radius $r$ then
$|\vec x - \vec O|^2 = r^2 \\ \Rightarrow (\vec x - \vec O) \cdot (\vec x - \vec O) = r^2 \\ \Rightarrow \vec x \cdot \vec x -2\vec x \cdot \vec O = r^2 - \vec O \cdot \vec O \qquad (1)$
Expanding $(\vec x- \vec a) \cdot (\vec x-\vec b) = c^2$ we have
$\vec x \cdot \vec x - \vec x \cdot (\vec a  + \vec b) = c^2 - \vec a \cdot \vec b \qquad (2)$
Comparing $(1)$ and $(2)$ we have
$\vec O = \frac{\vec a + \vec b}{2}$
$r^2 = c^2 - \vec a \cdot \vec b  + \vec O \cdot \vec O = c^2 -\frac{\vec a \cdot \vec a - 2 \vec a \cdot \vec b + \vec a \cdot \vec a}{4} = c^2 - \left | \frac{\vec a - \vec b}{2}\right |^2$


text:
Q: Calculating transformation of an object in an image using OpenCV I have two images.
Say one is a 10x10 which we call trainImage and then there is another queryImage which is the same chessboard photographed using a phone camera. Now I have to find the position of camera in (x,y,z) coordinates. Using openCV and feature detection I have been able to identify the chessboard object in photographed object, but how to go ahead with calculating the transformations on chessboard so that I can eventually calculate the position of camera. Any pointers to start looking upon will also be really appreciated. Thanks.
Edit:
Reframing the problem statement again, I have two images trainImage and queryImage. I need to find the position of camera i.e. (x,y,z) if we assume that trainImage is at (0,0,0) in queryImage. I did some reading to find this I need rvec(rotation vector) and tvec(translation vector).
When I use findHomography() function on two images I get a 3x3 homgraphy matrix using which I can find the pixels points(x,y) in queryImage by multiplying to pixel points(x,y) in trainImage. How can I use this homographyMatrix for calculating tvec and rvec.


text:
Q: gprof : How to generate call graph for functions in shared library that is linked to main program I am working on Linux environment. I have two 'C' source packages train and test_train.

*

*train package when compiled generates libtrain.so

*test_train links to libtrain.so and generates executable train-test

Now I want to generate a call graph using gprof which shows calling sequence of functions in main program as well as those inside libtrain.so
I am compiling and linking both packages with -pg option and debugging level is o0.
After I do ./train-test , gmon.out is generated. Then I do:
$ gprof -q ./train-test gmon.out

Here, output shows call graph of functions in train-test but not in libtrain.so
What could be the problem ?

A: I'm loading my library from Python and didn't have any luck with sprof. Instead, I used oprofile, which was in the Fedora repositories, at least:

operf --callgraph /path/to/mybinary
Wait for your application to finish or do Ctl-c to stop profiling. Now let's generate a profile summary:
opreport --callgraph --symbols

See the documentation to interpret it. It's kind of a mess. In the generated report, each symbol is listed in a block of its own. The block's main symbol is the one that's not indented. The items above it are functions that call that function, and the ones below it are the things that get called by it. The percentages in the below section are the relative amount of time it spent in those callees.

A: gprof won't work, you need to use sprof instead.  I found these links helpful:

*

*How to use sprof?

*http://greg-n-blog.blogspot.com/2010/01/profiling-shared-library-on-linux-using.html
Summary from the 2nd link:

*

*Compile your shared library (libmylib.so) in debug (-g) mode. No -pg.

*export LD_PROFILE_OUTPUT=`pwd`

*export LD_PROFILE=libmylib.so

*rm -f $LD_PROFILE.profile

*execute your program that loads libmylib.so

*sprof PATH-TO-LIB/$LD_PROFILE $LD_PROFILE.profile -p >log

*See the log.

I found that in step 2, it needs to be an existing directory -- otherwise you get a helpful warning.  And in step 3, you might need to specify the library as libmylib.so.X (maybe even .X.Y, not sure) -- otherwise you get no warning whatsoever.

A: If you're not on Linux (like me on Solaris) you simply out of luck as there is no sprof there.
If you have the sources of your library you can solve your problem by linking a static library and making your profiling binary with that one instead.
Another way I manage to trace calls to shared libraries, is by using truss. With the option -u [!]lib,...:[:][!]func, ... one can get a good picture of the call history of a run. It's not completely the same as profiling but can be very usefull in some scenarios.


text:
Q: How to set a hidden field from a Check box selection in jquery and passing it to the controller action method? I want to set the Hidden field in jquery for selected checkboxes. A user can select multiple checkboxes. I have multiple checkboxes which I want to save as comma separated value in Database. I am doing this with help of jquery and setting it using hidden field but no luck.

<input type="checkbox" class="Course" name="Courses" id="CoursesScience" value="Science">Science

<input type="checkbox" class="Course" name="Courses" id="CourseMath" value="Math">Math

<input type="checkbox" class="Course" name="Courses" id="CourseIt" value="IT">IT

<input type="checkbox" class="Course" name="Courses" id="CourseCommerce" value="Commerce">Commerce

<input type="checkbox" class="Course" name="Courses" id="CourseEnglish" value="English">English

<input type="hidden" name="CoursesSelected" id="CoursesSelected" />

In jquery
var Values = [];
$('.Course').change(function () {
    if (this.checked) {
        Values.push($(this).val());
    }
    else{
        Values.pop(this);
    }
});
$('#CoursesSelected').val(Values).appendTo('form');

This is not working as when I pop the value it pop last instance save in the array but not the one which is being deselected.
1) Also please tell me how I can access the hidden field in a controller.
2) Will this hidden field populate the property Courses in my class.
public partial class Register
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Class { get; set; }
    public string Courses { get; set; }
    public string Gender { get; set; }
}

A: You should not need to use jquery or a hidden field. Instead I would use a view model. Create a new class that only contains the information you want to post from your view, e.g:
public class RegisterViewModel
{
    public string Name { get; set; }
    public string Class { get; set; }
    public string[] Courses { get; set; }
    public string Gender { get; set; }
}

I don't know what your controller action looks like, but it should now be something like:
[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
  //Map the data posted to the form to your Register class
  var student = new Register();
  student.Name = model.Name;
  student.Class = model.Class;
  student.Gender = model.Gender;
  if (model.Courses != null)
    student.Courses = String.Join(",", model.Courses);

  //Then do whatever you need to do to save the data to the database
}

When you post your form, the Courses array should contain an element whose value is the id for each checkbox that has been ticked, e.g. ["CourseMath", "CourseCommerce"].


text:
Q: how to decode .dSYM file to explicit DWARF format? DWARF is a debugging information format. The .dSYM file generated by Xcode contain the DWARF debugging information.
The Question is : how to decode the .dSYM file to get the human-readable DWARF information, which should like below.

A: On Mac OS X, you use the dwarfdump utility to dump the DWARF in .o files or in .dSYM bundles.
% dwarfdump fig7.o
----------------------------------------------------------------------
 File: fig7.o (x86_64)
----------------------------------------------------------------------
.debug_info contents:

0x00000000: Compile Unit: length = 0x00000077  version = 0x0002  abbr_offset = 0x00000000  addr_size = 0x08  (next CU at 0x0000007b)

0x0000000b: TAG_compile_unit [1] *
             AT_producer( "Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn)" )
             AT_language( DW_LANG_C99 )
             AT_name( "fig7.c" )
             AT_low_pc( 0x0000000000000000 )
             AT_stmt_list( 0x00000000 )
             AT_comp_dir( "/tmp" )

0x00000026:     TAG_base_type [2]
                 AT_name( "int" )
                 AT_encoding( DW_ATE_signed )
                 AT_byte_size( 0x04 )

0x0000002d:     TAG_variable [3]
                 AT_name( "a" )
                 AT_type( {0x00000026} ( int ) )
                 AT_external( 0x01 )
                 AT_decl_file( "/private/tmp/fig7.c" )
                 AT_decl_line( 1 )
                 AT_location( [0x0000000000000000] )

0x00000043:     TAG_subprogram [4] *
                 AT_name( "foo" )
                 AT_decl_file( "/private/tmp/fig7.c" )
                 AT_decl_line( 2 )
                 AT_external( 0x01 )
                 AT_low_pc( 0x0000000000000000 )
                 AT_high_pc( 0x0000000000000006 )
                 AT_frame_base( rbp )

0x0000005d:         TAG_variable [5]
                     AT_name( "b" )
                     AT_decl_file( "/private/tmp/fig7.c" )
                     AT_decl_line( 4 )
                     AT_type( {0x00000026} ( int ) )
                     AT_location( fbreg -4 )

0x0000006b:         TAG_variable [5]
                     AT_name( "c" )
                     AT_decl_file( "/private/tmp/fig7.c" )
                     AT_decl_line( 5 )
                     AT_type( {0x00000026} ( int ) )
                     AT_location( fbreg -8 )

0x00000079:         NULL

0x0000007a:     NULL


text:
Q: How can I convert a very large integer from one base/radix to another using FFT? Are there known algorithms which will take a big integer with n digits encoded in one base/radix and convert it to another arbitrary base? (Let's say from base 7 to base 19.) n can be really big, like more than 100 000 digits, so I am looking for something better than O(n2) run time.
I have seen some algorithms that can multiply two huge integers using the Fast Fourier Transform (FFT), with the theoretical complexity of O(n log n), where n is the number of digits, so I wonder if something similar exists for bases/radix conversion?

A: I'm not well versed on the topic myself, but here's a page that hints at how to do radix conversion a bit faster than the naive remainder-and-divide algorithm:

*

*GNU MP - Binary to Radix
The page hints that you need a fast divide-and-conquer division algorithm, which in turn needs a fast multiplication algorithm (Karatsuba, Toom-Cook, FFT, etc.).


text:
Q: wont proceed from init() in servlet to doGET() I am writing a web app (for school) that manages products. The design is as follows:
After I checked login with a servlet, I'm forwarded to another servlet called ManageMainPageServlet, in which the doGet a) posts the html which consists of two forms for searching a product, and b) inserts the product into the database.
After the first form is filled in (the search product form), it is passed to the post method in the same servlet, which in turn redirects it to SearchProduct servlet.
I defined the init() there to register all the variables for connecting to the database (which I already tested and works).
After the init (which I know is run only once at first time) I presume the code goes to the doGet method, to start managing the query. This does not work for me, and it goes back to the ManageMainPageServlet.
I tried with a dispatcher.forward, and what I wrote right now is what happens, if I try to change it to response.redirect, it wont even get to the init() function in SearchProduct.
What am i missing?
This is code for ManageMainPageServlet:
@WebServlet(name = "ManageMainPageServlet", urlPatterns = {"/ManageMainPageServlet"})
public class ManageMainPageServlet extends HttpServlet {
    /**
     * Handles the HTTP
     * GET method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession(false);
        if(session==null || (Boolean)session.getAttribute("logged") == false)
            response.sendRedirect("index.html");
        out.println("<!DOCTYPE html>"+
                        "\n"+
                        "<title>Welcome to Main Page</title>\n"+
                        "\n"+
                        "
 Welcome to Main Page
\n"+
                        "<form action=\"ManageMainPageServlet\" method=\"POST\">\n"+
                        " Enter product name and\\or product id to search:
\n"+
                        "Product Name: <input type=\"text\" name=\"productName\" />
\n"+
                        "Product ID:<input type=\"text\" name=\"productId\" />
\n"+
                        " <input type=\"hidden\" name=\"direction\" value=\"/SearchProduct\">\n"+
                        " <input type=\"submit\" />\n"+
                        "</form>\n"+
                        " <form action=\"ManageMainPageServlet\" method=\"POST\">\n"+
                        "Fill in the fields to enter new product into DB.\n"+
                        "
Product Name: <input type=\"text\" name=\"productName\" />\n"+
                        "
Product ID: <input type=\"text\" name=\"productId\" />\n"+
                        "
Price:  <input type=\"text\" name=\"price\" />\n"+
                        "
Quantity: <input type=\"text\" name=\"productId\" />\n"+
                        "
Product Description:
<textarea rows=\"4\" cols=\"50\"  name=\"description\"></textarea>\n"+
                        " <input type=\"hidden\"  name=\"direction\" value=\"\">\n"+
                        "
 <input type=\"submit\" />\n"+
                        "  </form>\n"+
                        " <form action=\"LogOutServlet\" method=\"GET\">\n"+
                        " <input type=\"submit\" value=\"logout\"/>\n"+
                        " </form>\n"+
                        "");
    }

    /**
     * Handles the HTTP
     * POST method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String direction = request.getParameter("direction");
        //response.sendRedirect(direction);
        RequestDispatcher rd = request.getRequestDispatcher(direction);
        rd.forward(request, response);
    }

This is code for SearchProduct servlet:
@WebServlet(name = "SearchProduct", urlPatterns = {"/SearchProduct"})
public class SearchProduct extends HttpServlet {
    private Connection con=null;
    private String url=null;
    private String user=null;
    private String password=null;
    private String odbcDriver=null;

    /**
     * initializes servlet with db connection and throws back error if the
     * connection failed for some reason
     */
   @Override
   public void init(ServletConfig servletConfig) throws ServletException {
       try {
           this.url = servletConfig.getInitParameter("dbUrl");
           this.user = servletConfig.getInitParameter("user");
           this.odbcDriver = servletConfig.getInitParameter("odbcDriver");

           Class.forName(odbcDriver);

        } catch (Exception e) {
            //decide how to handle the exception
            System.out.println("Failed to load the driver");
            return;
        }

   }

    /**
     * Handles the HTTP
     * GET method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String productName = request.getParameter("productName");
        String productID = request.getParameter("productID");

        try {
            try {
                // Create the connection to the database
                con = DriverManager.getConnection(url,user,password);
                System.out.println("Made a connection to the database");
            } catch (Exception e) {
                System.out.println("Exception was thrown:\n");
                e.printStackTrace();
            }
            // Get a statement object from the connection
            //
            Statement statement = con.createStatement();
            if(productID==null);

       } catch (Exception e) {
           System.out.println("Exception was thrown:\n");
           e.printStackTrace();
       } finally {
           try {
               if (con != null) { con.close(); }
           }catch (SQLException e) {
               e.printStackTrace();
           }
       }
    }
}


text:
Q: Although it works in css on other pages, it doesn't work on the category page (Django) I built a blog site. Although it works in css on other pages, it doesn't work on the category page. What can I do? I edited. thanks for your answers. It looks like your post is mostly code; please add some more details.
Here is my code:
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/')

blog/views.py

def category_detail(request, cats):
    category_posts=Blog.objects.filter(category_id=cats)
    context = {
        'cats': cats, 'category_posts': category_posts,
    }
    return render(request, 'post/category.html',context)

urls.py

from django.conf.urls.static import static
from django.urls import include, path

from blog.views import blog_detail, category_detail
from home.views import home_view, about_view
urlpatterns = [
    url(r'^adminerdo/', admin.site.urls),
    url(r'^$', home_view),
    url(r'^about/$', about_view),
    url(r'^(?P<slug>[\w-]+)/$', blog_detail , name= 'detay'),
    url(r'^category/(?P<cats>[\w-]+)/$', category_detail, name='category'),
]
urlpatterns += static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT)

category.html
{% include 'header2.html' %}

{{ blog.title }}

{{ blog.title }}

 {{ blog.user}}

                         {{ cats }}
{% for blog in category_posts %}
    {{ blog.category }}
    {{ blog.title }}
{% endfor %}

{% include 'footer.html' %}

header2.html --- detail.html is working with it.
<!DOCTYPE html>

    <title>tittle</title>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <meta name="description" content="Blog">
    <meta name="keywords" content="">
    <meta name="author" content="kamleshyadav">
    <meta name="MobileOptimized" content="320">

    <link rel="stylesheet" type="text/css" href="../static/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="../static/css/font-awesome.css">
    <link rel="stylesheet" type="text/css" href="../static/js/plugins/swiper/swiper.css">
    <link rel="stylesheet" type="text/css" href="../static/js/plugins/magnific/magnific-popup.css">
    <link rel="stylesheet" type="text/css" href="../static/css/style.css">

    <link rel="shortcut icon" type="image/png" href="../static/images/favicon.png">

I edited. thanks for your answers. It looks like your post is mostly code; please add some more details.

A: You have:
urlpatterns += static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT)

when your settings say:
STATIC_URL = '/static/'
STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/')

Try:
urlpatterns += static(settings.STATIC_URL,document_root = settings.STATIC_ROOT)

EDIT after OP update:
So, you've set up django's static handling system, but you're not using it.  Try:
{% load static %}

<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" type="text/css" />

etc.


text:
Q: Is it possible to assign/change custom icons for files in a batch / from commandline? Actually, I'm talking about icons for Nautilus Scripts, and I have many of them. Although I prefer menus without icons, I cannot prevent icons from being displayed in Nautilus context menu items Open With and Scripts.
Particularly, having the same script icon displayed for all of them does not look good at all.
So, if I cannot prevent them, at least I'd like them use icons better related with the function of each script.
It's easy to assign a custom icon for a single file through File Properties but I have a total of 82 Nautilus Scripts at the moment!
When you enter gvfs-info /path/to/file command in terminal, you can see a line like this: metadata::custom-icon: file:///usr/share/icons/NITRUX-Buttons/apps/scalable/accessories-text-editor.svg
I wonder if it is possible at all to edit this line (where ever it is) in a batch / from command line?

A: I couldn't see it in the list shown as I was writing this question, but later I saw a similar question and the answer I was looking for in the list of Related questions on the right:
How can I programmatically change a file's icon?
It seems basically the command for this is:
gvfs-set-attribute -t string /path/to/your/file metadata::custom-icon file:///path/to/your/icon.png
Notes:
1. This doesn't seem to work for Nautilus Scripts in Ubuntu versions before 12.10.
2. This doesn't seem to work for Nautilus Scripts when running Nautilus as root either.

A: Using the ideas exposed here, changing the icon from Nautilus or Nemo would take this:
#!/bin/bash
# Written by Alfonso R. Reyes
# make hard links for multiple file selection
# be careful of not moving the hard link to a different file system
HARDLINK_ICON=${HOME}/.local/share/icons/mine/folder-green-activities-icon.png
for arg
do
    # make a hard link of the selected file
    if [[ -f "$arg" ]]
    then
        HARDLINK_NAME="Hard Link to $arg"
        ln "$arg" "${HARDLINK_NAME}"
        gio set -t string "${HARDLINK_NAME}" metadata::custom-icon file:///${HARDLINK_ICON}
    fi
done


text:
Q: How our database should be for using it with Salesforce Connect? I have a on-premise data base(Oracle DB), this database i need to use in salesforce directly using External Object technology provided by salesforce. I understood how to use External objects in salesforce, but my question is what should be there from database side so that salesforce external objects can use the database, if i have a hostname,username,password and port number for the data base is that enough can salesforce connect to database using host name alone in the url section provided in external data source creation?, and what in type if i select ODATA adapter 2.0 then what else my database should be configured with, should it be exposed with odata like a .svc file? and what is this odata service can i write my own odata service and host it for free?

A: The native REST API for Oracle databases is ORDS which is not compatible with Salesforce. It's possible to develop your own OData REST endpoint using WCF Data Services; or use a commercial Oracle Odata service specific to Salesforce from Progress DataDirect that generates an endpoint using your database connection information.


text:
Q: distances in TikZ I do not know which numbers have to be set to have a good looking from this code.
\documentclass{article}
\usepackage{times}
\usepackage[latin1]{inputenc}
\usepackage{tikz}
\usetikzlibrary{shapes,arrows}
\begin{document}
\pagestyle{empty}

% Define block styles
\tikzstyle{decision} = [diamond, draw, fill=white!20,
text width=4.5em, text badly centered, node distance=3cm, inner sep=0pt]
    \tikzstyle{block} = [rectangle, draw, fill=white!20,
text width=5em, text centered, rounded corners, minimum height=4em]
    \tikzstyle{line} = [draw, -latex']
    \tikzstyle{cloud} = [draw, ellipse,fill=white!20, node distance=3cm,
minimum height=2em]

    \begin{tikzpicture}[node distance = 2cm, auto]
% Place nodes
    \node [block] (seg) {seg};
    \node [cloud, left of=seg] (ct1) {ct};
%\node [cloud, right of=init] (system) {system};
    \node [block, below of=seg] (smoo) {smoo};
    \node [block, below of=seg] (vol) {vol};
%\node [block, left of=evaluate, node distance=5cm] (update) {update model};
    \node [block, below of=vol] (drr) {drr};
    \node [block, below of=drr] (acqu) {acqu};
    \node [cloud, left of=acqu] (target1) {target};
    \node [block, below of=acqu] (comp) {comp};
    \node [block, below of=comp] (trans) {trans};
    \node [decision, below of=trans] (3d) {3d};
    \node [block, below of=3d, node distance=3cm] (cloud) {cloud};
    \node [block, below of=cloud] (estab) {estab};
    \node [block, below of=estab] (meas) {meas};
    \node [block, left of=meas] (meas2) {meas};
    \node [cloud, below of=meas] (ct2) {ct set};
    \node [cloud, below of=meas2] (target2) {target};
%\node [block, below of=decide, node distance=3cm] (stop) {stop};
% Draw edges
\path [line] (ct1) -- (seg);
\path [line] (seg) -- (smoo);
\path [line] (smoo) -- (vol);
\path [line] (vol) -- (drr);
\path [line] (drr) -- (acqu);
\path [line] (acqu) -- (comp);
\path [line] (comp) -- (trans);
\path [line] (trans) -- (3d);
\path [line] (cloud) -- (3d);
\path [line] (estab) -- (cloud);
\path [line] (meas) -- (estab);
\path [line] (ct2) -- (meas);
\path [line] (target2) -- (meas2);
\path [line] (meas2) |- (cloud);
\path [line] (target2) -- (meas2);
\path [line] (target1) -- (acqu);

\end{tikzpicture}

\end{document}

A: This is one possible solution where the proposal breaks one long top-down flowchart, that exceeds the page length, into 4 segments, spreading horizontally.
The main trick is to change below of = xx into right = xx cm of yy at the point one wants to break and then use, for example, draw[line] (acqu.east) -- ++(1cm,0) |- (comp.west); which says drawing from acqu.east 1cm to the right then vertically up and turns horizontally to the comp.west.

Code
\documentclass{article}
\usepackage[margin=1in]{geometry}
\usepackage{times}
\usepackage[latin1]{inputenc}
\usepackage{tikz}
\usetikzlibrary{shapes,arrows,positioning}
\begin{document}
\pagestyle{empty}

% Define block styles
\tikzstyle{decision} = [diamond, draw, fill=white!20,
text width=4.5em, text badly centered, node distance=2cm, inner sep=0pt]
    \tikzstyle{block} = [rectangle, draw, fill=white!20,
text width=5em, text centered, rounded corners, minimum height=4em]
    \tikzstyle{line} = [draw, -latex']
    \tikzstyle{cloud} = [draw, ellipse,fill=white!20, node distance=2cm,
minimum height=2em]

    \begin{tikzpicture}[node distance = 2cm, auto]
% Place nodes
    \node [block] (seg) {seg};
    \node [cloud, left of=seg] (ct1) {ct};
%\node [cloud, right of=init] (system) {system};
    \node [block, below of=seg] (smoo) {smoo};
    \node [block, below of=smoo] (vol) {vol};
%\node [block, left of=evaluate, node distance=5cm] (update) {update model};
    \node [block, below of=vol] (drr) {drr};
    \node [block, below of=drr] (acqu) {acqu};
    \node [cloud, left of=acqu] (target1) {target};
    \node [block, right =2cm of seg] (comp) {comp};
    \node [block, below of=comp] (trans) {trans};
    \node [decision, below of=trans] (3d) {3d};
    \node [block, right = 2cm of comp] (cloud) {cloud};
    \node [block, below of=cloud] (estab) {estab};
    \node [block, below of=estab] (meas) {meas};
    \node [block, right = 1cm of meas] (meas2) {meas};
    \node [cloud, below of=meas] (ct2) {ct set};
    \node [cloud, below of=meas2] (target2) {target};
%\node [block, below of=decide, node distance=3cm] (stop) {stop};
% Draw edges
\path [line] (ct1) -- (seg);
\path [line] (seg) -- (smoo);
\path [line] (smoo) -- (vol);
\path [line] (vol) -- (drr);
\path [line] (drr) -- (acqu);
\path [line] (acqu.east) -- ++(1cm,0) |- (comp.west);
\path [line] (comp) -- (trans);
\path [line] (trans) -- (3d);
\path [line] (cloud.west) -- ++ (-1cm,0) |- (3d.east);
\path [line] (estab) -- (cloud);
\path [line] (meas) -- (estab);
\path [line] (ct2) -- (meas);
\path [line] (target2) -- (meas2);
\path [line] (meas2) |- (cloud);
\path [line] (target2) -- (meas2);
\path [line] (target1) -- (acqu);
\end{tikzpicture}
\end{document}


text:
Q: How to "reset" a listview and show again the @android:id/empty when repopulating All my listviews in my application are using the empty property to show a progressdialog while loading some web content:
    <RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent"
        android:id="@android:id/empty" android:gravity="center">
                <ProgressBar android:id="@+id/progressBar1" android:layout_width="wrap_content" android:layout_height="wrap_content"></ProgressBar>
    </RelativeLayout>
    <ListView android:id="@android:id/list"
        android:layout_width="fill_parent" android:layout_height="wrap_content" />

This is great and work fine the first time, but unfortunately, if I want to reload the listview, I expect the progressdialog to show again!
but, I can use:
getListView().setAdapter(null);

or
getListView().setAdapter(new TweetItemAdapter(getActivity(),R.layout.row_tweet,new ArrayList<Tweet>()));

I xon't get any dialog, just an empty view.
So basically my question is "how to show the empty layout again during the second loading of the listview?
EDIT: With comment below, I tried :
    @Override
    public void onResume() {
        super.onResume();
        TweetItemAdapter test = (TweetItemAdapter) getListView().getAdapter();
        if(test != null){
            test.clear();
            test.notifyDataSetChanged();
        }
        loadTweets(this, getListView());
    }

Still doesn't show the progressdialog, I get an empty view while loading. (EXCEPT for first loading that works perfectly)

A: Approach: Add in you XML the view that you want to show up when the ListView is empty. Then when populating the ListView check for the length of the data supplier you use in you adapter inside the getView() method (if it is null or its length is 0) if it is null/0-length then instantiate that view and change its visibility to View.VISIBLE. Or use getListView().setEmptyView(findViewById(R.id.myemptyview));
Remark: I think there is no need to clear you adapter test.clear() since (I assume somewhere in loadTweets() you have adapter and call notifyDataSetChanged() again) the listview will repopulate with the new data.
Question: Do you reinstantiate the progress dialog whenever you call notifyDataSetChanged() because my logic says that: progress dialog must be shown whenever you do fetching, i.e repopulating the listview with data? (I might be wrong)


text:
Q: Is there a way to Render into a different array index of a depth map in direct 3d 11 Recently, I was implementing cascaded shadow mapping with direct 3d 11, I used an array texture to store the different shadow maps for each light source. I also configured the depth map to be an array texture, but I can't seem to find out how to store depth in the other textures in the array.
I tried using a Geometry Shader and setting the SV_RenderTargetArrayIndex to 1 or 2, but I guess that only works for render target views and not depth stencil views.
I am just wondering if it's possible to do this without having to create 3 depth-Stencil Views for each texture in the array.
Edit: my mistake was not calling restartstrip after setting the positions.

A: From the documentation for System Value semantics in D3D11, in the SV_RenderTargetArrayIndex table row:

This value also indicates which array slice of a depth/stencil view is used for read/write purposes.

So the SV_RenderTargetArrayIndex semantic is the correct one to use for rendering to the different indices in the depth/stencil array.


text:
Q: Sql procedure is giving error when I pass input parameter I have created following procedure but it is giving me error
PROCEDURE profileMigration20 compiled
Warning: execution completed with warning
1/30           PLS-00103: Encountered the symbol "@" when expecting one of the following:

   <an identifier> <a double-quoted delimited-identifier>
   current delete exists prior

create or replace Procedure profileMigration20(@firstname varchar(40))
is
   Begin

    INSERT INTO DPS_USER(ID
    ,LOGIN
    ,AUTO_LOGIN
    ,PASSWORD
    ,MEMBER
    ,FIRST_NAME
    ,MIDDLE_NAME
    ,LAST_NAME
    ,USER_TYPE
    ,LOCALE
    ,LASTACTIVITY_DATE
    ,REGISTRATION_DATE)

    select ID
    ,LOGIN
    ,AUTO_LOGIN
    ,PASSWORD
    ,MEMBER
    ,FIRST_NAME
    ,MIDDLE_NAME
    ,LAST_NAME
    ,USER_TYPE
    ,LOCALE
    ,LASTACTIVITY_DATE
    ,REGISTRATION_DATE
   FROM NM_DPS_USER where FIRST_NAME=@firstname;
  End;

A: If memory serves me right...
It looks like you're using the wrong syntax (it looks like the T-SQL syntax used with MS SQL).
To use parameters in pl/sql the syntax should be:
CREATE [OR REPLACE] PROCEDURE procedure_name (
  param_name1 IN datatype, param_name12 IN datatype ... )

In your case:
create or replace Procedure profileMigration20(firstname IN varchar2(40))

and to use it just call it without the @ sign like:
FROM NM_DPS_USER where FIRST_NAME=firstname;


text:
Q: return json in column-wise format How to return json in column-wise format
Suppose the User table has 3 columns (Name, age, location),
User Table
Jack, 18, Taiwan
Mary, 27, Japan

Expected JSON response format (by columnar)
{
 name:["Jack", "Mary"],
 age: [18, 27],
 location: ["Taiwan", "Japan"]
}

How to finish it on Rails ?

A: You could do the following:
data = {
  name: User.pluck(:name),
  age: User.pluck(:age),
  location: User.pluck(:location)
}

render json: data

but be advised, this will query the database 3 times!
EDIT: If you want to do it all in 1 Query, do the following:
data = {
  name: [],
  age: [],
  location: []
}

User.pluck(:name, :age, :location).each do |u|
  data[:name] << u[0]
  data[:age] << u[1]
  data[:location] << u[2]
end

render json: data


text:
Q: VS2015 MVC No compile experience It was my understanding that with the new compiler it is possible to run code without restarting an ASP.NET MVC project, e.g. the no-compile experience.
For example changing the model or controller requires restarting the entire project, which can take quite some time in VS2013 (especially with Code First).
Is this, basically edit&continue for ASP.NET, now possible in VS2015? I tried CTP5 but could not get this working.
Edit: The actual question
Does VS2015, or will it, support edit and continue or a similar experience (not having to restart for model/controller changes) for ASP.NET MVC?

A:
Does VS2015, or will it, support edit and continue or a similar experience (not having to restart for model/controller changes) for ASP.NET MVC?

Visual Studio Edit and Continue is available and works for ASP.Net all the way back to version 2010 with constraints (IIS Express etc...).

Is this, basically edit&continue for ASP.NET

No.  Scott Hanselman did a very detailed explanation of all the new features in vNext in this blog post Introducing ASP.NET vNext.
Excerpt:

One of the great aspects of environments like node or rails is that they are "no compile." Just change some code and hit refresh. With the next version of ASP.NET you get the power and throughput of the .NET runtime plus the "Roslyn" compiler-as-a-service for a "no-compile compile." That means means during development time you can just change your C# classes and hit Refresh in the browser. It's the power of .NET with the dynamism of a refresh-and-go development experience.

and

NOTE: This isn't ASP.NET Websites, or Razor View compilation - this is the whole thing, compiled in memory. You can use Visual Studio for development, or text editors like Sublime, or freakin' Notepad. (Of course, if you want assemblies on disk, you can do that too.)

and

See my web app's bin folder in the screenshot below? There's no assemblies in there because the assemblies never exist on the disk. It's actually faster and easier to have the compiler do all the work in memory.


text:
Q: Is there a function $u$ with $g(u)$ regular whose "truncation" $g(T(u))$ is not regular? I hope the title is not to misleading.
Assume you have a continuous function $g:R\to R$ and a Lebesgue measurable function $u:\Omega\to R$ for some bounded domain $\Omega$ such that $g(u)\in H^1(\Omega)$.
Let now $T_k$ be the truncation function at level $k$, i.e.
$$ T_k(u) =\begin{cases}k & u>k \\ u& u\leq k \end{cases} $$
The question that comes up is the following one.
Does from $g(u) \in H^1(\Omega)$ also follow $g(T_k(u)) \in H^1(\Omega)$.
This is easy for $g$ being an increasing function, since then $g(T_k(u)) = T_{g(k)}g(u)$ and $T_k$ is piecewiese smooth.
Maybe this is a standard example. In that case I don't know it :) I haven't yet succeeded  in proving a negative result on the question. Any ideas?

A: This is not true. Take $\Omega = (0,1)$, $u = \chi_{(0,1/2)}$ and $g(t) = t \, (1-t)$.
Then, $g(u) \equiv 0$, but $g(T_{1/2}(u))$ is discontinuous, hence not in $H^1(\Omega)$.


text:
Q: Asp.net Web API : No action was found on the controller I am using Visual Studi0 2010. In my WebApiConfig.cs file I have below config, I can map these two urls /Values and /Values/1. It is working fine.
config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new {id= RouteParameter.Optional  }
        );

Since I wanted to my custom URL like /Values/Machines and /Values/Machines/100, I changed above setting to below.
config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new {action="get", id= RouteParameter.Optional  }
        );

It is now mapping below urls except this one, /Values/1. Please let me know what I am missing.
1./Values
2./Values/Machines
3./Values/Machines/100

Thanks.

A: It is expected behavior. According to your new Route the first parameter Values is expected to be a Controller name, and second parameter 1 is expected to be an Action, but you don't have an action with the name 1
In order to get to the Action you need the url with you new route should be like so: /Values/Index/1
You could do something like this:
routes.MapRoute(
    name: "IndexWithParam",
    url: "{controller}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    constraints: new { id = @"\d+" }
);

routes.MapRoute(
    name: "Default", // Route name
    url: "{controller}/{action}/{id}", // URL with parameters
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

In this case if the Url is like this: /Values/1, it will hit first route and redirect it to /Values/Index/1. Note that I've placed a constraint on this route that makes sure that second parameter is a number.


text:
Q: Magento 2.2.4 Show error message returned by plugin I'm beginner to Magento2 and I want to validate pincode which exists in custom table or not on Checkout page (www.test.com/checkout/), according to that I want to display error message on same page. Following is sample code of my plugin:
public function beforeSaveAddressInformation(
    \Magento\Checkout\Model\ShippingInformationManagement $subject,
    $cartId,
    \Magento\Checkout\Api\Data\ShippingInformationInterface $addressInformation
) {
    $shippingAddress = $addressInformation->getShippingAddress();
    $pincode = $shippingAddress->getPostcode();

    $enable = $this->helper->getIsEnable();
    $checkAddToCart = $this->helper->getIsCheckonAddtoCart();

    if ($enable && $checkAddToCart && $pincode) {
        $pincodeStatus = $this->helper->getPincodeStatus($pincode);

        if(!$pincodeStatus) {
            // Following error message want to show on checkout page
            throw new InputException(__($this->helper->getFailMessage()));
            exit;
        }
    }
}

Can anyone let me know is there any way to display standard error message thrown through plugin using Magento2 Standards. Or else I have to use custom jquery validation rule on Checkout page? if I have to use custom jquery validation rule, then let me know how can I apply jquery validation rule on Checkout page, please elaborate in brief.
Thanks in advance!

A: After so much investigation and implementation, I found a solution to display custom error message on checkout page.
1) Override a shipping.js file (vendor\magento\module-checkout\view\frontend\web\js\view\shipping.js) into your custom theme (app\design\frontend\Vendor\Theme\Module_Checkout\web\js\view\shipping.js):
2) Add your ajax call into setShippingInformation() function as follows:
    /**
     * Set shipping information handler
     */
    setShippingInformation: function () {
        var shippingAdd = quote.shippingAddress();
        var thisObj = this;
        $.ajax({
            url: '/pincodechecker/ajax/checkpincode',
            type: 'POST',
            data: 'pincode=' + shippingAdd.postcode,
            complete: function(response) {
                var res = JSON.parse(JSON.stringify(response));
                var responseText = JSON.parse(res.responseText);

                if (responseText.error === true) {
                    // Display error message exactly after pincode textbox
                    $(".message.warning").addClass("error").removeClass("warning");
                    $(".message.error").html(responseText.message);
                    return false;
                }
                else {
                    // Call validate shipping function only when your pincode is valid
                    if (thisObj.validateShippingInformation()) {
                        setShippingInformationAction().done(
                            function () {
                                stepNavigator.next();
                            }
                        );
                    }
                }
            }
        });
    },

3) Check pincode valid or not using ajax call (Namepsace/PincodeChecker/Controller/Ajax/CheckPincode) as follows:
public function execute() {
    $response = ['error' => false, 'message' => ''];
    ....
    // Add your pincode validation logic
    ....

    if (!$valid) {
        $response = ['error' => true, 'message' => 'Pincode is invalid!'];
    }
    echo json_encode($response); // return response to ajax call in js file
}

4) Delete var folder, delete files and folder from pub/static/frontend/
5) Run php bin/magento setup:static-content:deploy -f in terminal.
I hope this solution may help to anyone. :)


text:
Q: Average data points within a range of each other? I have a Pandas data frame with the following columns:
lat1    lon1    lat2    lon2

lat and lon variables are latitude and longitude in degrees. Many of the points are very, very close to each other. I want to divide this dataframe up in 'clusters, for example, group all data points that are within 60 feet of each other together. I know I can use geopy.distance.vincenty to get the distance between the points. But I'm not sure how I would go about cycling through the dataframe to cluster points based on distance from each other.

A: The problem is that your task is not well defined.
Consider points a, b, c. Let the distances be: a to b: 40, b to c: 40, a to c 80.
Now if you want to average points within 60, then you would need to average b with both a and c, but not a and c!
You need to be more precise here. Maybe single-link clustering, but maybe you want complete link, or average link, or ward, or DBSCAN, or ...


text:
Q: "unable to open '/usr/share/icons/Pop/16x16@2x/actions/bookmark-new.png.dpkg-new': No such file or directory" error while trying to update Ign:1 http://dl.google.com/linux/chrome/deb stable InRelease
Hit:2 http://ppa.launchpad.net/daniruiz/flat-remix/ubuntu focal InRelease
Hit:3 http://archive.ubuntu.com/ubuntu focal InRelease
Get:4 http://archive.ubuntu.com/ubuntu focal-updates InRelease [106 kB]
Hit:5 http://dl.google.com/linux/chrome/deb stable Release
Hit:7 http://archive.ubuntu.com/ubuntu focal-backports InRelease
Get:8 http://archive.ubuntu.com/ubuntu focal-security InRelease [107 kB]
Fetched 213 kB in 4s (48.5 kB/s)
Reading package lists... Done
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
The following packages will be upgraded:
  pop-icon-theme
1 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Need to get 0 B/7,360 kB of archives.
After this operation, 46.0 MB disk space will be freed.
Do you want to continue? [Y/n] Y
(Reading database ... 326295 files and directories currently installed.)
Preparing to unpack .../pop-icon-theme_2.1.0~1583343731~20.04~11f18cb~ubuntu1_all.deb ...
Unpacking pop-icon-theme (2.1.0~1583343731~20.04~11f18cb~ubuntu1) over
(1.4.0~1565992228~18.04~2bac292) ...
dpkg: error processing archive /var/cache/apt/archives/pop-icon-
theme_2.1.0~1583343731~20.04~11f18cb~ubuntu1_all.deb (--unpack):
 unable to open '/usr/share/icons/Pop/16x16@2x/actions/bookmark-new.png.dpkg-new': No such file or directory
No apport report written because the error message indicates an issue on the local system
         Errors were encountered while processing:
 /var/cache/apt/archives/pop-icon-theme_2.1.0~1583343731~20.04~11f18cb~ubuntu1_all.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

Output of apt-cache policy pop-icon-theme:
pop-icon-theme:
  Installed: 1.4.0~1565992228~18.04~2bac292
  Candidate: 2.1.0~1583343731~20.04~11f18cb~ubuntu1
  Version table:
     2.1.0~1583343731~20.04~11f18cb~ubuntu1 500
        500 http://archive.ubuntu.com/ubuntu focal/universe amd64 Packages
        500 http://archive.ubuntu.com/ubuntu focal/universe i386 Packages
 *** 1.4.0~1565992228~18.04~2bac292 100
        100 /var/lib/dpkg/status

A: I had the same issue. I removed the package and reinstalled using
sudo apt-get remove --purge pop-icon-theme
sudo apt install --reinstall pop-icon-theme


text:
Q: Why are _initializing and isTopLevelCall variables used in Initializable contract of Openzeppelin? This is abstract contract in the context of Proxy pattern:
abstract contract Initializable {
    bool private _initialized;
    bool private _initializing;

    modifier initializer() {
        require(_initializing || !_initialized, "Initializable: contract is already initialized");

        bool isTopLevelCall = !_initializing;
        if (isTopLevelCall) {
            _initializing = true;
            _initialized = true;
        }

        _;

        if (isTopLevelCall) {
            _initializing = false;
        }
    }
}

contract UpgradebleTest1 is Initializable {
    uint public x;

    function initialize(uint _x) public initializer {
        x = _x;
    }
}

I don't understand the necessity of _initializing and isTopLevelCall. Is not enough doing control using only _initialized?
Thanks,

A: The _initializing and isTopLevelCall combination allow for chained calls with the initializer modifier:
contract UpgradebleTest1 is Initializable {
    uint public x;

    function initialize(uint _x) public initializer {
        internalInit(_x);
    }

    function internalInit(uint _x) internal initializer {
        x = _x;
    }
}

Without the _initializing and isTopLevelCall check, the initializer modifier would pass on the first call (initialize()) but fail on the second call (internalInit()).
modifier initializer() {
    require(!_initialized, "Initializable: contract is already initialized");
    _initialized = true;
}

A: abstract contract Initializable {
        bool private _initialized;

        modifier initializer() {
            require(!_initialized, "Initializable: co...");
            _;
            _initialized = true;
        }
    }

contract UpgradebleTestParent is Initializable {
    uint public x;

    function initialize(uint _x) internal initializer {
        x = _x;
    }
}

contract UpgradebleTestMain is UpgradebleTestParent {
    function init(uint _x) public initializer {
        initialize(_x);
    }
}

If it is as above, it would execute same logic, but _initialized = true; would be executed twice unnecessarily, right? However, it seems like cheaper than the previous one which has a one more variable and related additional instructions? Isn't it?


text:
Q: Error in jquery response error I have the following piece of code
var sContactId = jQuery("[id$=contactId]").attr("value");

jQuery("#responseErrors").html("Check"+sContactId);

Now, it is not printing the value of sContactId. I am not sure where am I going wrong.

A: try this
jQuery("#responseErrors").html("Check"+jQuery("[id$=contactId]").val());

It will work for you.


text:
Q: How to set inherit default group and permission setting to a CustomUser? I have created a CustomUser to add new fields to the existing User class. I just want to default to User setting for group and permission controls for my CustomUser so I can use the default UserAdmin view.
How do I inherit the default group and permission (what do I have to add to my CustomUser class?)?

A: You can use post_signal signal to configure the default user permissions. Use the name attribute of Permission object to get them.
Here is an example :
@receiver(post_save, sender=CustomUser)
def define_default_user_permissions(sender, instance, **kwargs):
    # retrieve needed permissions
    # E.g : permission to add a token
    permission = Permission.objects.get(name='Can add token')
    # add this permission to the user
    instance.user_permissions.add(permission)

Add this  method at the end of your <app_name>.models. Read more about signals
If you want to display all permissions, open your python shell with python manage.py shell and do this :
# import Permission object
from django.contrib.auth.models import Permission
# display all permissions
Permission.objects.all()

Read more about Models Meta - permissions  to know how to create permissions for your models
You can do the same thing to define default groups to a new user with Group object.


text:
Q: IIS server gives 406 error on trying to download .img file We have an embedded product that download its firmware upgrade via HTTP using a program called nvtools. This works from a linux server using Apache. But we switched to a Windows server using IIS. Now we are getting a:
"406 - Client browser does not accept the MIME type of the requested page."
when trying to download the firmware update using nvtools. I can't change anything on the embedded system side to make this work. Our IT guy has not been able to fix this yet. What setting in IIS does he need to change to fix this issue?
Dennis

A: Add .img to the MIME types list as application/octet-stream

A: Most of the time when people have problems with MIME types, is because IIS is not configured to serve a file with a certain MIME type, the http status code for that is 404.3, Your 406 means the client has sends an http accept header which is not understood by the server.
A typical accept header would be:
Accept: text/html,application/xhtml+xml,application/xml

nvtools sends an accept header with a MIME type that the server does not know about, this explains why using a browser for the same request works fine. The browsers send a valid Accept header.
The accept header tells the server, that for this request the client accepts data in one or multiple MIME types.
You should sniff the network traffic to find out what Accept header is used by nvtools, adding the MIME type used to the MIME type mapping in IIS does not help because those are for serving MIME types, not for Accept ones.
You have two options:

*

*Fix whatever the MIME type in the Accept header of nvtools is.

*This solution is an assumption of mine, I have not tested it. Add that MIME type used by nvtools to Windows (not IIS) this is done by adding multiple entries under HKEY_CLASSES_ROOT in the registry, but right now I don't remember the details. There is no way to configure Accept MIME types in IIS so I assume adding it to Windows will be picked up by IIS as well.


text:
Q: Stock trading probability and return problem Statistics data has been collected to test a stock trading strategy; every time the strategy buys a stock, after certain conditions being met, it will sell it; and then the data table records its profit/loss with its respective proability % of occurence. First column is probability % of the event(adding up to 100%), the middle column is return, and the thrid column is expected return (probability% x return)
How to read the table examples:
6.32% 0.75: it means for 6.32% chance, the stock could make 0.75$/share
8.27% 0.55: it means for 8.27% chance, the stock could make 0.55$/share
11.18% -0.95: it means for 11.18% chance, the stock could make -0.95$/share
Now the question asks, given the data, assuming you have 1000 shares of a stock, what's the most optimized way to sell your positions.
My initial thought, it's basically a question of expected return, and choosing the highest expected return should be the way to go, thus, just simply looking at the table, 0.047 is the highest value, and it corresponds to 6.32% chance and 0.75 share profit; it means, just sell all my 1000 shares of stock whenever it makes 0.75; sure, after I sell it, it could go higher and make 2 or even 100 but the chance for those returns are very low, in a long run, if I am going to repeat above transactions many times, the most optimized way should just simply sell it wheneven it hit 0.75$/share profit.
But there is another side of the problem, it could also lose mony or leave money on the table, so if I set it at 0.75, the chance for the profit to be bigger than 0.75 is less than 27% (adding up all % bigger than 0.75), a lot of time it will never reach that 0.75 goal; however, if I set it at 0.4, the chance the profit to be bigger than 0.4 is 48.6%, but it also means, a lot of time, I left money on the table (After I sell at 0.4 profit target, it keeps going up higher); is maybe a better way to do this is break down 1000 shares into pieces
x shares @ 0.4 + y shares @ 0.5 + z shares @ 0.6 +.....=total sum
x+y+z+...=1000
maxmize total sum
but then, how to decide the weight of x y z?
I am really confused, is there actually an optimized answer for the problem?
Thanks!


text:
Q: How to setup Internet access on existing in house network? I currently the following set-up. 5 computers are hardwired thru an ethernet switch to share a "company specific software program", one of these computers connects to an additional computer by a wireless router to share QuickBooks Accounting file access. There are 2 additional computers connected thru the router, one hard-wired and one wireless for internet service access and individual use.
I would like to properly setup this system to provide internet access across the system. Can I just hardwire the router to the Ethernet switch by an Ethernet cable. the current network shows an ipv4 default gateway of 192.168.0.1 and so does the router.

A: Your "default gateway" setting is related to routing, and so probably really has no effect whatsoever as long as all of your devices are on the same subnet.  But when you get the Internet, then the "default gateway" setting will start to matter, because devices won't be able to communicate with the Internet until they get this setting right.
Can I just hardwire the router to the Ethernet switch by an Ethernet cable.
Sure, that ought to work.  Note that I'm not giving any advice related to security: things may have been separate for a reason, and you might be violating the original design/intent by connecting things up.  So, I'm not saying that it's a good idea; it might be dangerous.  Or, instead of just a security risk, you might introduce a switching loop that brings down the whole network (until you remove the loop).  Or, doing this might be just fine.  I totally don't have enough information about your network to know the full implications.  But, in general, wireless access points can communicate via Ethernet, and that may help you to connect.
There certainly may be possible variations/customizations.  A typical setup may look like this: You'll want a modem (DSL modem or cable modem) that gets Internet access from your ISP.  Then plug your WAP (wireless access point, which you are calling a router) or switch to the cable modem.
With a very common setup, the wireless access point will want to have a default gateway that points to the IP address provided by the DSL/cable modem.  Both the wireless access point and the modem can act like a "router", so the preferred "default gateway" address that other devices use will probably be the wireless access point or the modem.  Which one you need to use depends on how you wire things up (like if the modem is plugged into the "Internet" or "WAN" port of a wireless access point that is acting like a router, or if the modem is plugged into another port that makes the wireless access point act like a switch...  or maybe you connect the modem straight to the switch.)  If you use the wrong "default gateway" setting on a device, then it won't cause any major harm; you just won't have working Internet for that device.  So just try both addresses.