text:
Q: jQuery "this" changing in chain I have a div that has a div  inside it that will delete the outer div when clicked.  The jQuery to make this happen is
275 $(document).on('click','.rightMenuDelete', function(event) {
276   $(this).parents('.cell').
277   fadeOut(300, function()  {
278     $(this).remove();});
279  });

At 276 the this keyword is the inner div we clicked.  By 277 the wrapped set has the outer div we want to delete.  But I want to fade out the outer div before I remove it, so 277 applies the fadeOut and then the callback removes the outer div.  What surprises me a bit is that 278 works.  The this keyword at 278 is  the outer div, as we want , and no longer the inner div that we clicked originally.  Can anyone throw some light on how the this keyword can change as control moves down a jQuery chain?
Thanks

A: The element pointed to by this changes on line 276 itself, when parents('.cell') is executed. It no longer points to the inner div, but to the list of parents with the class cell.
After which you execute the fadeOut which loops over the collection of parents. Inside the loop, this refers to the current parent being looped over.

A: Just keep a reference to your old this, because here you're calling .fadeOut on .parents('.cell')

A: this in Javascript is scoped based on the function that it is in.  Create a variable that you pass into the callback and call .remove on it.
$(document).on('click','.rightMenuDelete', function(event) {
    var par = $(this).parents('.cell');
    par.fadeout(300, function() {$(par).remove();});
  });

Should work.

A: To preserve the original this you can save it in a variable:
$(document).on('click','.rightMenuDelete', function(event) {
   var that = this;
   $(this).parents('.cell').
       fadeOut(300, function()  {
           $(that).remove();});
});

The above technique is required because this changes context inside the fadeOut as noted by the other responses.

A: Thanks to everyone.  You guys are great, and quick. Assigning the parent to a variable and then using that variable in the fadeOut/remove line is clearly better coding, and I will do that. My main question, though, was what was happening in the jQuery to get the value of the this keyword to change from one function to the next inside the jQuery chain.  In pure JavaScript the this keyword inside of a function is the global object, like window or document, and clearly something more is happening here.
I understand now, though, that the this passed to the callback function is current member of the wrapped set passed to it, and the wrapped set at this point is the parent, not the original clickee. Thanks again.


text:
Q: Transformation of general equation of straight line to normal form Consider the general form of equation of straight line.
$$ax + by + c = 0$$
$$\Rightarrow ax + by = -c$$
$$\Rightarrow \frac{ax}{-c} + \frac{by}{-c} = 1$$
$$\Rightarrow \frac{x}{\frac {-c}{a}} + \frac{y}{\frac {-c}{b}} =1 $$
this is equation of line in intercept form with x-intercept  $\frac {-c}{a}$ and y-intercept $ \frac {-c}{b}$

In above fig. $\overline {OD}\bot\overline {AB}$
Now consider $\Delta$OAD
$$Cos\alpha =\frac {\overline{OD}}{\overline{OA}} = \frac{P}{\frac {-c}{a}} =\frac {-aP}{c} $$
In $\Delta$OBD
$$Cos(90-\alpha)=\frac {\overline{OD}}{\overline{OB}} = \frac{P}{\frac {-c}{b}} =\frac {-bP}{c} $$
Since Cos($90-\alpha$)= Sin $\alpha$ Therefore,
$$Sin\alpha = \frac {-bP}{c}$$
Now
$$tan\alpha =\frac {sin \alpha}{cos\alpha} = (\frac {-bP}{c})(\frac{-c}{aP})$$
$$tan \alpha = \frac {b}{c}=> \frac {perpendicular}{base}$$
$$\Rightarrow hyp = \pm\sqrt{a^2+b^2} (by Pythagorean theorem).........(a)$$
$$\Rightarrow cos\alpha = \frac {a}{\pm\sqrt {a^2+b^2}},sin\alpha = \frac {b}{\pm\sqrt {a^2+b^2}}...............(1)$$
Now for transforming general equation of straight line to normal form:
Consider the general form of equation of straight line
$$ax+by+c=0$$
$$\Rightarrow ax+by=-c$$
Now in order to to have Normal form of equation of straight line it is said that divide both sides by $\pm\sqrt{a^2+b^2}$, then we get
$$\frac {a}{\pm\sqrt{a^2+b^2}}x+\frac {b}{\pm\sqrt{a^2+b^2}}y=\frac {-c}{\pm\sqrt{a^2+b^2}}$$
Using equations (1) in above we get
$$xcos\alpha+ysin\alpha=\frac {-c}{\pm\sqrt{a^2+b^2}}$$
Now comparing with normal equation of straight line i.e.$xcos\alpha+ysin\alpha=P$
$$\implies P=\frac {-c}{\pm\sqrt{a^2+b^2}}$$
Now the question is:
1: In equation (a) $hyp = \pm\sqrt{a^2+b^2}$ but according to figure in $\Delta OAD hyp=\overline{OA}= \frac{-c}{a}$
How $\pm\sqrt{a^2+b^2}=\frac{-c}{a}$?

A: The general equation $ax+by+c=0$ of a straight line in $\mathbb R^2$ can be rewrtten as $\mathbf n\cdot\mathbf x=-c$, with $\mathbf n\ne0$. This form of the equation tells us that a line can be characterized as the set of points that have the same dot product with some fixed vector $\mathbf n$. If we normalize $\mathbf n$ by dividing both sides of the equation by its length, we have $${\mathbf n\over\|\mathbf n\|}\cdot\mathbf x=-{c\over\|\mathbf n\|}.$$ This is the so-called normal form of the equation for the line, characterized by $\mathbf n$ being a unit vector. The left-hand side of this equation is the (signed) length of the orthogonal projection of $\mathbf x$ onto $\mathbf n$, so an equivalent way to charactere the line is as the set of vectors $\mathbf x$ that have the same projection $\mathbf x_\parallel$ onto $\mathbf n$. The remainder $\mathbf x-\mathbf x_\parallel$ is perpendicular to $\mathbf n$, from which we can see that $\mathbf n$ is perpendicular to the line, and so the (perpendicular) distance of the line from the origin is ${|c|\over\|\mathbf n\|}$. Substituting the coefficients from the original equation yields the normal equation $${a\over\sqrt{a^2+b^2}}x+{b\over\sqrt{a^2+b^2}}y={-c\over\sqrt{a^2+b^2}}.$$ Since we have a unit normal, we can replace the coefficients on the left-hand side: $$x\cos\alpha+y\sin\alpha={-c\over\sqrt{a^2+b^2}},$$ where $\alpha$ is the angle made by the normal vector with the $x$-axis.
Now, as far as your equation (a) is concerned, remember that in computing $\tan\alpha$, you canceled a constant of proportionality that appeared in both the numerator and denominator, so the most that you can conclude from it is that the length of the hypotenuse of $\triangle{OAD}$ is proportional to $\sqrt{a^2+b^2}$. Indeed, in your diagram you have two other triangles that are similar to $\triangle{OAD}$: $\triangle{BOD}$ and $\triangle{BOA}$, so we have $$\tan\alpha = {\overline{AD}\over\overline{OD}} = {\overline{OD}\over\overline{BD}}={\overline{OA}\over\overline{OB}}.$$ The legs of the largest of these are the hypotenuses of the smaller ones, so there are at least two different lengths of hypotenuse in play. Moreover, it might be that none of the lengths is equal to $\sqrt{a^2+b^2}$!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Entity Framework: Poor Database Design and Multiple Keys I am developing a new version of our software in C# using entity framework. I am new to this technology, but the new version is coming along swimmingly. Our major holdback has been with how to design entities that match our existing (poorly designed) database schema. Designing a new database schema is outside of the scope of this project, although we can make small changes where necessary.
I am currently trying to get around a particular problem that has arisen. Here are some models to demonstrate the problem:
public class EntityA
{
    [Key]
    public int SurrogateKey { get; set; }
    public int NaturalKey1 { get; set; }
    public int NaturalKey2 { get; set; }

    public virtual ICollection<EntityB> B { get; set; }
    public virtual ICollection<EntityC> C { get; set; }
}

public class EntityB
{
    [Key]
    public int EntityBID{ get; set; }

    [ForeignKey("EntityA "), Column(Order = 0)]
    public int EntityANaturalKey1 { get; set; }
    [ForeignKey("EntityA "), Column(Order = 1)]
    public int EntityANaturalKey2 { get; set; }

    public virtual EntityA A { get; set; }
}

public class EntityC
{
    [Key]
    public int EntityCID{ get; set; }

    [ForeignKey("EntityA ")]
    public int EntityASurrogateKey  { get; set; }

    public virtual EntityA A { get; set; }
}

So in our database, we have like 20 entities that follow EntityB, where they reference the natural key of EntityA, and a similar number of entities like EntityC, where they reference the surrogate key.
From what I can tell, entity framework will not allow you to define multiple keys for the same entity. When I try and deal with these models in my application, I get errors regarding Multiplicity and the number of dependent and principal roles not being identical.
Are there are any workarounds to deal with this via Entity framework, or am I going to have to adjust my database such that all entities will use the surrogate key?


text:
Q: Cannot get project to build with new framework I'm working on an old project which has had a new framework added since my older copy. I've added the project by dragging it to the Framework folder but when I build I get an error saying it is missing one of the headers.

The WGFramework is listed along with the header files, including WGLog.h which is supposed to be missing

It is also listed in the Link Binary With Libraries in Build Phases. What do I need to do to get my project to recognise this framework that is clearly listed?

A: How about checking the framework search path?

Project -> Build Settings -> "Frameworks Search Path" field

Make sure it points to where the headers are located (or at least a parent directory with the recursive option).
In the command line:

find . -type f -iname "*WGLog.h"


text:
Q: How to get d3 to recognize push+shift as an add-new-object-to-end and remove-old-object-from-beginning, rather than as just a data change in place I am trying to use d3.js to animate a faceted wheel of incrementing numbers, where 3 facets are shown at a time, and each time a "tick" occurs, the top facet disappears, the middle facet goes up one, and a new bottom facet is added. I want the motion to appear smoothly, but it doesn't.
I can't seem to figure out how to use transitions here, and it looks like d3 just sees my array of size 3 with changing values. When really it should see the add and remove each time, but I don't know how to do that.
How can I fix this?

<!DOCTYPE html>

A: I guess the issue is that as long as the position is dependent on the index, and the indices don't change (0,1,2 for example) then there is no transition in position, just a change of text based on the data.
I found another way (circular buffer essentially) which works:

<!DOCTYPE html>

A: Oh, I should have used key functions to ensure reasonable object constancy. See https://bost.ocks.org/mike/constancy/
Here is an implementation that works along the lines I was originally thinking of:

<!DOCTYPE html>


text:
Q: Dataview filters with too many special characters How can I filter data table with string that contains too many special characters? I tried various way with escape sequence but none worked.
Below is my code:
DataView dt = Dt_Resut.DefaultView;
dt.RowFilter = query.ToString();
DataTable Dt_Result = dt.ToTable();

Where the value of query.ToString() is Special `~@#$%^&*()_+-=[]|:;'/.,<>?  message.
NOTE: 'query' is string builder. It will create string based on search criteria.


text:
Q: Python operations on an SQLite table: calculations all *slightly* wrong I have a script that goes through a large (~50,000x45) table. The issue is, that I get very weird results. The calculations aren't completely wrong, but slightly off. This is true in two ways:

*

*I run dates through a function that converts the calendar. For the same date, I get multiple different outputs. 1401/11/22 should be 2022/01/11 and I get this value when I manually run the function, but in the sql, the correct value is only inserted 9/10. I randomly seem to get a few 2022/01/12 and 2022/01/13, and 2022/01/14 in the data.

*Calculated Cell D = Cell A/Cell B. The result should be 3.33712..., but the result that gets inserted in my table is 3.34238...
Below I'll provide the code I'm running:
import sqlite3
import jdatetime

from jdatetime import datetime as jalali_datetime

def J2G(jalali_date):
    # jdatetime only supports string inputs for dates
    jalali_date = str(jalali_date)
    jalali_date = jalali_datetime.strptime(jalali_date, "%Y/%m/%d")
    gregorian_date = jalali_date.togregorian()
    gregorian_date = gregorian_date.strftime("%Y/%m/%d")
    return gregorian_date

def update_row(row):
    # 1) Effective_QTY
    try:
        Effective_QTY = max(row[11], row[13])
    except ValueError:
        Effective_QTY = None

    # 2) Contract_Date_Gre
    try:
        Contract_Date_Gre = J2G(row[15])
    except ValueError:
        Contract_Date_Gre = None

    # 3) Delivery_Date_Gre
    try:
        Delivery_Date_Gre = J2G(row[16])
    except ValueError:
        Delivery_Date_Gre = None

    # 4) Mean_Price_USD
    try:
        Mean_Price_USD = float(row[5]) / float(row[32])
    except ValueError:
        Mean_Price_USD = None

    # 5) Total_Value_USD
    try:
        Total_Value_USD = (float(row[6]) * 1000) / float(row[32])
    except ValueError:
        Total_Value_USD = None

    # 6) Final_USD
    try:
        Final_USD = float(row[7]) / float(row[32])
    except ValueError:
        Final_USD = None

    # 7) Lowest_USD
    try:
        Lowest_USD = float(row[8]) / float(row[32])
    except ValueError:
        Lowest_USD = None

    # 8) Highest_USD
    try:
        Highest_USD = float(row[9]) / float(row[32])
    except ValueError:
        Highest_USD = None

    # 9) Base_Price_USD
    try:
        Base_Price_USD = float(row[10]) / float(row[32])
    except ValueError:
        Base_Price_USD = None

    #return Effective_QTY, Contract_Date_Gre, Delivery_Date_Gre, Mean_Price_USD, Total_Value_USD, Final_USD, Lowest_USD, Highest_USD, Base_Price_USD

    return (Effective_QTY, Contract_Date_Gre, Delivery_Date_Gre, Mean_Price_USD,
            Total_Value_USD, Final_USD, Lowest_USD, Highest_USD, Base_Price_USD)

# Connect to the database
conn = sqlite3.connect('IME.db')
cursor = conn.cursor()

# Fetch all rows with Processing = 'post_dependencies'
cursor.execute("SELECT * FROM mainpage WHERE Processing = 'post_dependencies'")
rows = cursor.fetchall()

# Update each row
for row in rows:
    values = update_row(row) + (row[26],)
    cursor.execute("""UPDATE mainpage
                      SET Effective_QTY = ?, Contract_Date_Gre = ?, Delivery_Date_Gre = ?,
                          Mean_Price_USD = ?, Total_Value_USD = ?, Final_USD = ?,
                          Lowest_USD = ?, Highest_USD = ?, Base_Price_USD = ?,
                          Processing = 'pre_PtB_calcs'
                      WHERE offer_code = ?""",
                   values)

# Commit the changes
conn.commit()

# Close the connection
conn.close()

I ran the code on two different computers and I get the exact same weird, slightly wrong results. The slightly wrong arithmetic could be because of the datatypes I guess but the dates randomly being off have really thrown me off. Have absolutely zero idea what's going on.


text:
Q: How to save Offline Server Data in Application How to save the data on the server like in the khta book application and after reinstalling the application, how to save that data offline in the application

A: If you keep the data on the server always in sync with the data in the application, then after you reinstall the application and you log into your account you can just retrieve the data normally and have all your previous data.

A: If you want to include an initial Firestore data set with the application, so that the user can use this right after they install the app (even if they're offline), have a look at the documentation about data bundles.
Data bundles allow you to create a bundle of Firestore documents/queries, that you can then include in the APK, and load the bundle to Firestore's cache when the app is first started.
Also see the solutions guide on serving data bundles.


text:
Q: Elasticsearch Mapping lost on sails lift with mongo-connector I am developing an applications using MongoDB, Sails JS and ElasticSearch.
MongoDB is used to write records that are retrieve for the application. ElasticSearch is used for search text and geo locations distance search etc.
I am using mongo-connector to keep my data in sync from MongoDB to ElasticSearch.
Issue is, i am not able to maintain my mappings for geo_point for the fields that store lat and lon or parent/child or analyzer etc. Every time sails server is lifted i see in elasticsearch logs that all the mappings are removed, created and updated, and i lose my mapping for geo_point that is have created manually via the REST after every thing is up and running or even if i have created mapping at bootstrap time of sails js(as a work around).
I have also tried to create a mapping file and placed it in elasticsearch/config/mappings/index/mymapping.json but i get an error
Caused by: org.elasticsearch.index.mapper.MapperParsingException: Root type mapping not empty after parsing! Remaining fields: ...

Here i tried all the combinations to make this work but no success eg
{"mappings" : {
        "locations" : {
            "dynamic": "false",
            "properties":{
                "location": {
                    "type": "geo_point"
                }
            }
        }
    }
}

Also tried using a template to create the mapping but after that mongo-connector kick in and overrides the mapping.
As of now i am only able to make this work is to stop mongo-connector, delete the oplog.timestamp file, start the sails server(Here at bootstrap time i delete and recreate the mapping for that document) and then start mongo-connector. But this create accidents if we forgots to do a step.
Am i doing any thing wrong or is there a better way to sync the mongodb to elasticsearch without losing the custom mapping or an alternative mongo-connector.

A: According to the documentation, if you install a mapping on the filesystem, the file must be named <your_mapping>.json so in your case it should be named locations.json and be placed either in
elasticsearch/config/mappings/_default/locations.json

or
elasticsearch/config/mappings/<your_index_name>/locations.json

Moreover, you mapping file shouldn't contain the mappings keyword, it should instead look like this:
    {
        "locations" : {
            "dynamic": "false",
            "properties":{
                "location": {
                    "type": "geo_point"
                }
            }
        }
    }

You should try again after correctly naming your mapping file and folders.


text:
Q: React Native bottom navbar full width I'm trying to make a bottom navbar in React Native but it isn't spanning the full width, only the width of its content. I have tried using vw as in How to use vw and vh css with React Native but it gives the error: "width":<> is not usable as native method argument.
AppBar:
import { View, Pressable, Text } from "react-native"

const AppBar = ({ style, addNote }) => {
  return (
    <View style={style}>
      <Pressable
        onPress={() => addNote({ id: "9", title: "Hii", body: "new note" })}
      >
        <Text style={{ textAlign: "center", fontSize: 30 }}>Add</Text>
      </Pressable>
    </View>
  )
}

export default AppBar

style:
appbar: {
    position: "absolute",
    bottom: 0,
    display: "flex",
    justifyContent: "center",

    flexGrow: 1,
    flexShrink: 1,
    marginRight: "auto",
  },

How can I get the AppBar to span the full width?


text:
Q: iMovie question (possibly need a different apple product? IDK) Okay, this question is a bit of a doozy.
I decided to try my hand at making a rotoscoping animation. That's basically an animation created using real film as a base.
The original video is 16500 frames long, 24 frames per second. I'm only animating half of those frames.
I used "FireAlpaca" to draw each and every one of the still images that would be used in this video.
Do i use imovie to make this video? Obviously since there's less frames, it's going to by quicker, correct ? How do I make it so that there are only 12 frames per second instead of 24, and therefore be able to make my video at the same length as the original film I'm using as the basis for this animation?
Essentially it's just an extremely fast slideshow. Can I do this in imovie? Final Cut Pro? What do I do????

A: See How can I combine 30,000 images into a timelapse movie?
ffmpeg
In answers to this question the community suggest using the open source tools Avidemux or ffmpeg. For example the ffmpeg approach is:

This will create a video slideshow (using video codec libx264) from series of png images, named named img001.png, img002.png, img003.png, …
Each image will have a duration of 5 seconds, change the variable according to your choice.
ffmpeg -f image2 -r 1/5 -i img%03d.png -c:v libx264 -pix_fmt yuv420p out.mp4

If your images have four digits, use %04d, etc. If your images do not have this pattern, you can use shell globs, at least on Linux and OS X:
ffmpeg -f image2 -pattern_type glob -i 'time-lapse-files/*.JPG' …

You can also change the output framerate by specifying another -r after the input.

Also see:

*

*ffmpeg: create a video from images

*http://electron.mit.edu/~gsteele/ffmpeg/ for a researchers use of ffmpeg to combine individual images into a movie.

Homebrew
You can use Homebrew to get ffmpeg onto your Mac:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then install ffmpeg with:
brew install ffmpeg


text:
Q: better approach to define java constants for numeral values In java, we can define constants to avoid magic numbers e.g. list size , days.
My question is regarding reusing of the constant defined for numerals in code.
Approach 1:
I can define two constant which both have value 30 .
public static final int ONE_MONTH=30
public static final int LIST_SIZE_THIRTY=30

Approach 2:
I can define one constant with value 30.
public static final int THIRTY=30

Both are correct from java syntax perspective. Although approach 1 is giving more info but have to define two constants. Approach 2 is just a number written in english and can be used both places where we were suppose to use ONE_MONTH and LIST_SIZE_THIRTY.
Which approach is recommended and why ?

A: What do you want is the question.
You want readibility and reusability? Take the first one.
You want memory optimization? Take the second solution.
Why? Imagine tomorrow there will be 35 days in a month for any reason. with the second, you'll have to rework all your app, with the first, you'll juste have to change 30 to 35.
EDIT : To be clear, first solution is from far the best, no doubt about it, unless you're in a very very (very very very...) memory restrictive development...

A: If you define a constant such as
public static final int LIST_SIZE_THIRTY=30

it's quite the same as using 30 because if the default size becomes 20 it's not recommended to end with something like
public static final int LIST_SIZE_THIRTY=20

or creating a new constant and replacing the old one.
Your constants shoud be meaningful, i.e they must help who reads and maintains the code (even if he/she is the code author).
so my suggestion is something like:
public static final int ONE_MONTH=30;
public static final int DEFAULT_LIST_SIZE=30;

because they have different meanings, i.e. different semantic. If in you first version the requirements states that default list size is one_month you could stress it with
public static final int ONE_MONTH=30;
public static final int DEFAULT_LIST_SIZE=ONE_MONTH;

P.S. I did not consider that defining two constants uses more memory because this is a design question and one or two (or even more) variables usually do not make such a difference in terms of used memory in a Java program.

A: There is one alternative, change your second Approach like below--
Maintain one Constants class--
public class Constants{

public static final int NUMBER_THIRTY=30;
....
...  //rest of the class

}
And then, use Enums like below--
imprort ...Constants;
 public enum EnumConstants {

        MONTH(Constants.NUMBER_THIRTY),
             LIST_SIZE_THIRTY(Constants.NUMBER_THIRTY);

        int value;

    private EnumConstants(int value) {
        this.value = value;
    }

    public int value() {
        return value;

    }

}

So by this way, you can achive  code reusability, code readability, and maitainability. ( in future, if value of month changes, as stated in one answer, then you only need to change value in Constants class.)


text:
Q: From text file read and if there is a sentences define on the list text=open('tt.txt','r')
txt=text.read()
text.close()
print (txt)

text1=open('tt.txt','w')
lis=['elephants are the biggest animal.', 'sunset is the
     time of day when our siy meets the outer space solar
      winds.']
For i in range(len(lis)):
         If text.__contains__(lis[i]):
                text2=text.replace(lis[i],txts)
                text1.write(text2)
text1.close()
Print(text2)

From text file read and if there is a sentences define by on  list then replace it with <b> the list item that found  </b>; for example if I have elephants are the biggest animal. in a text file it will replaced by <b>elephants are the biggest animal.</b>.

A: f = open("tt.txt","r")
text = f.read()

lis=['elephants are the biggest animal.', 'sunset is the
     time of day when our siy meets the outer space solar
      winds.']

for i in lis:
    if i in text:
        text.replace(i, "<b>" + i + "<\b>")

f = open("out.txt","w")
f.write(text)

This should do the trick


text:
Q: How do I keep my collection in sorted order when sent as ArrayCollection and received as java.util.Set on the server? I've developed a web application using Flex 4.5, Java, BlazeDS and Spring.
I just discovered that when I fetch a collection (java.util.Set) from the server as an ArrayCollection, sort the ArrayCollection in the Flex web application and send it back to the server, this collection is received by the server as unsorted java.util.Set.
Any suggestion on how I can keep the collection sorted when sent to the server?

A: You'll need to use an object on the AS side and a Map on the Java side. In AS, put all the elements from your arraycollection in one object like this
            var list:ArrayCollection = new ArrayCollection();
            var obj:Object = new Object();
            list.addItem("test");
            list.addItem("test2");
            for(var i=0;i<list.length;i++){
                obj[i] = list.getItemAt(i);
            }

After that , send the obj to the Java side - an AS object will be serialized to a Java Map. On the server side you will have the positions as the keys from your map, so you will be able to rebuild the order (the Java code is trivial, so I'm not going to write it down here).

A: You can use a SortedSet.
-> http://download.oracle.com/javase/6/docs/api/java/util/SortedSet.html

A: Why does it need to be sorted in-transit?  I would just sort it when the server receives it.


text: Q: Como reproducir una lista de reproduccion de spotify con tarjeta nfc? tengo tarjetas NFC y mi idea es configurarla para que al pasar el celular por ella reproduzca automaticamente una lista de reproducción de spotify, la tengo configurada para que abra la lista, pero no he podido lograr que ponga play. Gracias!


text: Q: Azure error descriptions back to Access I've received the error "connection is busy with results for another command" - when adding a record via an Access DB connected to a SQL Azure DB.  Searching this error didn't turn up anything relevant, but I figured out that this was caused by a key violation on the table.  It would appear that a useable error message is not being passed back from Azure to Access.  Can anyone suggest how to handle this situation (other than querying the table in advance) - i.e., get an appropriate error description from Azure?


text:
Q: Question about lim inf or lim sup When taking the course of real analysis, the professor wrote the following:
Let $f_n \geq 0$ for all $n$.
Let $$a = \lim \inf \int_X f_n d\mu + \epsilon$$
I think here $\epsilon$ is any positive number.
Now, by the definition of $\lim \inf$, we have
$$\forall N, \exists\, n >N, \text{ such that } \int_X f_nd\mu <a$$

My question is, if $\{f_n\}$ is decreasing, i.e., $$f_1\geq f_2 \geq f_3 \cdots \geq f_n \geq \cdots,$$ then how could the conclusion hold? (if choosing $\epsilon \rightarrow 0$)


text:
Q: Check if the file is already in source control I am working with TFS programmatically using classes from Microsoft.TeamFoundation.VersionControl.Client namespace. My goal is to check-in files from the local folder into source control. Some files may already exist in SC and should be Edited, some are new and should be added, some exist in SC and haven't changed, so I don't need to do anything with them.
My problem is that I can't figure out how to check whether a file already exists in source control, so I can't decide in my code whether I should Add or Edit it. None of the Workspace methods seem to do what I need.
The code I have:
foreach (string file in fileList)
{
    workspace.PendEdit(file);
    workspace.PendAdd(file);
}

It does the job, but it looks dumb and feels slow. What is the correct way to do it?

A: I don't know about 'correct', but in one of my tools I make use of VersionControlServer.ServerItemExists in order to get what you 're after.In your case you would have to check with something like this:
versionControlServer.ServerItemExists(workspace.GetServerItemForLocalItem("filePath"), ItemType.Any)


text:
Q: Problems on Calculating Stochastic Integral Let f be a deterministic function in $L^2[a,b]$ and $X_t=X_a+\int^t_af(s)dB(s)$.
Show that $\int^b_af(t)X_tdB(t)=\frac{1}{2}(X_b^2-X_a^2-\int^b_af(t)^2dt)$.
My attempt:
$\frac{1}{2}(X_b^2-X_a^2)=X_a\int^b_af(t)dB(t)+\frac{1}{2}(\int^b_af(t)dB(t))^2$.
On the other hand:
$\int^b_af(t)X_tdB(t)=\int^b_af(t)X_adB(t)+\int^b_af(t)(\int^t_af(s)dB(s))dB(t)$.
So it remains to show that:
$\int^b_af(t)(\int^t_af(s)dB(s))dB(t)=\frac{1}{2}(\int^b_af(t)dB(t))^2-\frac{1}{2}\int^b_af(t)^2dt$
I learn only about the basic definition of stochastic integral. Is there any suggestions or hints? Also, I am wondering why f should be deterministic. What will go wrong if f is adapted and being in $L^2$? Thank you.

A: I am not sure whether you know Ito's formula, which is a useful tool to prove such identity.
Let $dX_t=f(t)dB_t$ and apply Ito's formula to $X_t^2$ gives you
$$dX_t^2=2X_tdX_t+(dX_t)^2=2X_tf(t)dB_t+f^2(t)dt,$$
then integrate $dX_t^2$ from $a$ gives you the desired result.

For an elementary proof, you may refer to my comment for this post. As you can see from the above argument, if $f$ is adapted and satisfies suitable integrablity assumptions, a similar identity also holds. But for an elementary proof, if $f$ is a deterministic function, we can start first with $f$ be a indicator function of $[s,t]$, for which the identity can be established with a direct calculation. But if $f$ is $L^2(\Omega\times [a,b])$, there is no such simple function for us to start with.


text:
Q: Anaconda python ver5.3 hangs at update forever I just installed anaconda ver5.3 which uses python v3.7
I ran the command;
conda update anaconda

The command hangs there forever. There is no error message. No hint what is wrong. Has anyone encountered similar problems? How did you solve it?
I am using Windows 10 and was previously using anaconda ver5.2 which uses python v3.6.

A: Try running
conda update anaconda --verbose

to get some insight. Adding --verbose multiple times increases logging to INFO, DEBUG and then TRACE level.
https://conda.io/docs/commands/conda-update.html

A: I think this could solve your problem to update anaconda, and yes it seems like a fairly common issue:
1) install the latest miniconda3 from here
2) make sure you run anaconda prompt as admin
3) update to latest version of conda
conda update conda
4) install anaconda
conda install anaconda
5) install navigator
conda install anaconda-navigator
6) verify conda is installed and check package number
conda info
View packages you installed in anaconda docs page here

A: I encountered exactly the same problem on Windows 10.
This problem has been fixed with the latest anaconda release ver5.3.1. You are using ver5.3. Please use the latest version. It should solve your problem.


text:
Q: Why is it so difficult to fix buffer overflows?
Possible Duplicate:
Why is it so difficult to make C less prone to buffer overflows?

I'm doing a course in college, where one of the labs is to perform buffer overflow exploits on code they give us. This ranges from simple exploits like changing the return address for a function on a stack to return to a different function, all the way up to code that changes a programs register/memory state but then returns to the function that you called, meaning that the function you called is completely oblivious to the exploit.
I did some research into this, and these kinds of exploits are used pretty much everywhere even now, in things like running homebrew on the Wii, and the untethered jailbreak for iOS 4.3.1
My question is why is this problem so difficult to fix? It's obvious this is one major exploit used to hack hundreds of things, but seems like it would be pretty easy to fix by simply truncating any input past the allowed length, and simply sanitizing all input that you take.


text:
Q: RC circuit with current and voltage source I am once again stuck on a task. The circuit initially looks like this:

And the question is:

So my attempt:
The first thing that came up in my mind was that the switch had been closed for a long time. That made me think that initially the capacitor behaves like an open circuit. So I redrawed the circuit like this:

Where Vc = Vab
So I thought that I could find Req and find Vab through the voltage divider.
However there are two things that makes it difficult form the to continue:

*

*The question states that when t = 1 μs then the switch opens, but the plot of Vc(t) should be from 0

*I don't know how I should consider the current source. Most problems that I solved have either had a current source or a voltage source. How should I look on the circuit when I have a current and voltage source?
Thanks in advance!
Edit:
Here is my new circuit after some help, however on the final state I am uncertain if the switch should be open and the capacitor not acting like an open circuit? :

A: I'm assuming that the current direction of the current source is as shown below: -

I don't know how I should consider the current source. Most problems
  that I solved have either had a current source or a voltage source.
  How should I look on the circuit when I have a current and voltage
  source?

My preference is to make the voltage source \$V_A\$ into a current source but first...
Your redraw is correct but there's one more thing you can do. R1 (in series with the current source) has no effect on the circuit because it is purely in series with a current source. It's the same for resistors in parallel with a voltage source - they do not affect the voltage source and can be turned into open circuits. In R1's case it becomes a short circuit.
Then, turn \$V_A\$ into a current source of 6 mA in parallel with R3. Do you see what I did here? The effective series combo of 6 volts and 1000 ohms become a current source of 6 mA in parallel with 1000 ohms.
So now you have R2 || R3 being fed by a current source of 2 mA (from the left) and a current source of 6 mA from the right. Total current is 8 mA into R2 || R3 (500 ohm) or, put another way, 4 mA flows into R2.
That sets the initial charged capacitor voltage.
Can you take it from here?


text:
Q: How to make sure docker-compose will not remove my volume with postgres data I am running a simple django webapp with docker-compose. I define both a web service and a db service in a docker-compose.yml file:
version: "3.8"

services:
  db:
    image: postgres
    volumes:
      - postgres_data:/var/lib/postgresql/data
    environment:
      - POSTGRES_DB=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    ports:
      - "8000:8000"
    env_file:
      - ./.env.dev
    depends_on:
      - db

volumes:
  postgres_data:

I start the service by running:
docker-compose up -d

I can load some data in there with a custom django command that I wrote for my app. Everything is running fine (with data) on localhost:8000.
However, when I run
docker-compose down

(so without -v) and then again
docker-compose up -d

the database is empty again. The volume was not persisted. From what I read in the docker-compose docs  and also in several posts here at SO, persisting the volume and reusing it when you start a new container should be the default behavior (which, if I understand it correctly, you can disable by using the --renew-anon-volumes flag).
However in my case, the volume is not persisted. Or maybe it is, but my data is gone.
By doing docker volume ls I can see that my volume (I'll use the name my_volume here) still exists after the docker-compose down command. However, the CreatedAt value has been changed. This makes me think it's a different volume with the same name, and my data is already gone, but I don't know how to confirm that.
This SO answer suggests to mount the volume on /var/lib/postgresql instead of /var/lib/postgresql/data. However, I've seen other resources (like this one) where the opposite is suggested. I've tried both, but neither option works.
Thanks for any advice.

A: It turns out that the Dockerfile of my app was using an entrypoint in which the following command was executed: python manage.py flush which clears all data in the database. As this gets executed every time the app container starts, it clears all data. It had nothing to do with docker-compose.


text:
Q: Should I connect battery ground to the metal enclosure I'm aware in the automotive world the chassis of the vehicle is used as the return path to the battery negative however I am building an electric-powered cart running on 48V lithium batteries.
The batteries come pre-built within a plastic enclosure with an Anderson connector.
The batteries will be fitted on the cart which consists of a metal frame sheet metal body.
I do not intend for the frame to carry current.
My reasons for not are:
By not connecting the frame to the negative, a short circuit would require both pos and neg to come into contact with the frame.
A user should not receive a shock should they come into contact with a fault arising in an energized frame/body/accessory/cable as there is no path back to negative.
Is there a benefit in this application to connecting the frame to the battery negative?

A: At 48 V, shock hazard is minimal.
Your batteries can probably deliver an embarrassingly large current in the event of a short circuit. Having the battery and the rest of the drive electronics isolated from the chassis means that you would need two faults to chassis rather than one to get a short.
You may find that an isolated chassis can enhance some frequencies of EMI coming from the electronics. If you are building a hobby one-off, you'll probably get away with this. If you're designing carts for a production run, then get this aspect checked out with a test house before you burn too much development money.


text:
Q: List Cognito Users in AWS I am trying to list all cognito users from my Cognito AWS service, I am trying to get the users pool id and I am taking it from here (please mind following image attached):

as I am using the following code (and taking the Pool Id from the image above):
public class AwsClient {
    private AWSCognitoIdentityProvider identityProvider;
    private final static String AWS_USER_POOL_ID = "<USER_POOL_ID>";

    public AwsClient(String regionName){
        AWSStaticCredentialsProvider provider = new AWSStaticCredentialsProvider(new BasicAWSCredentials(System.getenv("AWS_ACCESS_KEY_ID"),
                System.getenv("AWS_SECRET_ACCESS_KEY")));

        this.identityProvider = AWSCognitoIdentityProviderClientBuilder.standard().withCredentials(provider)
                .withRegion(Regions.US_EAST_1).build();
        ListUsersRequest req = new ListUsersRequest();
        req = req.withUserPoolId(AWS_USER_POOL_ID);
        ListUsersResult response = identityProvider.listUsers(req);

    }

I am getting the following error message:
User pool us-east-1_qvWp8iA5f does not exist.

What could be the problem?


text:
Q: DataGridView - Seperately change width for different columns after binding a datasource I have a basic datagrid that uses a datasource and want to set the width for specific columns while other columns still use autosize.
The dataGridView code:
$script:dataGridView1 = New-Object System.Windows.Forms.DataGridView;
$script:dataGridView1.Name = 'dataGridView1';
$script:dataGridView1.Size = '1235, 450';
$script:dataGridView1.RowTemplate.DefaultCellStyle.ForeColor = '#000088';
$script:dataGridView1.ReadOnly = $True;
$script:dataGridView1.AllowUserToDeleteRows = $False;
$script:dataGridView1.RowHeadersVisible = $False;
$script:dataGridView1.TabIndex = 3;
$script:dataGridView1.AutoSizeColumnsMode = 16;
$script:dataGridView1.AllowUserToAddRows = $False;
$script:dataGridView1.ColumnHeadersHeightSizeMode = 2;
$script:dataGridView1.Location = '13, 87';
$script:dataGridView1.AllowUserToOrderColumns = $True;
$script:dataGridView1.DataSource = $script:AWtable1;
$script:dataGridView1.Anchor = (4, 8, 1);
$script:dataGridView1.DataBindings.DefaultDataSourceUpdateMode = 0;

Full script: https://controlc.com/5359a6e5
Using this I get an exception saying "The property "AutoSizeMode/Width" cannot be found on this object."
What do I have to change to make this work? C# code works too.

A: From error message I guess that you don't have precreated columns on dataGridView1.
You may turn dataGridView1.AutoGenerateColumns to false and create, style your columns on your own while binding them to specific DataSource column through columns property DataPropertyName.
Example: https://stackoverflow.com/a/4907567/11409835
If you want dataGridView1.AutoGenerateColumns to remain true, you may change columns' settings after dataGridView1 had it's columns auto-created and rendered. For example you may change columns properties in Form.Load event.
dataGridView1.AutoGenerateColumns is not visible in VS editor, so if you want to set it to false, you have to do it through code. dataGridView1.AutoGenerateColumns is active only when you are using DataSource property.


text:
Q: HTML loading res/drawable images I have this html page (assets/page.html), and I want to load the image "res/drawable-xhdpi/image.png". There is a way?

A: Found a solution!
I made a copy of the image.png from the res folder to the assets folder (now assets/image.png).
Then I just srced the image src="image.png"


text:
Q: Not Enough Disk Space to Save File Mounted Image Ubuntu I have mounted an android system.img in my Ubuntu virtual machine using the command line code sudo mount -t ext4 -o loop system.img sys/ The mounting process goes just fine, I can open up the fiels to read them, but the second that I try to edit a subfile and save it it says "Not enough disk space to save the file".
On the virtual machine itself I have plenty of space, but the file folder that this image is mounted out of has zero space remaining. Does anybody know a way to be able to edit and save these files? I already tried exporting them to a different folder but nothing has worked thus far.
Thanks everyone!

A: You can use resize2fs to resize the volume.  I've done this in order to work around a bug in the Android tools that let you specify the size of the data partition (which didn't work at the time, so I had to resize the partition myself).  I also just tested this against a system.img that came from an Android system image from the SDK.


text:
Q: Spring Cloud Dependencies Issue I am getting this error message spammed when running my build in our CI servers:
[Fatal Error] spring-cloud-dependencies-Hoxton.RC2.pom:7:3: The element type "hr" must be terminated by the matching end-tag "
".
[Fatal Error] spring-cloud-dependencies-Hoxton.RC2.pom:7:3: The element type "hr" must be terminated by the matching end-tag "
".
[Fatal Error] spring-cloud-dependencies-parent-2.2.0.RC2.pom:7:3: The element type "hr" must be terminated by the matching end-tag "
".

Has anyone had this problem before? Doesn't happen locally.


text:
Q: codigniter: how to pass array from controller to view with jquery already my controller index method load with a parameter where two dropdown field, when I select the first one then I get data for the second one with jquery ajax and then when I select second one then I need to pass another array from a list_ByBatch method.
My controller is:
public function index() {
    $data['round'] = $this -> AttendanceModel -> get_round();

    $this->load->view('common/header');
    $this->load->view('common/menu');
    $this->load->view('attendance/attendance', $data);
    $this->load->view('common/footer');
}

public function list_ByBatch(){
    $batch=$this->input->post('batchid',TRUE);
    $list['trainee']=$this->AttendanceModel->get_traineeList($batch);
    if(!empty($list['trainee'])){
        return $list['trainee'];
    }
}

Script:
   <script type="text/javascript">
    $(document).ready(function() {
        $("#round").change(function(){
            /*dropdown post */
            $.ajax({
            url:"<?php echo base_url(); ?>index.php/attendance/batch_ByRound",
            data: {round: $(this).val()},
            type: "POST",
            success: function(data){
                $("#batch-list").html(data);
            }
            });
        });

        $("#batch-list").change(function(){
            /*dropdown post */
            $.ajax({
            url:"<?php echo base_url(); ?>index.php/attendance/list_ByBatch",
            data: {batchid: $(this).val()},
            type: "POST",
            success: function(data){
                $("#traineeList").html(data);
                $("#subTotal").html("Total: " + $('#traineeList tr').length.toString());
                document.getElementById("classHour").defaultValue = "4";
            }
            });
         });

    });

</script>

how do I pass the array in 'list_ByBatch' to view page which is already loaded when #batch-list change function execute.

A: Instead of returning, you should be using echo and json_encode:
public function list_ByBatch(){
    $batch=$this->input->post('batchid',TRUE);
    $list['trainee']=$this->AttendanceModel->get_traineeList($batch);
    if(!empty($list['trainee'])){
        echo json_encode($list['trainee']);
    }
}


text:
Q: How can I display CP437 charsets? Does anyone knows how I can display CP437 charsets? For example the chars ▒ and ░ ?
I tried to just say in the html meta tag:
<meta http-equiv="Content-Type" content="text/html;" charset=CP437">

But there I didn't saw any of the characters above.

A: There are two separate issues. One is about using the CP437 character encoding for an HTML document. Character encodings are often called "charsets" even in official protocols. The answer is that in principle you can use CP437, but in practice it hardly ever pays off.
A correct tag to declare CP437 is
<meta http-equiv="Content-Type" content="text/html; charset=IBM437">

or, simpler,
<meta charset=IBM437>

In the first syntax, note the use of quotation marks. The preferred MIME name for CP437 is IBM437, according to the IANA registry. This is just a matter of principle; in practice, the name CP437 works just as well, or as poorly.
(Note: Any such meta tag can be overridden by an HTTP header or by a UTF-8 BOM at the start of the actual data. There is nothing you can do in HTML to such things.)
On the practical side, tested in modern browsers on Win 7, only IE supports CP437. Both Firefox and Chrome fall back to their default encoding, in my case windows-1252. This means that the bytes will be interpreted in a completely different way.
The other issue is whether you can the characters that can be represented in CP437. The answer is emphatically yes: all those characters are Unicode characters, and you can use them like any other characters, either as such in a widely supported encoding, in practice UTF-8, or using character references, which work independently of character encoding. Example:

▒ and ░ (the characters as such)

▒ and ░ (using hexadecimal references)

▒ and ░ (using decimal references)

There is readable but non-authoritative information about CP437 to Unicode mapping in the Wikipedia page on CP437. I'm afraid I can't give a really authoritative reference, but the IANA registry refers to RFC 1345, even though it is informational only.


text:
Q: attempt to call method 'removeSelf' (a nil value) For some reason I can't remove a group object, even though I check if it's nil or not
First thing I tried:
if playGroup~=nil then
   playGroup:removeSelf()
end

ERROR: Attempt to remove an object that's already been removed from
  the stage or whose parent/ancestor group has already been removed.

I also tried this:
for k,v in pairs(playGroup) do
    if k ~= nil then
        k:removeSelf()
    end
end

ERROR: attempt to call method 'removeSelf' (a nil value)

A: You should destroy v and not k:
for k,v in pairs(playGroup) do
  if v ~= nil then
     v:removeSelf()
  end
end

A: You do not need to remove objects from a group, Corona does it for you when you remove the group. So the loop (even after the fix proposed by hades2510), is not required.
The error you get, "Attempt to remove an object that's already been removed..." suggests that playGroup is a regular table rather than a display object. Calling removeSelf on a display object removes Corona-related entries, leaving the object as a regular table. So there are at least these possibilities:

*

*it could be that your code has already removed playGroup as part of another event handler, or

*the handler was called a second time, or

*playGroup was created as a regular table rather than a display object.

One thing you could do is set playGroup = nil after removeSelf so that if Corona comes across that if block again, it will not attempt to remove it again:
if playGroup ~= nil then
    playGroup:removeSelf()
    -- now playGroup is plain table
    -- dont' want to run this block of code again:
    playGroup = nil
end

If this does fix the problem, it is probably still worth determining why the if block gets called after playGroup has been removed from display. A print statement, without setting playGroup to nil, will do the trick:
if playGroup ~= nil then
    print('WARNING: Going to remove play group from display')
    playGroup:removeSelf()
    print('WARNING: Play group removed from display')
end

Once you know the reason, you can add back the playGroup = nil.

A: Make sure you have inserted the object in your table or group. If you don't insert the object in table or group and try to remove it, then this error will produce.


text:
Q: whats best practice for Log Truncation in SQL Server? I have a production DB in SQL server and wanted to put the final touches after the functionality is completed. prior to shipping it out i want to make sure i have some clean up in the SQL server DB and truncate and shrink log files?
can i have a nightly job run to truncate logs and shrink files?
this is what i have so far:
MY RECOVERY MODEL IS SIMPLE
ALTER proc [dbo].[UTIL_ShrinkDB_TruncateLog]
as
-- exec sp_helpfile
BACKUP LOG PMIS WITH TRUNCATE_ONLY
DBCC SHRINKFILE (PMIS, 1)
DBCC SHRINKFILE (PMIS, 1)

A: *

*Don't truncate or shrink your log files.

*See point 1

Why do you think this is a good idea?
With simple recovery, the internal log entries are removed periodically (ready to be reused) but the file requires no more processing.
The log file is the size it is because of your day to day activities. If you shrink the log file you'll end up with poor performance.


text:
Q: How to return an array which is not equal to a specific number in ReactJS? Number = 10;
occupiedBeds = [2, 8];
I want to return numbers from 1 to number not equal to occupiedBeds, that is:
[1, 3, 4, 5, 6, 7, 9, 10]

My code so far:
 const vacantBeds = (number) => {
      const occupiedBeds = patientsData && patientsData.map((patient) => Number(patient.room.slice(-1)[0].bed))

      let numArr = [...Array(number).keys()].map((x) => x + 1)

      let filtered = numArr.filter((x) => x !== occupiedBeds)

      return filtered.map((bed) => (
        <option key={bed} value={bed}>
          {bed}
        </option>
      ))
    }

A: This should work for you
  let filtered = numArr.filter( x => !occupiedBeds.includes(x))


text:
Q: Windows: How to add batch-script action to Right Click menu I have a few programs that creates temp files or backup files or similar files that are not important.
For example, GVim for Windows by default creates a backup file in filename.txt~.
I sometimes need to clean up a directory and remove all these files. I have made a simple .bat file for this. However, it is cumbersome to have to start up CMD, navigate to the folder, run the script.
Especially since this is a script that I would like to run often on various folders. And I do not want to copy the script to multiple folders, as this would be a maintenance nightmare.
So, I was thinking, that the best solution would be to add a Right Click menu item that allows me to run the script. So that I can right click on a folder in Explorer and click Cleanup and then have my script run on this folder.
So my question is: How do I add a right click menu action that runs a custom batch script?

A: Actually, the current answer isn't out of date. I tried the exact same thing on Windows 10 and was able to add Run Batch script to the context menu of all folders in Windows.
This is the content of my batch script (won't work with UNC paths):

@ECHO OFF
ECHO %~n0 was called with the following arguments:
SET args=%*
IF NOT DEFINED args GOTO END
ECHO %*
:END
PAUSE

The registry changes I made can be replicated with this REG file:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\shell\Run Batch script]
@="&Run Batch script"

[HKEY_CLASSES_ROOT\Directory\shell\Run Batch script\command]
@="\"H:\\BATCH_FILE_PATH\\context-batch.bat\" \"%1\""

This only adds a context menu item for all directories/folders in Windows. If you want it showing for each and every file instead, you can use this:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\*\shell\Run script]
@="Run &script"

[HKEY_CLASSES_ROOT\*\shell\Run script\command]
@="\"H:\\BATCH_FILE_PATH\\context-batch.bat\" \"%1\""

Alternatively, you can add your batch script to the Send To item list by creating a shortcut to your batch script and placing it under %APPDATA%\Microsoft\Windows\SendTo (or enter shell:sendto into the address bar)
If you want your script to show in the context menu that appears when you right click on the empty space within a directory (directory background?)  you can use the following REG file:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\Background\shell\Run Batch script]
@="&Run Batch script"
"Icon"="%SystemRoot%\\System32\\shell32.dll,71"

[HKEY_CLASSES_ROOT\Directory\Background\shell\Run Batch script\command]
@="H:\\BATCH_FILE_PATH\\context-batch.bat \"%V\""

You don't need the "Icon"="%SystemRoot%\\System32\\shell32.dll,71" line. It simply adds an icon to your context-menu that looks like this:

A: I have tried on Windows XP SP3 with this .reg key. Don't have Windows 7 at the moment to test it properly but it should be almost the same.

*

*Open notepad and paste the code from below.

*Edit as per your need.

*Save as MyScript1.reg

*Double click to import in registry.

*Test by Right click on any directory in Explorer

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\shell\MyScript1]
@="Execute MyScript1"

[HKEY_CLASSES_ROOT\Directory\shell\MyScript1\command]
@="\"C:\\MyScriptsDirectory\\MyScript1Directory\\MyScript1.bat\" \"%1\""

A: I would recommend Default Programs Editor for this task.  It is both more user friendly and arguably safer than editing the registry directly.
Choose Context Menu

Select the extension you want to change.

Choose Add...

Give your command a Title, browse to the batch file and optionally pick an icon to represent your command.

Save the context menu to the registry and you're good to go.

A: @Vinayak,
If using the "send to" option, you would probably need to add the line cd /d %1 to the start of the batch command so that it runs under the target path.
my current batch file looks like this:
@echo off
cd /d %1
del *.txt
pause

Thanks for the help, I happened to stumble upon this via google at the right time :)

A: Alternative solution which I use on Windows 10 is adding script to one of folders in path variable, and then when you are in explorer use sequence:

*

*ctrl + L - to start writing in search bar

*type: cmd, then press Enter - to start cmd in current directory

*run your script, by typing its file name

A: I am using one to add the registry entries when they do not exist, and use an icon file of the folder, if it exists, already renaming it to Folder.ico.
@echo off

setlocal EnableExtensions
title <nul && title ..\\%~nx0
%__AppDir__%chcp.com 1252 >nul

set "_bat=%~dpnx0" & %__AppDir__%mode.com 40,02
set "_key=HKCR\Directory\shell\Set_Folder_Icon"

set "_reg_qry=%__AppDir__%reg.exe query "%_key%""
set "_ico_reg=%SystemRoot%\System32\shell32.dll,71"
set "_bat=%_bat:\=\\%" & set "_ico_reg=%_ico_reg:\=\\%"

>nul 2>&1 ( %__AppDir__%net.exe "session" && set "_adm=y" || set "_adm=n"
      %_reg_qry%|%__AppDir__%find.exe "_" && set "_reg=y" || set "_reg=n")

if /i "%_adm%|%_reg%" == "y|n" >nul 2>&1 (
    ( %__AppDir__%reg.exe add "%_key%" /ve /d "Set Folder Icon" /f
      %__AppDir__%reg.exe add "%_key%\command" /ve /d "\"%_bat%\" \"%%V\"" /f
      %__AppDir__%reg.exe add "%_key%" /v Icon /t reg_sz /d "\"%_ico_reg%\"" /f
    )&& goto %:^))else if /i "%_adm%|%_reg%" == "n|n" (set "_er=y" && goto %:^|
    )else if "%_adm%%_reg%" == "yy" (set "_er=n" && goto %:^|)else ;set "_er=n"

%:^)
2>nul cd/d "%~dpnx1\\." && %__AppDir__%Attrib.exe -r -a .\. || goto %:^|

if exist .\\Folder.ico (%__AppDir__%Attrib.exe -s -r -h +a .\\Folder.ico
    )else if exist .\\*.ico (for %%i in (.\\*.ico)do ren "%%~fi" Folder.ico & goto %:^/
    )else goto %:^| )

%:^/
if exist .\\Desktop.ini >.\\Desktop.old (
     %__AppDir__%Attrib.exe -s -r -h +a .\\Desktop.ini
     echo;[.ShellClassInfo] && echo;IconResource=Folder.ico,0
     %__AppDir__%Findstr.exe /bliv "\[\.Shell IconR IconF IconI" <.\\Desktop.ini
    )else >nul 2>&1 %__AppDir__%CertUtil.exe -decode -f "%~dpnx0" .\\Desktop.ini

if exist .\\Desktop.old >nul 2>&1 move/y .\\Desktop.old .\\Desktop.ini

%:^|
if "%_er%" == "y" (%__AppDir__%timeout.exe 5|echo\Admin rights required!
    )else if "%_er%" == "n" (%__AppDir__%Attrib.exe +s +r +h -a .\\Desktop.ini
     <con: %__AppDir__%Attrib.exe -r +a .\. && %__AppDir__%Attrib.exe +r -a .\.
     <con: cd../ && %comSpec% /e:off/v:off/s/q/r "ren "%~dpnx1" "%~nx1" >nul 2>&1"
    )>nul 2>&1 else rem :: batch continue.

2>nul del/q /f /a "%~f1\Desktop.old" & endlocal & <con: move nul 2>&0 ||goto :eOf
::-----BEGIN -----Wy5TaGVsbENsYXNzSW5mb10gDQpJY29uUmVzb3VyY2U9LlxGb2xkZXIuaWNvLDA
NCltWaWV3U3RhdGVdDQpNb2RlPQ0KVmlkPQ0KRm9sZGVyVHlwZT1HZW5lcmljDQo=-----END -----::

This code considers:

*

*That you are going to put the bat in the folder where it should be, where it will always be called.

*Will run a first time (as an administrator) so that the necessary entries in the Windows registry are added, (by the bat itself) and pointed to the location of the/this File.bat.

*The following executions will be right click menu, in the target folder

*If a Folder.ico file is in the target folder, it will be used, in the absence, another icon file will be used, and renamed to Folder.ico

*When a Desktop.ini file exists in the target folder, the necessary edits will be made to replace the .ico file, if not, a new one will be created.

*To add or change a folder icon

*

*You also can use a .cmd instead .reg file to add all entries in the Windows Register

*

*Save the contents below as File.cmd, and run as an administrator to add the registry entries.

Windows Registry Editor Version 5.00 2>nul

;The following line/commands run and add the current file by "itself"
;@(cls & %__APPDIR__%reg.exe import "%~f0" >nul 2>&1 & goto=:EOF )

[HKEY_CLASSES_ROOT\Directory\shell\Set_Folder_Icon]
@="Set Folder Icon"
"Icon"="\"C:\\\\WINDOWS\\\\System32\\\\shell32.dll,71\""

[HKEY_CLASSES_ROOT\Directory\shell\Set_Folder_Icon\command]
@="\"F:\\\\2020-SU\\\\Q1635169\\\\Q1635169.cmd\" \"%V\""

; Just replace drive and folder\file name...
Obs.: Initially to answer


text:
Q: Speeding up deploys and development builds for image heavy Gatsby.js website I'm using Gatsby.js and gatsby-image to build a website that currently has about 300 images on it. I'm encountering 2 problems:

*

*gatsby develop and gatsby build take many minutes to run because gatsby-image generates multiple resolutions and svg placeholder images for every image on the site. This makes for a great user experience once that pre-optimization is done, but a very slow development experience if I ever need to re-build.

My current workaround is to remove all but a few images during development.

*Deploying to GitHub Pages takes too long with so many images (300 base images * 3 resolutions + 1 svg representation). Trying to deploy the website to GitHub pages causes a timeout. Going to attempt deploying to Netlify instead, but I anticipate the same problem. I also don't want to have to re-upload the images every time I make a change on the website.

I don't feel like my <1000 images should qualify as "image heavy", but given poor to mediocre upload speeds, I need a way to upload them incrementally and not re-upload images that have not changed.
Is there a way to upload images separately from the rest of a build for a Gatsby website?
I think maybe I could get something working with AWS S3, manually choosing which files from my build folder I upload when creating a new deploy.
Anyone else dealt with handling an image-heavy Gatsby site? Any recommendations for speeding up my build and deploy process?

A: Disclaimer:  I work for Netlify
Our general recommendation is to do the image optimization locally and check those files into GitHub since it can take longer than our CI allows you (15 minutes) to do all that work and it is repetitive.
There is also an npm module that lets you cache the things you've made alongside your dependencies: https://www.npmjs.com/package/cache-me-outside that may do that for you without abusing GitHub (instead abusing Netlify's cache :))

A: See another answer from Netlify: smaller source images (as mentioned by @fool) or offloading to a service like Cloudinary or Imgix.


text:
Q: How do you web scrape nested table using PHP? Backstory
First off, I have used PHP to read email and extract out the HTML attachment which later on I stored in a PHP variable.
Now the problem I am facing is that I am trying to extract out information from the HTML in a nested table and hoping to convert to some sort of array so that I can store in SQL.
May I know if there are solutions for this? As I have tried finding but to no avail.
Example

hi

I want to locate the nearest table tag where "hi" is located so that I can get all the information from that table
Stuff I have tried
I have tried using simple HTML DOM but I guess the HTML file that I tried scraping was too large that it causes memory issues.
include('./simple_html_dom.php');

/* Parse the HTML, stored as a string in $woString */

$html = str_get_html($worksOrder);

/* Locate the ultimate grandfather table id that wraps all his generation */

$messytables = $html->find('table');

print_r($messytables);

A: Rather than using simple HTML DOM, this uses DOMDocument and XPath to find the elements.
This draws on the answer XPath to find nearest ancestor element that contains an element that has an attribute with a certain value to locate the
 tags that enclose the
 tags which have hi in it.  As there are a few levels of enclosing
 tags, it then uses last() (from XSLT getting last element) to find the innermost enclosing
...
libxml_use_internal_errors(true);
$doc = new DOMDOcument();
$doc->loadHTML( $worksOrder );
$xp = new DOMXPath($doc);

$table = $xp->query('(//ancestor::table[descendant::p="hi"])[last()]');

echo $doc->saveHTML($table[0]);

The last line is just to display the data, you can just start with $table[0] and fetch the data as needed.
This outputs with your test data...

hi


text:
Q: Maintain Tab Name on Return from SSH I use multiple terminal tabs, which I manage with names on the tabs. Thus, I have tabs named "python", "workspace", etc. One of these tabs is for an SSH connection to my remote machines, which is named "ssh".
The problem is that when I ssh into a remote machine, the tab name is changed to reflect the identity of the machine into which I'm SSH'd. This is good. However, when I come back to my local machine, the tab name is not reset to "ssh", nor is it reset to the default tab name (what appears when I open a new tab - I even have a customized version of this defined in my ~/.zshrc).
Is there a way I can reset the tab name when I come back to localhost by terminating an SSH connection?
Technical Details:

*

*OS: Mac OS X 10.9.2

*Shell: zsh

Relevant parts of ~/.zshrc:
source ~/.zsh_functions
tabn "ashwin@cortana"

Relevant parts of ~/.zsh_functions:
function tabn {
  printf "\e]1;$1\a"
}

A: There is a pair of xterm escape sequences (recognized by most terminals as well) that can save and restore the window title. The following command would push the current window title on to the stack:
printf '\e[22;2t'

and this would restore it:
printf '\e[23;2t'

You could define a function that wraps ssh to automatically save the current title and restore it after ssh completes:
ssh () {
    # If you redirect the output of ssh to a file or a pipeline,
    # make sure these terminal sequences go to the terminal, not
    # standard output.
    printf '\e[22;2t' > /dev/tty
    command ssh "$@"
    printf '\e[23;2t' > /dev/tty
}

As with any stack, this assumes that anything pushed on the stack on the remote end is popped off before ssh exits.


text:
Q: Beautiful Soup get the second attribute from element I have this code:
all_cells = result.find_all('div')
test = all_cells[1].find('a')

Which normally return this line
<a data-toggle='tooltip' data-placement='bottom' data-html='true' title="" href='details.php?id=234' title='sometext'>anothertext

I want to get the content of the second "title" attribute (sometext in my example) but also to consider that sometimes the first "title" attribute is missing. As example when the first attribute is missing this will return the info i need.
testok = test['title']


text:
Q: Sorting of a list with different lengths I have a list of disordered numbers. They are collected in different lists. I mean
list = {
   {1, 13, 5},
   {3, 94, 85, 21, 7, 5, 6},
   {2, 5, 9, 88, 4, 15, 36, 4, 8},
   {5, 3, 12, 3},
   {0, 1, 5, 66, 4, 8},
   {5, 8, 7, 4, 6, 2, 55, 98, 4, 65, 4}
   };

I want to have the list in an ordered form but when I use Sortby[list, Last] or Sort[list] nothing happens. How can I sort the list to have the results as
{  {1, 5, 13},
   {3, 5, 6, 7, 21, 85, 94},
   {2, 4, 4, 5, 8, 9, 15, 36, 88},
   {3, 3, 5, 12},
   {0, 1, 4, 5, 8, 66},
   {2, 4, 4, 4, 5, 6, 7, 8, 55, 65, 98}
}

A: Try
Map[Sort, list]
(*{{1, 5, 13}, {3, 5, 6, 7, 21, 85, 94}, {2, 4, 4, 5, 8, 9, 15, 36,
88}, {3, 3, 5, 12}, {0, 1, 4, 5, 8, 66}, {2, 4, 4, 4, 5, 6, 7, 8,
55, 65, 98}}*)


text:
Q: Install obsoleting package without removing obsoleted package Is there any way to install an obsoleting package alongside the package it obsoletes using yum? There are a couple conflicting files but the packages can coexist just fine with the latest version of these files.
A normal installation of the obsoleting package removes the obsoleted package:
# rpm -qa | grep tc-server
vfabric-tc-server-standard-2.9.7-RELEASE.noarch

# yum -y install pivotal-tc-server-standard vfabric-tc-server-standard
---> Package pivotal-tc-server-standard.noarch 0:3.2.1-RELEASE will be obsoleting
---> Package vfabric-tc-server-standard.noarch 0:2.9.7-RELEASE will be obsoleted
...
================================================================================
 Package                     Arch    Version           Repository          Size
================================================================================
Installing:
 pivotal-tc-server-standard  noarch  3.2.1-RELEASE     pivotal-app-suite   34 M
     replacing  vfabric-tc-server-standard.noarch 2.9.7-RELEASE
...
Running Transaction
  Installing : pivotal-tc-server-standard-3.2.1-RELEASE.noarch              1/2
  Erasing    : vfabric-tc-server-standard-2.9.7-RELEASE.noarch              2/2

Installed:
  pivotal-tc-server-standard.noarch 0:3.2.1-RELEASE

Replaced:
  vfabric-tc-server-standard.noarch 0:2.9.7-RELEASE

# rpm -qa | grep tc-server
pivotal-tc-server-standard-3.2.1-RELEASE.noarch

I tried:
yum -y --setopt=obsoletes=0 install pivotal-tc-server-standard vfabric-tc-server-standard

yum -y install pivotal-tc-server-standard --exclude=vfabric-tc-server-standard

Which don't seem to do anything different from a normal install.
I also tried:
# yum install pivotal-tc-server-standard --setopt=protected_packages=vfabric-tc-server-standard
---> Package pivotal-tc-server-standard.noarch 0:3.2.1-RELEASE will be obsoleting
---> Package vfabric-tc-server-standard.noarch 0:2.9.7-RELEASE will be obsoleted
Error: Trying to remove "vfabric-tc-server-standard", which is protected

A: I haven't been able to figure out how to do this using yum yet. Here's what does work:
# yum -y install yum-utils
# yumdownloader pivotal-tc-server-standard
# rpm -i --replacefiles pivotal-tc-server-standard-X.X.X-RELEASE.noarch.rpm

# rpm -qa | grep tc-server
vfabric-tc-server-standard-2.9.7-RELEASE.noarch
pivotal-tc-server-standard-3.2.1-RELEASE.noarch


text:
Q: How do you use MySQL spatial queries to find all records in X radius? I have a table in a MySQL database with a spatial geometry column of type POINT. I'd like to be able to take a point at the center of a map and find all records within X miles (or whatever distance) of it. I can't seem to find a good example or explanation of how to do this that doesn't get heavily into geometric math. I'm happy to go that route, but would first like to try and solve it with a true spatial database.

A: It won't work because MySQL hasn't actually implemented the code to make this work. They only use bounding box queries.
Notice there are no functions listed here:
http://dev.mysql.com/doc/refman/5.5/en/functions-for-testing-spatial-relations-between-geometric-objects.html
I would reccomend using PostGIS or Spatialite instead.


text:
Q: Differences between singleton/static class/instance class with a private ctor? The below seem to be very similar:

*

*What differences are there between a static and private ctor in a class?

*Furthermore, what's the difference between a singleton and an instance class with a static or private constructor?

A: Both static constructors (see Fourth version) and private constructors can be used to implement the Singleton design pattern.

A: A static constructor is called the first time the class type is mentioned in any way. Could be used for filling static dictionaries, for example. These constructors can not be called explicitly.
Private constructors on the other hand, can only be called from within the class itself. This can be used to restrict or monitor the creation of new instances of that class, by creating factory methods, for example.
As for the singleton question, Oren A about summed that up.


text:
Q: How to add custom title to django form fields? I wanna add my own title to django form fields like this image.
My models.py file
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse

class Post(models.Model):
    ad_soyad = models.CharField(max_length=255, default="")
    tarih = models.CharField(max_length=255, default="")
    dogum_tarihi = models.CharField(max_length=255, default="")
    dogum_yeri = models.CharField(max_length=255, default="")
    medeni_hali = models.CharField(max_length=255, default="")
    birinci_evlilik = models.CharField(max_length=255, default="")
    ikinci_evlilik = models.CharField(max_length=255, default="")
    bosanma_tarihi = models.CharField(max_length=255,  default="")
    ogrenim_durumu = models.CharField(max_length=255, default="")
    meslek = models.CharField(max_length=255, default="")
    kan_grubu = models.CharField(max_length=255, default="")
    boy = models.CharField(max_length=255, default="")
    kilo = models.CharField(max_length=255, default="")
    max_kilo = models.CharField(max_length=255, default="")
    max_kilo_tarih = models.CharField(max_length=255, default="")
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField()

    def __str__(self):
        return self.title + '|' + str(self.author)

    def get_absolute_url(self):
    #    return reverse('article-detail', args=(str(self.id)))   bu kod olursa yazı ekledikten sonra o eklenen yazıya gidiyor
         return reverse('home')

And my forms.py file
from django import forms
from .models import Post

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = '__all__'
        #field = ('title', 'author')

        widgets = {
            'title': forms.TextInput(attrs={'class': 'form-control'}),
            'author': forms.Select(attrs={'class': 'form-control'}),
            'body': forms.Textarea(attrs={'class': 'form-control'}),
            'ad_soyad': forms.TextInput(attrs={'class': 'form-control'}),
            'tarih': forms.TextInput(attrs={'class': 'form-control'}),
            'dogum_tarihi': forms.TextInput(attrs={'class': 'form-control'}),
            'dogum_yeri': forms.TextInput(attrs={'class': 'form-control'}),
            'medeni_hali': forms.TextInput(attrs={'class': 'form-control'}),
            'birinci_evlilik': forms.TextInput(attrs={'class': 'form-control'}),
            'ikinci_evlilik': forms.TextInput(attrs={'class': 'form-control'}),
            'bosanma_tarihi': forms.TextInput(attrs={'class': 'form-control'}),
            'ogrenim_durumu': forms.TextInput(attrs={'class': 'form-control'}),
            'meslek': forms.TextInput(attrs={'class': 'form-control'}),
            'kan_grubu': forms.TextInput(attrs={'class': 'form-control'}),
            'boy': forms.TextInput(attrs={'class': 'form-control'}),
            'kilo': forms.TextInput(attrs={'class': 'form-control'}),
            'max_kilo': forms.TextInput(attrs={'class': 'form-control'}),
            'max_kilo_tarih': forms.TextInput(attrs={'class': 'form-control'}),
        }

A: You can do this on the model level, such that this is done for all ModelForms for that model with the verbose_name=… [Django-doc]:
class Post(models.Model):
    # …,
    dogum_yeri = models.CharField(verbose_name='Doğum Tarihi', max_length=255, default="")
    # …
You can also specify the labels attribute of the Meta of the ModelForm, in that case this label of course only applies to that specific form, and for other ModelForms for the same model, you thus will have to repeat labeling:
class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = '__all__'
        widgets = {
            # …
        }
        labels = {
            'dogum_yeri': 'Doğum Tarihi'
        }
I would advise to use verbose_name first, and only if a form needs to deviate, specify the labels for that specific ModelForm.

A: I found the answer finally
Adding these code to forms.py
 labels = {
        'ad_soyad': ('Ad Soyad'),
        'dogum_tarihi': ('Doğum Tarihi'),
    }


text:
Q: Can I load a texture into OpenGL based off of the display density? Following example code for Android OpenGL programming, I am loading my textures from a raw resource.
eg.,
// Create a texture handle
int[] texArray = new int[1];
GLES20.glGenTextures(1, texArray, 0);
int textureID = texArray[0];

// Bind the texture and configure parameters
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureID);
GLES20.glTexParameterf(etc...);

// Open the image resource as a stream
InputStream is = resources.openRawResource(R.raw.sometexture);

// Read the stream into a bitmap
Bitmap bitmap = BitmapFactory.decodeStream(is);

// Load the bitmap into GL
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);

bitmap.recycle();
is.close();

(My actual code does have error checking etc...)
This is loading a bitmap from a PNG file stored in res/raw/sometexture.png
How do I load an image based on the current display density?  I assume that I would put the images into the various res/drawable-??dpi folders, but then not sure how to load them!

A: Apparently, I can use
BitmapFactory.decodeResource(getResources(), R.drawable.sometexture);

and that will load an image from the best available option of the drawable-??dpi folder under /res/.


text:
Q: Regular expression for password validation - Objective C I need a regular expression that can validate following cases,

*

*Be 8 to 20 characters

*Use at least 1 upper case letter, 1 lower case letter, and 1 number

*Not repeat the same number or letter more than 3 times in a row

*Not contain spaces, and may only use these characters
@ # * ( ) + = { } / ? ~ ; , . - _

The closest solution I can find is
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z])(?=.*[@(#*){+=}/?~;,._]).{8,20}$

But contains following issue,

*

*Accepting space

*Can't add - character

*Repeating same number or letter more than 3 times in a row.

EDIT: Fixed the repeating character issues and have final expression like,
^(?!.*?(.)\1{3})(?!.* )(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?!.*[:£€&"!'[\]%^\|<>$]).{8,20}$

But its only working on online tester like [RegExr][1]
I tried following code but it generates runtime
- (BOOL)string:(NSString *)text matches:(NSString *)pattern{

NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];

NSArray *matches = [regex matchesInString:text options:0 range:NSMakeRange(0, text.length)];

return matches.count > 0;

}


text:
Q: How to toggle auto brightness on and off? (not a repeat) I'm simply trying to toggle auto brightness on and off.
I started with this code (inside the onCreate method)
final ToggleButton autoBrightToggle = (ToggleButton) findViewById(R.id.brightToggle);

    // display auto brightness state
    final ToggleButton autoBrightToggle = (ToggleButton) findViewById(R.id.autoToggle);
    autoOnOrOff.setText(String.valueOf(getAutoBrightnessMode()));

    autoBrightToggle.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (autoBrightToggle.isChecked()) {
                setAutoBright(true);
            } else {
                setAutoBright(false);
            }
        }
    }); // end anonymous OnClickListener function

    // toggle the brightness mode
    private void  setAutoBright(boolean mode) {
      if (mode) {
        Settings.System.putInt(cr, SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
        autoOnOrOff.setText(String.valueOf(getAutoBrightnessMode()));
      } else {
        Settings.System.putInt(cr, SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_MANUAL);
        autoOnOrOff.setText(String.valueOf(getAutoBrightnessMode()));
      }
    }

Which doesn't seem to work. The setAutoBrightnessMode() method is also called again in onResume() but with the same non-results.
Anyway, I'm sorry if someone feels this question is redundant but the other posts did not get me where I need to go!
(FWIW - I'm testing this on my old Droid X and my Galaxy Nexus, not the Emulator)
EDITED - UPDATE ON THIS:
I'm 99% sure now that I am not seeing any changes to the Auto-Brightness mode reflected in the Settings panel and desktop widgets - even though I may actually be changing it's value.
part of the problem is that I don't know how exactly to determine if Auto-Brightness is on or not!
For instance, does the screen quickly and visibly change? I've been expecting immediate visible changes in brightness according to environment - but perhaps the changes are subtle? and over a longer period? or perhaps it takes 30 seconds or more of environment change before brightness changes?
Can someone suggest how I can track this? I've tried querying the Settings.System.SCREEN_BRIGHTNESS_MODE constant - hooking this method up to a textfield:
   private int getAutoBrightnessMode() {
     try {
        int brightnessMode = Settings.System.getInt(cr, SCREEN_BRIGHTNESS_MODE);
     } catch (Settings.SettingNotFoundException e) {
        e.printStackTrace();
        int brightnessMode = -10000;
     }
    return brightnessMode;
   }

But it always reads 0, even after an onResume(). :-((
I know this is a simple procedure, but I'm trying to learn this stuff on my own, and have had almost no formal CS training...  So all I can say is I'm very frustrated by this and feel like I've worked myself into a corner and at this point I'm so annoyed I can't think straight anymore.
So help would be great.

A: I use following approach in my application. Tested on HTC Desire HD and pair of noname chinese tablets.
Add to manifest permission:
<uses-permission android:name="android.permission.WRITE_SETTINGS" />

And use below code to toggle auto brightness. There is one trick in the code: we need to "refresh" brightness of app manually, because it doesn't changes automatically. May be it is the problem in your case.
void setAutoBrightness(boolean value) {
    if (value) {
        Settings.System.putInt(getContentResolver(), SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
    } else {
        Settings.System.putInt(getContentResolver(), SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_MANUAL);
    }

    // After brightness change we need to "refresh" current app brightness
    if (isChecked) {
        refreshBrightness(-1);
    } else {
        refreshBrightness(getBrightnessLevel());
    }
}

private void refreshBrightness(float brightness) {
    WindowManager.LayoutParams lp = getWindow().getAttributes();
    if (brightness < 0) {
        lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
    } else {
        lp.screenBrightness = brightness;
    }
    getWindow().setAttributes(lp);
}

int getBrightnessLevel() {
    try {
        int value = Settings.System.getInt(getContentResolver(), SCREEN_BRIGHTNESS);
        // convert brightness level to range 0..1
        value = value / 255;
        return value;
    } catch (SettingNotFoundException e) {
        return 0;
    }
}


text:
Q: Bootstrap 4 fixed-top not working on mobile I am having an issue with using 'fixed-top' with Bootstrap 4. It is working on my nav bar on the desktop. However, when using it when the navbar is collapsed it does not fix the navbar at the absolute top. When scrolling when it is collapsed the navbar will partially disappear before becoming fixed. About 50% of the navbar will disappear before becoming fixed at the top. When scrolling back up the navbar comes back into view. I'll link to a short video; https://drive.google.com/file/d/1Lxr7Qw83Co_AYqaMsLOILglhqKjiQbF8/view

SomeBrand

<button class="navbar-dark navbar-toggler" type="button" data-toggle="collapse" data-target="#navToggle" aria-controls="navToggle" aria-expanded="false" aria-label="Toggle navigation">

</button>

            SIGN IN

            REGISTER

                WELCOME CHRIS

                <button class="dropdown-item-custom navbar-link-custom" type="button">My Profile</button>

                <button class="dropdown-item-custom navbar-link-custom" type="button">Logout</button>

I'm also using AngularJS to add some color to the navbar on scroll but I'm pretty positive this has nothing to do with it, since it seems to be working fine by lg, and medium screens but the fixed top position is getting cut off on small screens.
I appreciate any feedback.
EDIT: It seems that this block of code that I use for the header is somehow creating part of this issue.. here is that code;

            NOT ALL Brands ARE CREATED EQUALLY

.header {
background: #7F00FF;  /* fallback for old browsers */
background: -webkit-linear-gradient(to top, #ff00ff 20%, #6705ff 200%);  /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(to top, #ff00ff 20%, #6705ff 200%); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
height: 100vh;

}
The way this works.. the navbar is loaded, and under it I have the page which includes the code from above to load the header. When I remove the header block, the behavior still exists but the amount of movement is cut down dramatically.

A: I just did some testing with your code and found that your HTML snippet was invalid.
That might have been the reason for your issue because after fixing the error I did extensive testing and could not detect the behavior shown in your video. I also switched to Galaxy S5 (just for good measure because that's what you were using in your video) and in all cases, the navbar remains rock-solid at the top. None of the behavior shown in your video.
Here's the valid, working code I used (click the "run code snippet" button below and expand to full screen to test):

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    SomeBrand

    <button class="navbar-dark navbar-toggler" type="button" data-toggle="collapse" data-target="#navToggle" aria-controls="navToggle" aria-expanded="false" aria-label="Toggle navigation">

    </button>

                SIGN IN

                REGISTER

                WELCOME CHRIS

                    <button class="dropdown-item-custom navbar-link-custom" type="button">My Profile</button>

                    <button class="dropdown-item-custom navbar-link-custom" type="button">Logout</button>

            Lorem ipsum dolor sit amet, consectetur adipisicing elit.

            Lorem ipsum dolor sit amet, consectetur adipisicing elit.


text:
Q: how to stop directory structure from being viewable in J2EE apps in a J2EE app if user explicitly takes out the the ending page name then what is the best way to not show the directory structure?
Example:
/mycoolapp/somefolder/test.jsp

/mycoolapp/somefolder/  -- this will show all the files under 'somefolder'

What is the best way to redirect or show the user a page saying 'not where you belong'.  I want to avoid providing index.jsp in all the folders/subfolders of my application.
Appserver being used is GlassFish.  Also the app is using Struts2 framework, though not all of the code is in struts2. Some code is using traditional Servlets

A: I noticed that you had been asking questions about GlassFish in the past, so I figured I would find out how to do this with GF.  If you are on a different server, this answer is probably wrong, since this kind of configuration is not defined in the J2EE or Java EE specs.
In AS9/Glassfish world, there is a default-web.xml file in the config directory.    Look for the setting:
<init-param>
  <param-name>listings</param-name>
  <param-value>true</param-value>
</init-param>

Change "True" to "False".
Found with this query: http://www.google.com/search?q=glassfish+disable+directory+listing
In this blog post: http://blogs.oracle.com/bounds/entry/turning_off_directory_listings_in


text:
Q: Не получается сравнить даты, если больше или меньше текущего времени Calendar.MONTH Я пытаюсь проверять дату, чтобы поставить подходящий сепаратор, но проблема в том, что сравнение Calendar.MONTH не происходит, а остальные проверки нормально работают.
Подскажите, как можно это сделать ?
if   (calendar.get(Calendar.DAY_OF_YEAR) > Calendar.getInstance().get(Calendar.DAY_OF_YEAR) && calendar.get(Calendar.YEAR) > Calendar.getInstance().get(Calendar.YEAR) ||
                        (calendar.get(Calendar.DAY_OF_YEAR) < Calendar.getInstance().get(Calendar.DAY_OF_YEAR) && calendar.get(Calendar.YEAR) > Calendar.getInstance().get(Calendar.YEAR)) ||
                        (calendar.get(Calendar.DAY_OF_YEAR) == Calendar.getInstance().get(Calendar.DAY_OF_YEAR) && calendar.get(Calendar.YEAR) > Calendar.getInstance().get(Calendar.YEAR))||
                        (calendar.get(Calendar.DAY_OF_YEAR) == Calendar.getInstance().get(Calendar.DAY_OF_YEAR) && calendar.get(Calendar.MONTH) > Calendar.getInstance().get(Calendar.MONTH)&&calendar.get(Calendar.YEAR) == Calendar.getInstance().get(Calendar.YEAR)))
                        {
                newTask.setDateStatus(ModelSeparator.TYPE_FUTURE);
                if (!adapter.containsSeparatorFuture) {
                    adapter.containsSeparatorFuture = true;
                    separator = new ModelSeparator(ModelSeparator.TYPE_FUTURE);
                    Toast.makeText(getActivity(),"Future",Toast.LENGTH_SHORT).show();
                }

A: Класс Calendar реализует методы after(Object calendar) и before(Object calendar), с помощью которых легко сравнивать даты.


text:
Q: 'Permission denied' while installing 32-bit Java (JDK/JRE) on 64-bit Ubuntu I use Ubuntu 10.10 server as test server for a Java program.
Linux sugam 2.6.35-22-server #35-Ubuntu SMP Sat Oct 16 22:02:33 UTC 2010 x86_64

GNU/Linux Ubuntu 10.10
Since it is a test server and we like to see our application to work in both, 64-bit and 32-bit Java, I like to have OpenJDK (32-bit and 64-bit) and Java SE (32-bit and 64-bit), (total 4 instances) installed on the server.
I could install 64-bit easily and have the following Java versions:
$/app/java64bit/jre1.6.0_23/bin/java -version
java version "1.6.0_23"
Java(TM) SE Runtime Environment (build 1.6.0_23-b05)
Java HotSpot(TM) 64-Bit Server VM (build 19.0-b09, mixed mode)

$ /usr/lib/jvm/java-6-openjdk/jre/bin/java -version
java version "1.6.0_20"
OpenJDK Runtime Environment (IcedTea6 1.9.2) (6b20-1.9.2-0ubuntu2)
OpenJDK 64-Bit Server VM (build 19.0-b09, mixed mode)

But I am unable to install 32-bit Java on this 64-bit machine.
I have correct binaries (cksum and md5sum validated).
On unpacking I get the following error for 32-bit version:
$ ./jre-6u23-linux-i586.bin
Unpacking...
./jre-6u23-linux-i586.bin: 56: cannot create install.sfx.12308: Permission denied
Checksumming...
/usr/bin/sum: install.sfx.12308: No such file or directory
[: 83: -ne: unexpected operator
[: 83: -ne: unexpected operator
chmod: cannot access `install.sfx.12308': No such file or directory
Extracting...
./jre-6u23-linux-i586.bin: 86: ./install.sfx.12308: not found
Failed to extract the files.  Please refer to the Troubleshooting section of
the Installation Instructions on the download page for more information.

Is there a way to install 32-bit Java on a 64-bit server?
Any help appreciated.

A: The error given suggests that you are trying to run the binary to somewhere that you don't have permissions. I'm fairly certain that you have to run it as root, so sudo ./jre-6u23-linux-i586.bin should get rid of that error.
Also make sure that you have ia32-lib installed, otherwise you shouldn't be able to run 32-bit applications.


text:
Q: Kubectl: command not found on travis ci I am trying to deploy a kubernetes cluster using Travis CI and I get the following error
EDIT:

invalid argument "myAcc/imgName:" for t: invalid reference format
See docker build --help
./deploy.sh: line 1: kubectl: command not found

This is my travis config file
travis.yml
sudo: required
services:
  - docker
env:
  global:
    - SHA-$(git rev-parse HEAD)
    - CLOUDSDK_CORE_DISABLE_PROMPTS=1
before-install:
  - openssl aes-256-cbc -K $encrypted_0c35eebf403c_key -iv $encrypted_0c35eebf403c_iv -in service-account.json.enc -out service-account.json -d
  - curl https://sdk.cloud.google.com | bash > /dev/null
  - source $HOME/google-cloud-sdk/path.bash.inc
  - gcloud components update kubectl
  - gcloud auth activate-service-account --key-file service-account.json
  - gcloud config set project robust-chess-234104
  - gcloud config set compute/zone asia-south1-a
  - gcloud container clusters get-credentials standard-cluster-1
  - echo "$DOCKER_PASSWORD" | docker login -u "$DOCKER_USERNAME" --password-stdin

deploy:
  provider: script
  script: bash ./deploy.sh
  on:
    branch: master

This is my deploy script
deploy.sh
doccker build -t myAcc/imgName:$SHA
docker push myAcc/imgName:$SHA
kubectl apply -k8s

I guess the gcloud components update kubectl command is not working. Any ideas?
Thanks !

A: The first issue invalid argument "myAcc/imgName:" for t: invalid reference format because the variable $SHA is not defined as expected. There is a syntax issue with defining the variable you should use = instead of - after SHA, so it should be like this:
- SHA=$(git rev-parse HEAD)

The second issue which is related to kubectl you need to install it using the following command according to the docs:
gcloud components install kubectl

Update:
After testing this file on Travis-CI I was able to figure out the issue. You should use before_install instead of before-install so in your case the before installation steps never get executed.
# travis.yml
---
env:
  global:
    - CLOUDSDK_CORE_DISABLE_PROMPTS=1
before_install:
 - curl https://sdk.cloud.google.com | bash > /dev/null
 - source $HOME/google-cloud-sdk/path.bash.inc
 - gcloud components install kubectl

script: kubectl version

And the final part of the build result:
$ kubectl version
Client Version: version.Info{Major:"1", Minor:"11", GitVersion:"v1.11.7", GitCommit:"65ecaf0671341311ce6aea0edab46ee69f65d59e", GitTreeState:"clean", BuildDate:"2019-01-24T19:32:00Z", GoVersion:"go1.10.7", Compiler:"gc", Platform:"linux/amd64"}


text:
Q: Why it's showing Undefined index when I try to convert a module from M1 to M2? I'm trying to convert one module to M2, and after running the code_conversion_tool, I've ended up with .converted files all around.
I've renamed them to replace the actual files.
While doing setup:upgrade I get:
[Exception]
  Notice: Undefined index: modules in <path to magento2>/vendor/magento/framework/App/Route/Config/Converter.php on line 47

If I remove the module from the app/code folder the error disappears, so it's clear that is the converted module causing this.
How can I pinpoint the origin of this issue?
I've done  " grep -rnisI "converter" * " inside the module folder and got 2 references for the word "Converter"
Model/Checkout/Onepage.php:30:
\Magento\Framework\Api\ExtensibleDataObjectConverter $extensibleDataObjectConverter,

Model/Checkout/Onepage.php:59:
$extensibleDataObjectConverter,

But i don't see any relation with line 47 wich is:
$routeConfig['modules'] = $this->_sortModulesList($routeConfig['modules']);

Can someone help, please?

A: This tool will not fully convert your module - it will only perform a limited set of code changes. You are responsible for remaining tasks.


text:
Q: String s = new String("abc") memory allocation String s = new String("abc")

I know that this would create a new String object in Heap.
But i am confused about a statement in SCJP book by Kathy Sierra.
It states that the above statement would create an object in heap and at the same if the String "abc" is not present in the String pool , it would also add "abc" to the String pool.
Could anyone please tell me if the object "abc" is also created in the String pool in the above case.

A:
String s = new String("abc")

Yes,above line will create two objects, one in string pool and other in Heap.
So, now
1) If you create a string literal like:-
String s1="abc"; //abc value will be taken from string pool which is previously added

2) If you create a String object and call intern method, no new object will be created instead it will just refer to "abc" present in string pool.
String s2=new String("abc").intern();

Note: When we are creating new String object based on existing one, it reuses char[] value.
Since new String(someStringValue) creates an exact copy of existing string and strings are immutable, there is clearly no reason for the two to exist at the same time.
Even if you have two String objects, they might still point to the same content.
You can refer this:- https://dzone.com/articles/string-memory-internals

A: Yes it does. To optimize memory use, it does so.
In case you create another variable with same value "abc",
new variable will still point to earlier rather than creating a new one.
Somehow it is trying not to create two equal objects

A: Yes, it will be created as you are not having the same string before this line in your code. Now consider this example.
String temp = "abc";            // line1
String s = new String("abc");   // line2

In this case "abc" is not recreated. s will point to "abc" that was created at line 1.

sujith in comment : But in that case i do not see any difference between String temp ="abc" and String temp = new String("abc").

In line 1 a new "abc" will be created in heap. And a new String object will be created and added into the stack. And in line2 a new object of String will be created which will be referring to the "abc" that was created at line1 in heap. To better understand what thing goes to stack and what goes to heap visit here.


text:
Q: Mysql - Performance Issues I have the following 2 tables:
CREATE TEMPORARY TABLE T1 (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Date` datetime NOT NULL,
  PRIMARY KEY (`ID`)
)ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE T2 (
  `ID` bigint(20) NOT NULL AUTO_INCREMENT,
  `RecordID` int(11) NOT NULL,
  PRIMARY KEY (`ID`),
  KEY `ID` (`ID`),
  KEY `RecordID` (`RecordID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

where T1 has ~100,000 records
and T2 has ~6,000,000 records
The following query takes ~1.5 seconds:
SELECT * FROM T1 INNER JOIN T2 ON T1.ID = T2.RecordID

when I add the following where clause, it takes ~20 seconds:
WHERE T1.Date <= '2017-02-18'

Knowing that the query with the where cause returns no records.
I need your help please.

A: You have to be careful when you measure the speed of a query.  If you only look for the return of the first row, then you might get a misleading indicator.
For this query:
SELECT *
FROM T1 INNER JOIN
     T2
     ON T1.ID = T2.RecordID
WHERE T1.Date <= '2017-02-18';

You want a composite index on T1(Date, ID).  You also want an index on T2(RecordId), but you already have that index.


text:
Q: Does anybody know what the ARP cache timeout is for macOS Sierra? Does anyone know deafult ARP cache timeout for macOS Sierra?

A: There's no standard time out value for routes stored in an arp table.  For instance, on Cisco gear, it's 4 hours.
The arp utility that macOS uses is the one from BSD and it's time out is 20 minutes if the host has been validated. Static entries don't time out, but can be over written by network traffic.  Permanent entries also do not time out and cannot be over written.