text:
Q: What is the algorithm that Sass uses to resolve an @import statement? The algorithm that Node.js uses to resolve a require() call is very clearly documented in pseudocode.
I need the same thing for Sass's @import statement.
I know that @import 'foo' will try various combinations of the basenames foo and _foo, with extensions .scss and .sass, in the same directory as the importing file as well as relative to any of the configured 'load paths'... But what order these are tried in, i.e. what takes precedence if there are multiple files that could satisfy the @import? Does starting with a ./ or ../ affect whether it tries the load paths? Are there any other things it will try that I haven't covered? What about .css files?
The guide doesn't say much beyond "Sass is smart and will figure it out for you." The reference docs go into more detail, but still don't spell out the resolution steps.
Can anyone provide the exact algorithm it uses, in pseudocode?

A: Here is a simplified algorithm for @import <import_arg>;.
This is derived from reading the source code for SASS and from running my own tests.
def main(import_arg)
  let dirname = File.dirname(import_arg)
  let basename = File.basename(import_arg)
  if import_arg is absolute ... # omitted as this is a rare case
  else return search(dirname, basename)
end

# try resolving import argument relative to each path in load_paths
# 1. If we encounter an unambiguous match, we finish
# 2. If we encounter an ambiguous match, we give up
# see: https://stackoverflow.com/a/33588202/3649209
def search(dirname, basename)
  let cwd = operating system current working directory
  let load_paths = paths specified via SASS_PATH env variable and via --load-path options
  let search_paths = [cwd].concat(load_paths)
  for path in search_paths
    let file = find_match(File.expand_path(basename, path), basename)
    if (file != false) return file
  end
  throw "File to import not found or unreadable"
end

def find_match(directory, basename)
  let candidates = possible_files(directory, basename)
  if candiates.length == 0
    # not a single match found ... don't give up yet
    return false
  else if candidates.length > 1
    # several matching files, ambiguity! ... give up
    # throw ambiguity error
    throw "It's not clear which file to import"
  else
    # success! exactly one match found
    return candidates[0]
  end
end

# NB: this is a bit tricky to express in code
# which is why I settled for a high-level description
def possible_files(directory, basename)
  # if `basename` is of the form shown on the LHS
  # then check the filesystem for existence of
  # any of the files shown on the RHS within
  # directory `directory`. Return the list all the files
  # which do indeed exist (or [] if none exist).
  #   LHS        RHS
  #   x.sass -> _x.sass, x.sass
  #   x.scss -> _x.scss, x.scss
  #   x      -> x.scss, _x.scss, x.sass, _x.sass
  #   _x     -> _x.scss, _x.sass
end

Note for brevity, I am using Ruby's File#dirname, File#basename as well as File#expand which is like Node.js's path.resolve. I'm using a Ruby-like pseudocode but it is still meant to be pseudocode.
Key Points:

*

*There is no precedence order. Rather than implementing a precedence order, SASS gives up when there are several possible candidates. For example, if you wrote @import "x" and say both x.scss and _x.scss exist, then sass will throw an ambiguity error. Similarly, if both x.scss and x.sass exist then an ambiguity error is thrown.

*Load paths are tried from 'left to right' order. They provide a root or base to resolve imports from (similar how UNIX use $PATH to find executables). The current working directory is always tried first. (although this behaviour will change from 3.2 to 3.4)

*Load paths are always tried regardless of whether you used ./ or ../

*In a sass file, regular .css files cannot be imported
If you want more detail, I would recommend reading SASS's source code:

*

*the import method of sass/lib/sass/tree/import_node.rb. On lines 53-56 you can see the same for loop as the one inside the search function in our pseudocode.

*the Importers::Base abstract class sass/lib/sass/importors/base.rb. The comments of this file are quite handy.

*the find_real_file method of sass/lib/sass/importors/filesystem.rb. Lines 112-126 implements our possible_files function. Line 156 checks there is only one match. If there isn't then line 167 throws an ambiguity error, else line 183 picks the one matching file.

Edit: I wasn't happy with my previous answer so I've rewritten it to be a bit clearer. Algorithm now correctly handles underscores in filename (previous algorithm didn't). I also added some key points that address the other questions OP asked.


text: Q: Is any algebraic number a root of a given orthogonal polynomial? Let $S=\left\{P_n(x)\right\}_{n=0}^{\infty}$ be any sequence of $n$-degree polynomials which are orthogonal in the interval $(a,b)\in\mathbb{R}$. If $\xi$ is an arbitrary algebraic number such that $a<\xi<b$, then, is true that we can always find a finite positive integer $m$ such that $P_m(\xi)=0$?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Confluent kafka sink connector error: java.sql.SQLException: Field 'email' doesn't have a default value I am trying to take data from kafka topic and then insert it to a mysql database table. The topic (smartdevdbserver1.signup_db.users) is derived from another mysql database table column called users and is populated using a debezium CDC mysql source connector.
I will be grateful if someone can help me figure out why the sink connector is throwing the below error:
connect           | java.sql.SQLException: Field 'email' doesn't have a default value
connect           |
connect           |     at io.confluent.connect.jdbc.sink.JdbcSinkTask.put(JdbcSinkTask.java:93)
connect           |     at org.apache.kafka.connect.runtime.WorkerSinkTask.deliverMessages(WorkerSinkTask.java:581)
connect           |     at org.apache.kafka.connect.runtime.WorkerSinkTask.poll(WorkerSinkTask.java:333)
connect           |     at org.apache.kafka.connect.runtime.WorkerSinkTask.iteration(WorkerSinkTask.java:234)
connect           |     at org.apache.kafka.connect.runtime.WorkerSinkTask.execute(WorkerSinkTask.java:203)
connect           |     at org.apache.kafka.connect.runtime.WorkerTask.doRun(WorkerTask.java:188)
connect           |     at org.apache.kafka.connect.runtime.WorkerTask.run(WorkerTask.java:243)
connect           |     at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
connect           |     at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
connect           |     at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
connect           |     at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
connect           |     at java.base/java.lang.Thread.run(Thread.java:829)
connect           | Caused by: java.sql.SQLException: java.sql.BatchUpdateException: Field 'email' doesn't have a default value
connect           | java.sql.SQLException: Field 'email' doesn't have a default value

The schema and payload of kafka topic looks like this:
{"schema":{"type":"struct","fields":[{"type":"int32","optional":false,"field":"id"},{"type":"string","optional":false,"field":"email"},{"type":"string","optional":false,"field":"password"},{"type":"string","optional":false,"name":"io.debezium.data.Enum","version":1,"parameters":{"allowed":"ACTIVE,INACTIVE"},"default":"INACTIVE","field":"User_status"},{"type":"string","optional":true,"field":"auth_token"}],"optional":false,"name":"smartdevdbserver1.signup_db.users.Value"},"payload":{"id":6,"email":"testing6@firstclicklimited.com","password":"$2a$10$PRGfCpjCCKqSKSf89m5M6uSRWzjlZTG7RuuJgR5MrVY.nh0BKA7Nq","User_status":"INACTIVE","auth_token":null}}

Below is the kafka sink connector config:
{
    "name": "resetpassword-sink-connector",
    "config": {
        "connector.class": "io.confluent.connect.jdbc.JdbcSinkConnector",
        "tasks.max": "1",
        "key.converter": "org.apache.kafka.connect.json.JsonConverter",
        "value.converter": "org.apache.kafka.connect.json.JsonConverter",
        "key.converter.schemas.enable": "true",
        "value.converter.schemas.enable": "true",
        "topics": "smartdevdbserver1.signup_db.users",
        "connection.url": "jdbc:mysql://RPWD_mysql:3306/rpwd_db?user=rpwd_user&password=*xxxxxxxx*",
        "fields.whitelist": "rpwd_db.users.email,rpwd_db.users.password,rpwd_db.users.User_status,rpwd_db.users.auth_token",
        "transforms.unwrap.drop.tombstones": "false",
        "insert.mode": "upsert",
        "delete.enabled": "true",
        "table.name.format": "rpwd_db.users",
        "pk.fields": "id",
        "pk.mode": "record_key"
    }
}

The table schema where data is to be inserted:
DROP TABLE IF EXISTS `users`;
CREATE TABLE IF NOT EXISTS `users` (
  `id` int NOT NULL AUTO_INCREMENT,
  `email` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `User_status` enum('ACTIVE','INACTIVE') NOT NULL DEFAULT 'INACTIVE',
  `auth_token` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

I tried to use auto.create so that the sink connector can create its own table (just so i see if the error will go away) but the table it created had just one field (and that's the primary key field: id), and of course, there was no error. So i am guessing that the sink connector sees every other field (perhaps) as a null.

A: Something similar happened to me. Have you tried removing the schema and table from fields.whitelist property?
"fields.whitelist": "email,password,User_status,auth_token"


text:
Q: Java Riddle with finally block and recursion I just prepared a game for our team about java riddles. So to say, small pieces of java code that do things that you do not expect at the first glance.
While googeling for such riddles I also scribbled around in my IDE and tried out some weird things that you would never write in production code. Just for the fun of it.
Suddenly I came up with the following:
public static int cnt = 0;
public static int blubb() {
    try {
        cnt++;
        return blubb();
    } finally {
        return cnt;
    }
}

public static void main(String[] args) {
    System.out.println(cnt + ": " + Main.blubb() + ": " + cnt);
}

When executed it prints something like "0: 21245: 21245" where 21245 is different for each run.
I'd expect either an endless recursion, or returning 1 in the finally block (0: 1: 1)
When adding a catch block to catch Throwable and debugging, the debugger will never stop in this block.
Can somebody explain me what is going on here?

A: Adding a catch block like this, and not seeing a stack trace, doesn't indicate that nothing was thrown:
    } catch (Throwable t) {
      t.printStackTrace();
      throw t;
    } finally { ... }

Not being able to print the stack trace of a StackOverflowError immediately after catching a StackOverflowError is expected: a SOE literally means that no more method calls can be made.
But to invoke printStackTrace(), you need to make another method call. So, that method call actually results in another, separate StackOverflowError, which you don't attempt to print. But then the return in the finally causes the StackOverflowError to be discarded.
Try this, which doesn't require a method invocation when the StackOverflowError is thrown:
import java.util.*;

class Main {
  public static int cnt = 0;

  private static Throwable caught;

  public static int blubb() throws Throwable {
    try {
      cnt++;
      return blubb();
    } catch (Throwable t) {
      caught = t;
      throw t;
    } finally {
      return cnt;
    }
  }

  public static void main(String[] args) throws Throwable {
    System.out.println(cnt + ": " + Main.blubb() + ": " + cnt);
    System.out.println(caught);
  }
}

For me, this prints:
0: 9672: 9672
java.lang.StackOverflowError

So yes, a StackOverflowError was caught.

A: You create an infinite recursion loop.
At one time the call stack get so big it throws an StackOverflowError and you your app should crash.
BUT you set the recursive call in a try block. So the exception is partially handled, while not being displayed as you don't have a catch block.
As you have a finally block returning the value of cnt, the many calls in the stack return the value, then returning 19543 or whatever number of times it was called before the exception.
TL;DR : when using a try block, don't hide the exception


text:
Q: Allow C++ constants to be a default function parameter using Rcpp Attributes I created a cumsum function in an R package with rcpp which will cumulatively sum a vector until it hits the user defined ceiling or floor. However, if one wants the cumsum to be bounded above, the user must still specify a floor.
Example:
a = c(1, 1, 1, 1, 1, 1, 1)

If i wanted to cumsum a and have an upper bound of 3, I could cumsum_bounded(a, lower = 1, upper = 3). I would rather not have to specify the lower bound.
My code:
#include <Rcpp.h>
#include <float.h>
#include <cmath>
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector cumsum_bounded(NumericVector x, int upper, int lower) {
  NumericVector res(x.size());
  double acc = 0;
  for (int i=0; i < x.size(); ++i) {
    acc += x[i];
    if (acc < lower)  acc = lower;
    else if (acc > upper)  acc = upper;
    res[i] = acc;
  }
  return res;
}

What I would like:
#include <Rcpp.h>
#include <float.h>
#include <cmath>
#include <climits> //for LLONG_MIN and LLONG_MAX
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector cumsum_bounded(NumericVector x, long long int upper = LLONG_MAX, long long int lower = LLONG_MIN) {
  NumericVector res(x.size());
  double acc = 0;
  for (int i=0; i < x.size(); ++i) {
    acc += x[i];
    if (acc < lower)  acc = lower;
    else if (acc > upper)  acc = upper;
    res[i] = acc;
  }
  return res;
}

A: In short, yes its possible but it requires finesse that involves creating an intermediary function or embedding sorting logic within the main function.

In long, Rcpp attributes only supports a limit feature set of values. These values are listed in the Rcpp FAQ 3.12 entry

*

*String literals delimited by quotes (e.g. "foo")

*Integer and Decimal numeric values (e.g. 10 or 4.5)

*Pre-defined constants including:

*

*Booleans: true and false

*Null Values: R_NilValue, NA_STRING, NA_INTEGER, NA_REAL, and NA_LOGICAL.

*Selected vector types can be instantiated using the
  empty form of the ::create static member function.

*

*CharacterVector, IntegerVector, and NumericVector

*Matrix types instantiated using the rows, cols constructor Rcpp::Matrix n(rows,cols)

*

*CharacterMatrix, IntegerMatrix, and NumericMatrix)

If you were to specify numerical values for LLONG_MAX and LLONG_MIN this would meet the criteria to directly use Rcpp attributes on the function.  However, these values are implementation specific. Thus, it would not be ideal to hardcode them. Thus, we have to seek an outside solution: the Rcpp::Nullable<T> class to enable the default NULL value. The reason why we have to wrap the parameter type with Rcpp::Nullable<T> is that NULL is a very special and can cause heartache if not careful.
The NULL value, unlike others on the real number line, will not be used to bound your values in this case. As a result, it is the perfect candidate to use on the function call. There are two choices you then have to make: use Rcpp::Nullable<T> as the parameters on the main function or create a "logic" helper function that has the correct parameters and can be used elsewhere within your application without worry. I've opted for the later below.
#include <Rcpp.h>
#include <float.h>
#include <cmath>
#include <climits> //for LLONG_MIN and LLONG_MAX
using namespace Rcpp;

NumericVector cumsum_bounded_logic(NumericVector x,
                                   long long int upper = LLONG_MAX,
                                   long long int lower = LLONG_MIN) {

    NumericVector res(x.size());
    double acc = 0;
    for (int i=0; i < x.size(); ++i) {
        acc += x[i];
        if (acc < lower)  acc = lower;
        else if (acc > upper)  acc = upper;
        res[i] = acc;
    }

    return res;
}

// [[Rcpp::export]]
NumericVector cumsum_bounded(NumericVector x,
                             Rcpp::Nullable<long long int> upper = R_NilValue,
                             Rcpp::Nullable<long long int> lower = R_NilValue) {

    if(upper.isNotNull() && lower.isNotNull()){
        return cumsum_bounded_logic(x, Rcpp::as< long long int >(upper), Rcpp::as< long long int >(lower));
    } else if(upper.isNull() && lower.isNotNull()){
        return cumsum_bounded_logic(x, LLONG_MAX, Rcpp::as< long long int >(lower));
    } else if(upper.isNotNull() && lower.isNull()) {
        return cumsum_bounded_logic(x, Rcpp::as< long long int >(upper), LLONG_MIN);
    } else {
        return cumsum_bounded_logic(x, LLONG_MAX, LLONG_MIN);
    }

    // Required to quiet compiler
    return x;
}

Test Output
cumsum_bounded(a, 5)
## [1] 1 2 3 4 5 5 5
cumsum_bounded(a, 5, 2)
## [1] 2 3 4 5 5 5 5


text:
Q: Select matching substring Given the following ideal2.json

[
    {
    "url": "/classroom-videos/lesson1/sublesson1/video",
        "data": {
            "fieldset": "lesson-video-overview",
            "title": "5th Grade Math - Interpreting Fractions",
        },
        "order": 4
    },
    {
    "url": "/classroom-videos/lesson1/sublesson2/video",
        "data": {
            "fieldset": "lesson-video-clip-single",
            "title": "Post-Lesson Debrief Part 5",
        },
        "order": 14
    },
    {
        "url" : "about-us",
        "data": {
            "fieldset": "lesson-video-clip-single",
            "title": "Lesson Part 2B",
        },
        "order": 6
    }
]

I want to extract only the items where the url starts with /classroom-videos/
Ideally my output would look like this:

[
    {
    "url": "/classroom-videos/lesson1/sublesson1/video",
        "data": {
            "fieldset": "lesson-video-overview",
            "title": "5th Grade Math - Interpreting Fractions",
        },
        "order": 4
    },
    {
    "url": "/classroom-videos/lesson1/sublesson2/video",
        "data": {
            "fieldset": "lesson-video-clip-single",
            "title": "Post-Lesson Debrief Part 5",
        },
        "order": 14
    }
]

I tried lots of variations with no luck:
e.g.
select(.url | contains("yomama")) produces
jq: error (at :47): Cannot index array with string "url"
exit status 5
.[].url produces a nice list of all the urls

A: It looks like this might do the trick:
jq '.[] | select(.url |test("classroom-videos"))'


text:
Q: using asynTask to update LocationListener im already looking for the aswer in this forum but none working, im creating an android apps and im trying to get coordinate update from locationlistener in asyncTask (my asyncTask job only to update the latitute and longitude)
while the main thread get the coodinate from the asyncTask via Location Manager, and it works yesterday, today its not working anymore,
here's my asyncTask code :
 private class LoopMsg extends AsyncTask<String,Void,Void>{
        protected Void doInBackground(String... urls){

            Looper.prepare();

            LocationListener listen = new LocationListener() {

                @Override
                public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onProviderEnabled(String arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onProviderDisabled(String arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onLocationChanged(Location loc) {
                    // TODO Auto-generated method stub

                    Log.d(TAG,"Latitude :"+String.valueOf(loc.getLatitude()));
                    Log.d(TAG,"Longitude :"+String.valueOf(loc.getLongitude()));
                    Glatitude = loc.getLatitude();
                    Glongitude = loc.getLongitude();
                }
            };
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 0, listen);
            Looper.loop();

            return null;

        }
    }

please help me what went wrong here? and how to fix this? it running good before
the next day i got exception at Looper.prepare()
it says that only one looper may be created per thread, then i delete Looper.prepare and Looper.loop Part, the error change become
*FATAL EXCEPTION: asyncTask #1
*java.lang.RuntimeException: an error occured while executing do in background

im really don't know why, coz im not update ui thread at my doInBackground method
why i know my app not working :
1.onLocationChanged never called again
2.the app crash if im not using looper.prepare and looper.loop
and I also tried like this :
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 0, listen, Looper.getMainLooper());

and this :
Looper.Mylooper.prepare();
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 0, listen, Looper.getMyLooper());

but still no luck,the app still not running
this is the logCat i got after removing the Looper in AsyncTask (and the app always crash)
-Fatal Exception: AsyncTask#2
-java.lang.RuntimeException: An error occured while executing doInBackground()
-at android.os.AsyncTask$3.done(AsyncTask.java:299)
-at java.util.concurrent.FutureTask.finishCompletion(FutureTask.Java:219)
-at java.util.concurrent.FutureTask.run(FutureTask.Java:239)
-at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
-at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
-at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
-at java.lang.Thread.run(Thread.java:838)
-Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not  called Looper.prepare()
-at android.os.Handler.<init>(Handler.java:197)
-at android.os.Handler.<init>(Handler.java:111)
-at android.location.LocationManager$ListenerTransport$1.<init>(LocationManager.java:199)
-at android.location.LocationManager$ListenerTransport.<init>(LocationManager.java:199)
-at android.location.LocationManager.wrapListener(LocationManager.java:822)
-at android.location.LocationManager.requestLocationUpdates(LocationManager.java:835)
-at android.location.LocationManager.requestLocationUpdates(LocationManager.java:432)
-at android.location.ZTEPrivacyLocationManager.requestLocationUpdates(ZTEPrivacyLocationManager.java:107)
-at com.login.absen.MyService$LoopMsg.doInBackground(MyService.java:244)
-at com.login.absen.MyService$LoopMsg.doInBackground(MyService.java:1)
-at android.os.AsyncTask$2.call(AsyncTask.java:287)
-at java.util.concurrent.FutureTask.run(FutureTask.java:234)
-... 4 more

UPDATE
i guest i can simplyfy the problem
Actually the problem was the onLocationChange method not called at (zte n986 - android 4.2) , im trying this code in another device (journey - android 2.3.3) the behavior was the same, asyncTask also stop running at Looper.loop BUT the onLocationChange method was running, so the location update still running

A: First there is no need of AsyncTask for listening for location update. LocationLintener itself run asynchronously  so just register for location update and update the ui in
 public void onLocationChanged(Location loc) {
                    // TODO Auto-generated method stub

                }

A: Use Service and you can use Location Listner there,no ne

A: public class LocateDeviceService extends Service {

private static final String TAG = "";

double lat = 0;
    double lng = 0;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    customHandler.postDelayed(updateTimerThread, 0);
    return super.onStartCommand(intent, flags, startId);
}

private Handler customHandler = new Handler();

private Runnable updateTimerThread = new Runnable() {

    public void run() {
        try {
            //send location

    LocationManager locman = (LocationManager) context
            .getSystemService(Context.LOCATION_SERVICE);

    Criteria criteria = new Criteria();
    String provider = locman.getBestProvider(criteria, false);
    Location location = locman.getLastKnownLocation(provider);

    if (location != null) {
        lat = location.getLatitude();
        lng = location.getLongitude();

    }

            customHandler.postDelayed(this,60000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

};

public void sendLocationToServer(Double lat,Double lng )
        throws InterruptedException {
    //do ur job here

}

@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    if (null != customHandler && null != updateTimerThread) {
        customHandler.removeCallbacks(updateTimerThread);
    }
}
}

A: There is no need for AsyncTask to get location changes. Locations can be sent to your registered class running on main thread. If you want to upload the location to a server, then use AsynTask only for that portion.

Here are steps:

1. Implement "LocationListener" on your class that extends Service.

2. Then you need to implement the unimplemented methods in the LocationListener. Location is passed to you on is:

    @Override
    public void onLocationChanged(Location location) {
        //Use AsyncTask only to upload the location information
        uploadLocationToServerThroughAsyncTask(location);
    }

3. Now, register with LocationManager to send the locations to your class when it changes as below:

    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    String provider = lm.getBestProvider(criteria, true);
    if (provider == null || provider.trim().isEmpty()) {
        // No provider hence return.
        return;
        }
    // If there are any available provider, then register for location updates.
    lm.requestLocationUpdates(locProvider, 1000, 200, this); // 1 sec and 200 meter updates

4. Unregister from location manager at the appropriate time as below:

    try {
        lm.removeUpdates(this);
        } catch (Exception e) {
        e.printStackTrace();
    }


text:
Q: Efficient way in Pandas to count occurrences of Series of values by row I have a large dataframe for which I want to count the number of occurrences of a series specific values (given by an external function) by row. For reproducibility let's assume the following simplified dataframe:
data = {'A': [3, 2, 1, 0], 'B': [4, 3, 2, 1], 'C': [1, 2, 3, 4], 'D': [1, 1, 2, 2], 'E': [4, 4, 4, 4]}
df = pd.DataFrame.from_dict(data)
df
   A  B  C  D  E
0  3  4  1  1  4
1  2  3  2  1  3
2  1  2  3  2  2
3  0  1  4  2  4

How can I count the number of occurrences of specific values (given by a series with the same size) by row?
Again for simplicity, let's assume this value_series is given by the max of each row.
values_series = df.max(axis=1)
0    4
1    3
2    3
3    4
dtype: int64

The solution I got to seems not very pythonic (e.g. I'm using iterrows(), which is slow):
max_count = []
for index, row in df.iterrows():
    max_count.append(row.value_counts()[values_series.loc[index]])
df_counts = pd.Series(max_count)

Is there any more efficient way to do this?

A: We can compare the transposed df.T directly to the df.max series, thanks to broadcasting:
(df.T == df.max(axis=1)).sum()

# result
0    2
1    1
2    1
3    2
dtype: int64

(Transposing also has the added benefit that we can use sum without specifying the axis, i.e. with the default axis=0.)

A: You can try
df.eq(df.max(1),axis=0).sum(1)
Out[361]:
0    2
1    1
2    1
3    2
dtype: int64

A: The perfect job for numpy broadcasting:
a = df.to_numpy()
b = values_series.to_numpy()[:, None]

(a == b).sum(axis=1)


text:
Q: Migrating from Atlassian Subversion to Assembla With Atlassian discontinuing its hosted Subversion repositories, I have migrated to Assembla's hosted SVN.  Our Jira installation (also cloud based, at Atlassian) still generates automatic links to atlassian SVN when it sees revision tags such as r1501 in the ticket comments.
I would like to reconfigure such that those links point to Assembla rather than Atlassian.  Is there any way to do this?

A: I learned that there is no direct integration available from Assembla to Jira on-demand. Assembla has their own ticket-management system.  Oh well!


text:
Q: Coordinates of an n-sphere I'm a little embarrassed to ask this question because it should be easy but it's stumped me for over a week now. The answer will determine how I write some code, so it matters.
According to Wikipedia the coordinates of an n-sphere in $n$ coordinates is given as
\begin{align}
x_1 &= r \cos(\phi_1) \\
x_2 &= r \sin(\phi_1) \cos(\phi_2) \\
x_3 &= r \sin(\phi_1) \sin(\phi_2) \cos(\phi_3) \\
    &\vdots\\
x_{n-1} &= r \sin(\phi_1) \cdots \sin(\phi_{n-2}) \cos(\phi_{n-1}) \\
x_n &= r \sin(\phi_1) \cdots \sin(\phi_{n-2}) \sin(\phi_{n-1}) \,.
\end{align}
By this formula, the coordinates of an n-sphere in 4 coordinates should be
\begin{align}
x_1 &= r \cos(\phi_1) \\
x_2 &= r \sin(\phi_1) \cos(\phi_2) \\
x_3 &= r \sin(\phi_1) \sin(\phi_2) \cos(\phi_3) \\
x_4 &= r \sin(\phi_1) \sin(\phi_2) \sin(\phi_3)
\end{align}
Whereas mathworld.wolfram.com gives coordinates as (allowing for a change of notation and ordering)
\begin{align}
x_1 &= r \cos(\phi_1) \\
x_2 &= r \sin(\phi_1) \cos(\phi_2) \\
x_3 &= r \sin(\phi_1) \sin(\phi_2) \sin(\phi_3) \\
x_4 &= r \sin(\phi_1) \sin(\phi_2) \cos(\phi_3)
\end{align}
Which is correct? Note that $x_3$ and $x_4$ are swapped in my version and wolfram's.


text:
Q: Noun for a "dual side product" I want to express a concept about source code.
Coding style of the code is like a product for developer, especially on open sourced product. If the style is well established and maintained, developers consider it a good product and vice versa.
But the code is a product for the machine, too. So no matter the coding style, as long as the logic is correct, the result of execution is the same.
How can I express a kind of product that is good in both respects, in one special word?


text:
Q: Collapsable Table with Sortable, Moving 2 Rows at Once? I'm trying to mix two jquery events together and am having a hard time getting it to work correctly. I am using JQuery UI's sortable function, to allow drag and dropping of table rows... and using a Jquery collapsible menu. Basically when you click the parent row, a child opens underneath it.
I need to be able to drag the parent, and have the child row follow along. Clicking the parent should have the child appear below the parent. Currently the child is left behind and expands where the parent used to be.
Also the child should not be able to be sortable.
I have a JSFiddle showing this working here: http://jsfiddle.net/u7cfZ/
Here is the HTML:

1

1.1

2

2.1

3

3.1

4

4.1

5

5.1

Here is the JQuery:
$('tr.parent')
    .css("cursor","pointer")
    .attr("title","Click to expand/collapse")
    .click(function(){
        $(this).siblings('.child-'+this.id).toggle();
        $('tr[class^=child-]').not('.child-'+this.id).hide();
});

$('tr[class^=child-]').hide().children('td');

$('table tbody').sortable({
    helper: function(e, ui) {
        ui.children().each(function() {
            $(this).width($(this).width());
        });
        return ui;
    },
    cursor: 'move',
    update: function (event, ui) {
        var data = $(this).sortable('serialize');
        $.ajax({
            data: data,
            type: 'POST',
            url: 'URL_HERE'
        });
    }
}).disableSelection();

I'm trying to keep is clean, and since the tables will contain data.. I'm trying to maintain using HTML tables vs DIV / UL / LI.
Can anyone help come up with a solution that moves the child along with the parent?

A: I was able to come up with a solution. The answer seems to be to add a function to sortable that is triggered upon 'start' and 'stop'. The code I am using is this:
start: function(event, ui) {
    ui.item.startPos = ui.item.index();
},
stop: function(event, ui) {
    if(ui.item.startPos < ui.item.index()){
        var child = $('.child-' + ui.item.context.id).remove().clone();
        $('#' + ui.item.context.id).after(child);
        var child = $('.'+$('.child-' + ui.item.context.id).next().attr('class')).remove().clone();
        $('#' + ui.item.context.id).before(child);
    }else{
        var child = $('.child-' + ui.item.context.id).remove().clone();
        $('#' + ui.item.context.id).after(child);
    }
},

The child row is copied into a variable and then removed. It is placed into the code after the parent row.
There is a jsfiddle showing this in action: http://jsfiddle.net/u7cfZ/14/
There was a bug that caused the row to cut off a different child row when moving down, so there are two separate functions that are triggered depending on which direction the move is going.


text:
Q: Can you use MBR with UEFI - a question about the UEFI specification I am reading through the UEFI standard: https://uefi.org/sites/default/files/resources/UEFI_Spec_2_9_2021_03_18.pdf
On page 115 section 5 it discusses the GPT disk layout. I'm a bit confused as to exactly how this works. From the below it sounds like UEFI will ignore the MBR.

A legacy MBR may be located at LBA 0 (i.e., the first logical block)
of the disk if it is not using the GPT disk layout (i.e., if it is
using the MBR disk layout). The boot code on the MBR is not executed
by UEFI firmware.

So is this basically saying if you put the firmware in legacy boot mode, this is how to define an MBR which will play nicely with that legacy boot mode? Am I correct in saying that if the system's firmware were in UEFI mode then a system with an MBR defined as specified in chapter 5 would not be bootable?

A:
So is this basically saying if you put the firmware in legacy boot mode, this is how to define an MBR which will play nicely with that legacy boot mode?

Yes, it's possible to have a disk that's boot table in both BIOS and UEFI mode. Many tools to create a bootable USB stick can do that

Am I correct in saying that if the system's firmware were in UEFI mode then a system with an MBR defined as specified in chapter 5 would not be bootable?

No, that part of the spec only says The boot code on the MBR is not executed by UEFI firmware which means the the 446-byte region in the MBR containing the binary instructions for booting the system won't be run in UEFI mode
It's still possible to boot from an MBR disk in UEFI mode if you create a proper ESP (EFI System Partition) on it. UEFI systems only boot executable images in the ESP
So by putting a proper BIOS boot loader in the MBR and a UEFI boot loader in the ESP you can have a disk that boots in either mode


text:
Q: Casting partial dates in Postgresql I have a dataset that contains a birthdate attribute. The date format is M/D/YYYY(single digit representation such as 5/8/2009) and stored in text format. Now, I need to change the column type to date. But, there are many entities (more than that can be fixed manually) that have partial dates - that is, either day or both day and month are missing. For example:
"//1935"
"/5/1929"
"/4/1931"

Now, when I apply to_date(birthdate,'DD/MM/YYYY') I get error because Postgresql cannot parse these dates. What I need to do, is to fill in the missing values with a default value. For instance, "//1935" and "/5/1929" should be converted to "1/1/1935" and "1/5/1929" respectively. Is there a quick way of fixing this problem? Or, do I need to write a regular expression parser?

A: SQL Fiddle Demo
CREATE TABLE product
    ("inputDate" varchar(9))
;

INSERT INTO product
    ("inputDate")
VALUES
    ('//1935'),
    ('/5/1929'),
    ('/4/1931')
;

SELECT *,
       CASE WHEN substr("inputDate", 1, 2) = '//' THEN '1/1/' || substr("inputDate", 3, 10)
            WHEN substr("inputDate", 1, 1) = '/' THEN '1/' || substr("inputDate", 2, 10)
            ELSE "inputDate"
       END as result
FROM Product;


text:
Q: Writing and saving a dataframe into a CSV file throws an error in Pyspark I have pyspark initiated in the local mode with the aim of learning. Everything almost going well until I tried to write and save a dataframe into a CSV file using this code:
out_path = "data/sparkify_log_small.csv"
user_log.write.save(out_path, format="csv", header=True)

It gives me this error meanwhile creating an empty folder with the name of the CSV file without writing the file itself, and I have been poking around to find a solution to it without any clue:
---------------------------------------------------------------------------
Py4JJavaError                             Traceback (most recent call last)
<ipython-input-18-960f808bce3b> in <module>
----> 1 user_log.write.save(out_path, format="csv", header=True)

C:\spark\spark-2.4.7-bin-hadoop2.7\python\pyspark\sql\readwriter.py in save(self, path, format, mode, partitionBy, **options)
    737             self._jwrite.save()
    738         else:
--> 739             self._jwrite.save(path)
    740
    741     @since(1.4)

C:\spark\spark-2.4.7-bin-hadoop2.7\python\lib\py4j-0.10.7-src.zip\py4j\java_gateway.py in __call__(self, *args)
   1255         answer = self.gateway_client.send_command(command)
   1256         return_value = get_return_value(
-> 1257             answer, self.gateway_client, self.target_id, self.name)
   1258
   1259         for temp_arg in temp_args:

C:\spark\spark-2.4.7-bin-hadoop2.7\python\pyspark\sql\utils.py in deco(*a, **kw)
     61     def deco(*a, **kw):
     62         try:
---> 63             return f(*a, **kw)
     64         except py4j.protocol.Py4JJavaError as e:
     65             s = e.java_exception.toString()

C:\spark\spark-2.4.7-bin-hadoop2.7\python\lib\py4j-0.10.7-src.zip\py4j\protocol.py in get_return_value(answer, gateway_client, target_id, name)
    326                 raise Py4JJavaError(
    327                     "An error occurred while calling {0}{1}{2}.\n".
--> 328                     format(target_id, ".", name), value)
    329             else:
    330                 raise Py4JError(

Py4JJavaError: An error occurred while calling o195.save.
: org.apache.spark.SparkException: Job aborted.
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:198)
    at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelationCommand.run(InsertIntoHadoopFsRelationCommand.scala:159)
    at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult$lzycompute(commands.scala:104)
    at org.apache.spark.sql.execution.command.DataWritingCommandExec.sideEffectResult(commands.scala:102)
    at org.apache.spark.sql.execution.command.DataWritingCommandExec.doExecute(commands.scala:122)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:131)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:83)
    at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:81)
    at org.apache.spark.sql.DataFrameWriter$$anonfun$runCommand$1.apply(DataFrameWriter.scala:696)
    at org.apache.spark.sql.DataFrameWriter$$anonfun$runCommand$1.apply(DataFrameWriter.scala:696)
    at org.apache.spark.sql.execution.SQLExecution$$anonfun$withNewExecutionId$1.apply(SQLExecution.scala:80)
    at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:127)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:75)
    at org.apache.spark.sql.DataFrameWriter.runCommand(DataFrameWriter.scala:696)
    at org.apache.spark.sql.DataFrameWriter.saveToV1Source(DataFrameWriter.scala:305)
    at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:291)
    at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:249)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 7.0 failed 1 times, most recent failure: Lost task 0.0 in stage 7.0 (TID 11, localhost, executor driver): java.io.IOException: (null) entry in command string: null chmod 0644 F:\BOOKS\Data Analytics\Data Engineering Nanodegree\4. Data Lakes with Spark\Lesson 2 - Data Wrangling with Spark\Data and Exercises\data\sparkify_log_small.csv\_temporary\0\_temporary\attempt_20201002001955_0007_m_000000_11\part-00000-33b03dc3-af9a-4343-81cb-d97c53f31fd2-c000.csv
    at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:770)
    at org.apache.hadoop.util.Shell.execCommand(Shell.java:866)
    at org.apache.hadoop.util.Shell.execCommand(Shell.java:849)
    at org.apache.hadoop.fs.RawLocalFileSystem.setPermission(RawLocalFileSystem.java:733)
    at org.apache.hadoop.fs.RawLocalFileSystem$LocalFSFileOutputStream.<init>(RawLocalFileSystem.java:225)
    at org.apache.hadoop.fs.RawLocalFileSystem$LocalFSFileOutputStream.<init>(RawLocalFileSystem.java:209)
    at org.apache.hadoop.fs.RawLocalFileSystem.createOutputStreamWithMode(RawLocalFileSystem.java:307)
    at org.apache.hadoop.fs.RawLocalFileSystem.create(RawLocalFileSystem.java:296)
    at org.apache.hadoop.fs.RawLocalFileSystem.create(RawLocalFileSystem.java:328)
    at org.apache.hadoop.fs.ChecksumFileSystem$ChecksumFSOutputSummer.<init>(ChecksumFileSystem.java:398)
    at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:461)
    at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:440)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:911)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:892)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:789)
    at org.apache.spark.sql.execution.datasources.CodecStreams$.createOutputStream(CodecStreams.scala:81)
    at org.apache.spark.sql.execution.datasources.CodecStreams$.createOutputStreamWriter(CodecStreams.scala:92)
    at org.apache.spark.sql.execution.datasources.csv.CsvOutputWriter.<init>(CSVFileFormat.scala:177)
    at org.apache.spark.sql.execution.datasources.csv.CSVFileFormat$$anon$1.newInstance(CSVFileFormat.scala:85)
    at org.apache.spark.sql.execution.datasources.SingleDirectoryDataWriter.newOutputWriter(FileFormatDataWriter.scala:120)
    at org.apache.spark.sql.execution.datasources.SingleDirectoryDataWriter.<init>(FileFormatDataWriter.scala:108)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.org$apache$spark$sql$execution$datasources$FileFormatWriter$$executeTask(FileFormatWriter.scala:236)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1.apply(FileFormatWriter.scala:170)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1.apply(FileFormatWriter.scala:169)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:123)
    at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:408)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1925)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1913)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1912)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1912)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:948)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:948)
    at scala.Option.foreach(Option.scala:257)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:948)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:2146)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2095)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2084)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:49)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:759)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2061)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.write(FileFormatWriter.scala:167)
    ... 32 more
Caused by: java.io.IOException: (null) entry in command string: null chmod 0644 F:\BOOKS\Data Analytics\Data Engineering Nanodegree\4. Data Lakes with Spark\Lesson 2 - Data Wrangling with Spark\Data and Exercises\data\sparkify_log_small.csv\_temporary\0\_temporary\attempt_20201002001955_0007_m_000000_11\part-00000-33b03dc3-af9a-4343-81cb-d97c53f31fd2-c000.csv
    at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:770)
    at org.apache.hadoop.util.Shell.execCommand(Shell.java:866)
    at org.apache.hadoop.util.Shell.execCommand(Shell.java:849)
    at org.apache.hadoop.fs.RawLocalFileSystem.setPermission(RawLocalFileSystem.java:733)
    at org.apache.hadoop.fs.RawLocalFileSystem$LocalFSFileOutputStream.<init>(RawLocalFileSystem.java:225)
    at org.apache.hadoop.fs.RawLocalFileSystem$LocalFSFileOutputStream.<init>(RawLocalFileSystem.java:209)
    at org.apache.hadoop.fs.RawLocalFileSystem.createOutputStreamWithMode(RawLocalFileSystem.java:307)
    at org.apache.hadoop.fs.RawLocalFileSystem.create(RawLocalFileSystem.java:296)
    at org.apache.hadoop.fs.RawLocalFileSystem.create(RawLocalFileSystem.java:328)
    at org.apache.hadoop.fs.ChecksumFileSystem$ChecksumFSOutputSummer.<init>(ChecksumFileSystem.java:398)
    at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:461)
    at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:440)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:911)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:892)
    at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:789)
    at org.apache.spark.sql.execution.datasources.CodecStreams$.createOutputStream(CodecStreams.scala:81)
    at org.apache.spark.sql.execution.datasources.CodecStreams$.createOutputStreamWriter(CodecStreams.scala:92)
    at org.apache.spark.sql.execution.datasources.csv.CsvOutputWriter.<init>(CSVFileFormat.scala:177)
    at org.apache.spark.sql.execution.datasources.csv.CSVFileFormat$$anon$1.newInstance(CSVFileFormat.scala:85)
    at org.apache.spark.sql.execution.datasources.SingleDirectoryDataWriter.newOutputWriter(FileFormatDataWriter.scala:120)
    at org.apache.spark.sql.execution.datasources.SingleDirectoryDataWriter.<init>(FileFormatDataWriter.scala:108)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$.org$apache$spark$sql$execution$datasources$FileFormatWriter$$executeTask(FileFormatWriter.scala:236)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1.apply(FileFormatWriter.scala:170)
    at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1.apply(FileFormatWriter.scala:169)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:123)
    at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:408)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    ... 1 more

A: I was with the same error. But, I found a topic and solve my problem. In my case, I made the download of winutils of the correct version in site: https://github.com/cdarlint/winutils in the folder bin I downloaded the hadoop.dll and put in the same path of winutils.exe For example "C:\Spark\spark-3.2.1-bin-hadoop3.2\bin"

A: In spark you cannot name a file, therefore if you want a single csv file you would do it like this, and then rename it if you'd like.
out_path = "data/"
user_log.repartition(1).write.option("header", "true").csv(out_path, mode = 'append')

A: The correct solution requires a combination of answers given on this site.

*

*You require hadoop.dll from the site, where
winutils was downloaded.

*The save function accepts a path, and not a
.csv file, as many have thought of.
The real story is, it is going to write a hdfs
file as output, and needs a path.
If we dig into the code, we could deduce the
save method signature as:
df.write.save(dir_path, "csv", "append")
where dir_path is any Windows path.
Of course, there are many more options, but
this worked on spark-3.1.2-bin-hadoop3.2,
running on an old Windows 7 laptop.
The output file produced looks like:
part-00000-4e8efdcb-60e3-483a-b165-
9d1a67394a0c-c000.csv


text:
Q: pyspark: Sort a PyhonRDD using the object attribute I have a result RDD, which is created using pyspark.mllib.fpm
The result RDD looks like:
print(result)
result.take(5)

PythonRDD[32] at RDD at PythonRDD.scala:48
Out[18]:
[FreqSequence(sequence=[['John']], freq=18980),
 FreqSequence(sequence=[['Mary']], freq=106),
 FreqSequence(sequence=[['John-Mary']], freq=381),
 FreqSequence(sequence=[['John-Ann']], freq=158),
 FreqSequence(sequence=[['Ann']], freq=433)]

How do I sort the above result RDD based on the freq attribute? Thanks!

A: You can use keyfunc argument:
rdd.sortBy(lambda x: x.frequency)

A: You can use keyfunc argument:
rdd.sortBy(lambda x: x.freq)


text:
Q: plot horizontal line in all subplots I;m working in python and found a couple solutions to do this. But it requires creating each individual subplot. But since there's a parameter where you could do subplot=True, I'm wondering is there a way to to do it in one line of code...much how you could say sharey=True, can you make it "share" a horizontal constant?
I've been playing around with it. At first, it was only showing up on the last graph, but now it's not showing at all.
import matplotlib.pyplot as plt

line_up_points.plot(subplots=True, layout=(3, 3),sharey=True, figsize=(18, 12))
plt.legend(loc='best')
plt.axhline(y=125.08, color='r')

Here's what it's showing:

But I would like to have a horizontal line on each of those subplots at y=125.08
Any idea without individually creating 7 different graphs?

A: If I'm not mistaken then you should get back a matrix of axis objects.
This should do the trick:
axes = line_up_points.plot(subplots=True, layout=(3, 3),sharey=True, figsize=(18, 12))

for c in axes:
   for ax in c:
      ax.axhline(y=125.08, color='r')

Here's a full example:
%matplotlib inline  # For Jupyter Notebooks
import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.rand(10, 7))

axes = df.plot(subplots=True, layout=(3, 3), figsize=(16,9))

for c in axes:
    for ax in c:
        ax.axhline(y=0.5, color='r')


text:
Q: Why is the assert not getting imported here I have the following unit test case.
import unittest
from webPageTestUtils import WebPageTestProcessor

class webPageUtilsTest(unittest.TestCase):

    def setUp(self):
        self.webPageTestProcessor = WebPageTestProcessor()

    def test_submitTest(self):
        url = None;
        assertEqual(self.webPageTestProcessor.submitTest(url),None)

if __name__ == '__main__':
    unittest.main()

Upon execution I get an error saying.
NameError: global name 'assertEqual' is not defined
I have subclassed unittest.TestCase , then why is python not recognizing assert

A: It's a method on self:
self.assertEqual(self.webPageTestProcessor.submitTest(url), None)


text:
Q: how to capture httpresponse in custom field I have written this code. I want to store response in response sms history field of sms history obj.here is code.
String body= '[{"from_number":"+14145337913","messages": [{"text":  "'+message+'","to_number": "'+phonenumber+'"}]}]';
        Blob headerValue = Blob.valueOf(username + ':' + password);
        String authorizationHeader = 'Basic ' +  EncodingUtil.base64Encode(headerValue);
             req.setHeader('Authorization', authorizationHeader);
             req.setHeader('Content-Type','application/json');
             HTTPResponse res= new HTTPResponse();
             req.setBody(body);
             system.debug(req.getBody());
             Http http = new Http();
             res = http.send(req);
             **response=res;**
        SMS_History__c SMSHistory = new SMS_History__c();
        if(res.getstatuscode()==200)
        {
                //system.debug('Authentication success@@@@@@@'+ res);
                SMSHistory.Name = SMSHistory.Name+' Succeeded';
                SMSHistory.Status__c = 'SMS Sent Successfully';

        }

but it showing error "Illegal assignment from System.HttpResponse to String"
when I used
string response=res;

Any help will be appriciated

A: You do need to do this like
SMSHistory.response__c = res.getBody();
SMSHistory.Name = SMSHistory.Name+' Succeeded';
SMSHistory.Status__c = 'SMS Sent Successfully';

or
string response=res.getBody();

Where response__c is the custom field API name(which you can change).


text:
Q: Operator does not exist: character varying = record in Postgres I am trying to execute query in community edition version of postgres:
select COUNT(*)
from cdar_cpms_owner.hshldgrp_wkly_actvty
where wkly_actvty_cd  IN (('B','H') ,'N')

From that query, I get this error:

ERROR:  operator does not exist: character varying = record
LINE 1: ..._owner.hshldgrp_wkly_actvty where wkly_actvty_cd  IN(('B','H...
                                                                  ^
  HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.

While the same query is working fine with the EDB version of postgres.
Can anyone please suggest what changes are required in this query to make it work?

A: Here:
where wkly_actvty_cd IN ( ('B','H'),'N')

Your list has a nested list element: ('B','H'). So Postgres ends up trying to compare a scalar value (wkly_actvty_cd) to a tuple, which raises the error that you are getting.
Did you actually mean?
where wkly_actvty_cd IN ('B', 'H', 'N')


text:
Q: Deleting Record violates foreign key constraint I have a table for notifications, which stores the ID from several Models, so a user gets a notification upon actions related to those (someone posted a comment on your article). The notifications do not "belong to" anything but a user it's going to, though, it's just referencing the IDs of things. So now whenever I try to delete an article, for example, I get an error:
ActiveRecord::InvalidForeignKey (PG::ForeignKeyViolation: ERROR:  update or delete on table "comments" violates foreign key constraint "fk_rails_9268535f02" on table "notifications"

How can I set it up to delete any referenced notifications also?
My db schema for notifications:
create_table "notifications", force: :cascade do |t|
t.integer  "recipient_id"
t.integer  "notified_by_id"
t.integer  "glip_id"
t.integer  "article_id"
t.integer  "group_id"
t.integer  "post_id"
t.integer  "comment_id"
t.integer  "notation_id"
t.integer  "response_id"
t.integer  "remark_id"
t.integer  "conversation_id"
t.integer  "message_id"
t.boolean  "read",              default: false
t.datetime "created_at",                        null: false
t.datetime "updated_at",                        null: false
t.integer  "notification_type"
t.index ["article_id"], name: "index_notifications_on_article_id"
t.index ["comment_id"], name: "index_notifications_on_comment_id"
t.index ["conversation_id"], name: "index_notifications_on_conversation_id"
t.index ["glip_id"], name: "index_notifications_on_glip_id"
t.index ["group_id"], name: "index_notifications_on_group_id"
t.index ["message_id"], name: "index_notifications_on_message_id"
t.index ["notation_id"], name: "index_notifications_on_notation_id"
t.index ["notified_by_id"], name: "index_notifications_on_notified_by_id"
t.index ["post_id"], name: "index_notifications_on_post_id"
t.index ["recipient_id"], name: "index_notifications_on_recipient_id"
t.index ["remark_id"], name: "index_notifications_on_remark_id"
t.index ["response_id"], name: "index_notifications_on_response_id"

end
And my notifications Model:
class Notification < ApplicationRecord
  enum notification_type: { comment: 0, notation: 1, message: 2, feature: 3, marked_helpful: 4,
                            participation: 5, response: 6, remark: 7, follow: 8, unfollow: 9 }
  enum read: { read: true, unread: false }
  belongs_to :notified_by, class_name: 'User'
end

A: Your User should use the :dependent option:
class User < ApplicationRecord
  # ...
  has_many :notifications, foreign_key: :notified_by_id, dependent: :destroy
end

The :foreign_key should also be specified if you used :class_name on the belongs_to side of the association.
Now, when you delete a User, all of the notifications referencing them are also deleted.
You can repeat the same process for the Article or any other model referenced.

A: It may be due to while an article is deleted the associated comments are being deleted together and there is a foreign key constraint between comments and notifications tables at db level which prevents it from deletion.
My suggestion is to add dependent: :destroy in Comment model if you want that associated notifications to be deleted along with comments
class Comment < ApplicationRecord
  has_many :notifications, dependent: destroy
end

If you want to notifications not to be deleted while deleting comments
class Comment < ApplicationRecord
  has_many :notifications, dependent: :nullify
end

For more details please have a look
Difference between dependet :destroy & dependent: :nullify


text:
Q: Can an amenable group have a weak mixing unitary representation without almost invariant vectors? Does there exist a finitely generated discrete amenable group $G$ that acts on a separable Hilbert space $\mathcal{H}$ by unitary transformations, and where (1) $\mathcal{H}$ has no finite dimensional $G$-invariant closed subspaces and (2) there does not exist a sequence $(v_n)_n$ of unit vectors in $\mathcal{H}$ such that $\lim_n \|g.v_n - v_n\|=0$ for all $g \in G$?
This is impossible if $\mathcal{H}$ is $L^2$ of an invariant probability measure.

A: If $G$ is amenable, then every weakly mixing representation $\pi$ has almost invariant finite-dimensional subspaces. This means that $\pi \otimes \bar \pi$ has almost invariant vectors.
Results like this can be found in
M.E.B. Bekka. Amenable unitary representations of locally compact groups. Invent. Math. 100 (1990), 383–401.
A concrete example of a weakly mixing representation without almost invariant vectors would be given by the Heisenberg group $H(\mathbb Z)$ acting on $\ell^2(\mathbb Z^2)$ with generator of the center acting by multiplication with some irrational $\theta \in S^1$. It is easy to see that there are no finite-dimensional subrepresentations and since the generator of the center acts by $\theta$ (and not by $1$), there cannot be any almost invariant vectors.


text:
Q: Google Maps URL Tile Server API and Documentation? I would like to use Google Maps tiles for maps inside of my Wolfram Language projects.  There are currently 18 Google Maps APIs and I think I need the Static Maps API.  However, this API appears to return whole maps instead of individual tiles.
Which API do I need for use as a URL tile server for the GeoServer option in the Wolfram Language Maps & Cartography functions?  Also, where is there official documentation of the URL tile server in Google's documentation?
Update
From @ChrisDegnen answer below I think the Static Map API is the only option.  However. I wanted to use the map as a background to the existing Maps & Cartography functions in the Wolfram Language.  Unfortunately, the Static Map API does not allow explicit specification of the lat-long boundaries so it is not a good fit.
For example to map the continental USA using the "visible" parameter to set the map bounds.
visible =
 StringReplace["\n" -> "|"]@
  ExportString[
   Flatten[Outer[List, Sequence @@ GeoBounds[Entity["Country", "UnitedStates"]]], 1],
   "CSV"]

"25.1246466,-124.733151|25.1246466,-66.949806|49.3844900814454,-124.733151|49.3844900814454,-66.949806|"

The Static Map API returns this map (my personal key having been removed).
URLExecute["http://maps.googleapis.com/maps/api/staticmap",
 {
  "size" -> "600x300",
  "visible" -> visible,
  "key"-> "mykey"
  }
 ]

The Static Map API adds far too much padding when compared to the default GeoGraphics map.
GeoGraphics[{Entity["Country", "UnitedStates"]},
 ImageSize -> {600, 300}]

This extra padding will throw off anything I add to the map in my code.  So in the end I can't use the Google maps.

A: The Mathematica documentation demonstrates use of the Static Maps API, if that's any help.
https://www.wolfram.com/mathematica/new-in-10/url-manipulation/call-urls-like-functions.html
URLExecute[
 "http://maps.googleapis.com/maps/api/staticmap",
 {"center" -> "Brooklyn Bridge,New York,NY",
  "zoom" -> "13", "size" -> "600x300"}, "Method" -> "GET"]


text:
Q: How to extend bash-completion with the already exist completion in another file? For example, there is bash-completion for rar on linux, I want to extend, make more completions for the same command - rar, maybe for my own filename extension, but I don't want to touch the already existing completion script, how to start it?
Thanks!

A: The base support is usally in /etc/bash_completion and details in the directory /etc/bash_completion.d
For more information, see:
An introduction to bash completion: part 1 for general knowledge
An introduction to bash completion: part 2 for details on scripts in /etc/bash_completion.d


text:
Q: Good Partition for Postgresql Server I'm setting up a dedicated postgresql server on ubuntu, using 500GB RAID 1. I'm wondering if someone might share a simple, yet effective partitioning schema that I can use, since I'm pretty new to all this.

A: You won't get much performance benefit from partitioning with a single big RAID (though you will avoid major headaches from / filling up).
Generally I would just use the OS defaults unless you're really comfortable sizing things yourself and just make sure you have a good sized chunk of space where you intend to create the PGDATA directory.  The OS partitioning suggestions below are what I use on FreeBSD systems, it's probably OK for Ubuntu too.
 /                    1GB (or larger)
 [SWAP]               2GB or 2*RAM Size
 /var                 10GB
 /usr                 10GB
 /usr/local           15GB
 /tmp                 2GB
 /home                10GB ("Big enough for home directories")
 -------------------------------------------------------------
 (OS Total)           50 GB
 [PGDATA]             Postgres data directory ("The rest")

(Ubuntu may not make use of /usr/local, if not you can fold some of that into /usr)

Re: Postgres-specific partitioning, if you're doing this on a single RAID-1 just make [PGDATA] big enough to hold your DB and transaction logs, plus some growth room.
If this is a production box and you're expecting a lot of DB activity what you want to do is separate this out onto a bunch of RAID-1s to separate disk activity (super-high-volume you may even consider splitting it across controllers).
Oracle has lots of great whitepapers on this and I highly recommend stealing their designs: They aren't simple, but they are effective. The partitioning scheme I use (each on their own pair of disks) is:
[PGDATA]               5-10GB
[PGDATA]/pg_xlog       5-10GB (More if you expect lots of transaction logs)
[PGDATA]/base          Big enough for your database
[PGDATA]/[Tablespace]  Optional - Separate out "high-traffic" table spaces
[PGDATA]/xlog_archive  Big enough for archived transaction logs & dumps

A: I've a postgresql server with some interesting activity between 600-1000 transactions per second and my partitioning is something like this:
/      - 10GB
swap   - 15GB (I have 8GB RAM)
/var   - 20GB
/home  - 60GB (don't ask why, but I think 60gb is too much for home)
pgdata - 100 GB

According with your data, would be interesting if you dive into table partitioning, to avoid scanning a huge table in the case you need a small part of data. For example, I use partitioned tables to store logs so I have a master table called logs and monthly tables called YYYYMM_logs inherited from the master. Then I use a trigger function to put each log on the corresponding partitioned table.


text:
Q: MacOS Safari and Chrome have WebGL display issue Have a look at the attached image

*

*the Safari browser with macOS High Sierra Version 10.13.

Also there is a video
https://share.vidyard.com/watch/AZyZGJJ4tJvAQDCYiUQD6W with a closed issue. It is this plugin http://3dflipbook.net . Generally the plugin works well. This problem was not met on other OS: Windows, Android or iOS. Does anyone has any ideas what is wrong?
Best regards,
Ivan.
[1]:

A: I'm also experiencing this bug, only happens in safari on high sierra.  Have you logged an issue with WebKit?  I was about to do the same thing.

A: Can confirm that WebGL in Chrome is broken in Mac OSX High Sierra. I'm on a 2011 MacBook Pro.
Same machine, Firefox Quantum can play WebGL however
Testing using https://get.webgl.org
Most odd

A: This bug happens because we disabled anti aliasing for the webgl context.  If you turn it back on the issue goes away.  Probably not the answer you want if like us you're doing it in the shaders instead.  The guys from webkit have already fixed the issue their end and its fixed in the latest technical preview of safari so just waiting for it to get to the release build

A: One of my customers confirmed, using antialiasing resolves the issue. So create render in this way:
var renderer = new THREE.WebGLRenderer({ antialias: true});


text:
Q: Infragistics Hierarchical databind in web application Hi We have to bind the data in web infragistics hiergrical control. so we need some code snipet

A: You need to instantiate 2 or more data sources and then add relationships and add the primary datasource to the WebGrid:
                dataset.Relations.Add("Flags", this.dataset.Tables[0].Columns["ParticipantID"], this.dsParticipants.Tables[1].Columns["ParticipantID"]);
            this.uwgParticipants.DataSource = ds.Table[0];
            Session["data"] = ds.Table[0];
            this.uwgParticipants.DataBind();


text:
Q: PyQt4/Qt: Set orientation of QDial (minimum value at the top) I'm using PyQt4 with Python 2.7 on Windows and for a music player, I decided to replace Phonon.SeekSlider with a QDial.
My problem is, that the minimum value of a QDial is always at the bottom of the dial, but I want it to be at the top (value still increasing clockwise). I tried setInvertedAppearance() and setInvertedControls(), but that just flips the dial horizontally and setOrientation() didn't help either.
My Question: Is there some way to either specify an angle to position the minimum value on the dial or flip the whole dial vertically?

A: I don't believe there is a way to do this directly. However, you can place the QDial in a QGraphicsView, and rotate it as an item in the scene. Something like this should work:
import sys
from PyQt4 import QtGui, QtCore

class RotatableView(QtGui.QGraphicsView):
    def __init__(self, item, rotation=0):
        QtGui.QGraphicsView.__init__(self)
        scene = QtGui.QGraphicsScene(self)
        self.setScene(scene)
        graphics_item = scene.addWidget(item)
        graphics_item.rotate(rotation)

        # make the QGraphicsView invisible
        self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.setFixedHeight(item.height())
        self.setFixedWidth(item.width())
        self.setStyleSheet("border: 0px")

class DialExample(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        dial = QtGui.QDial()
        dial.setNotchesVisible(True)
        label = QtGui.QLabel('0')
        dial.valueChanged.connect(label.setNum)

        layout = QtGui.QVBoxLayout()
        layout.addWidget(RotatableView(dial, 180))
        layout.addWidget(label)
        self.setLayout(layout)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    dialexample = DialExample()
    dialexample.show()
    sys.exit(app.exec_())

A: Hackyday give a QgraphicsView answer, here I give you a pyqt solution without using QgraphicsView.
You can do it directly on python with a little if/else statement.
You create your qDial, I suppose that you want a dial as a compass (0 - 360°) and I suppose you wrote the output of qDial on a qSpinBox):
<widget class="QDial" name="dial">
 <property name="geometry">
  <rect>
   <x>20</x>
   <y>150</y>
   <width>101</width>
   <height>111</height>
  </rect>
 </property>
 <property name="mouseTracking">
  <bool>false</bool>
 </property>
 <property name="acceptDrops">
  <bool>false</bool>
 </property>
 <property name="layoutDirection">
  <enum>Qt::LeftToRight</enum>
 </property>
 <property name="minimum">
  <number>0</number>
 </property>
 <property name="maximum">
  <number>360</number>
 </property>
 <property name="singleStep">
  <number>0</number>
 </property>
 <property name="pageStep">
  <number>0</number>
 </property>
 <property name="value">
  <number>135</number>
 </property>
 <property name="sliderPosition">
  <number>135</number>
 </property>
 <property name="orientation">
  <enum>Qt::Horizontal</enum>
 </property>
 <property name="invertedAppearance">
  <bool>false</bool>
 </property>
 <property name="invertedControls">
  <bool>false</bool>
 </property>
 <property name="wrapping">
  <bool>true</bool>
 </property>
 <property name="notchesVisible">
  <bool>false</bool>
 </property>
</widget>

<widget class="QSpinBox" name="oAzimuth">
 <property name="geometry">
  <rect>
   <x>10</x>
   <y>110</y>
   <width>52</width>
   <height>30</height>
  </rect>
 </property>
 <property name="maximum">
  <number>360</number>
 </property>
 <property name="value">
  <number>315</number>
 </property>
</widget>

If you want to set your default location of slider to 315° so, set it to 135° as in my example. Why ? Because all your degrees between 0° and 180° have to be shift to +180° and the degrees between 181° and 360° to -180°.
So on pyqt, on your file.py, you can write and if/else statement to correct that automatically inside a function:
def Edit_Slider(self):
    if self.dockwidget.spinbox.value() > 180:
         self.dockwidget.dial.setValue(self.dockwidget.spinbox.value()-180)
    else:
         self.dockwidget.dial.setValue(self.dockwidget.spinbox.value()+180)

def Edit_Spinbox(self):
    if self.dockwidget.dial.value() > 180:
         self.dockwidget.spinbox.setValue(self.dockwidget.dial.value()-180)
    else:
         self.dockwidget.spinbox.setValue(self.dockwidget.dial.value()+180)

And to edit this change automatically while you moved your slider or your SpinValue :
self.dockwidget.spinbox.valueChanged.connect(self.Edit_Slider)
self.dockwidget.dial.valueChanged.connect(self.Edit_Spinbox)

A: you also can use qdial value in the linedit.
As the QDial works on Integers only, by using following commands you can use any value in float.
    self.dial_object = QtGui.QDial(self.centralwidget)
self.dial_object.setNotchesVisible(True)
self.dial_object.setGeometry(QtCore.QRect(15,110,45,45))
self.dial_object.setMinimum(50)
this sets dial minimum value to .5
    self.dial_object.setMaximum(100)
this sets dial maximum value to 1
    self.dial_object.setSingleStep(10)
this sets dial resolution value to .01
    self.dial_object.setValue(0)
this sets dial starting value to 0
    self.dial_object.valueChanged.connect(self.dvalue1)
where
    def dvalue1(self):
self.lineEdit_object.setText(str(float(self.dial_object.value())*0.01))
this will change the value into float to string type(used in setText).
0.01 decides the dials resolution.


text:
Q: Detect MIME-type change on image request nodejs I'm using the requests library in NodeJS to pull images from a website, and save them to disk. The website I'm pulling from, instead of 404-ing, redirects to the homepage, and serves the HTML. Is there a proper way of detecting this change/redirect without parsing the body of the response?

A: You can check the Content-Type sent by the server in response.headers['content-type'].


text:
Q: Files disappearing from Amazon S3 Here are links to four files that I uploaded in the last week, but have now disappeared from my bucket on S3:
https://gh-resource.s3.amazonaws.com/ghImage/SWjqzgXy9rGCYvpRF-naypyidaw.jpg
https://gh-resource.s3.amazonaws.com/ghImage/SWjqzgXy9rGCYvpRF-london.jpg
https://gh-resource.s3.amazonaws.com/ghImage/SWjqzgXy9rGCYvpRF-brussels.jpg
https://s3.amazonaws.com/gh-resource/ghImage/SWjqzgXy9rGCYvpRF-ottawa.jpg

I know they successfully uploaded because I saw them on my website multiple times before they disappeared.  The last file above (ottawa), I just now re-uploaded, so that I could look at the permissions and see if there was an expiry date or expiry rule.  When I looked at the permissions, 'everyone' has read/download permission.  Expiry date is None, expiry rule is N/A.  This has been happening regularly for the last year or so.  What could be causing this?

A: You should enable logging on your bucket. This will tell you who/what is deleting your files.
See: Logging Amazon S3 API Calls By Using AWS CloudTrail
I found that if you have an expiry policy setup you'll also see that in the logs. See Lifecycle and Other Bucket Configurations for more info.


text:
Q: Blob to image in browser I am trying to access image which is saved as blob, and the type of column is image which is saved using c# in mssql
While retrieving image is showing correctly using c# code
While accessing using php the image is broken
code which i have tried
 $image = imagecreatefromstring($stationDetail->cstatpic3);
 ob_start();
 imagejpeg($image);
 $data = ob_get_contents();
 ob_end_clean();
  echo '<img src="data:image/jpeg;base64,' .  base64_encode($data)  .     '" />';
 exit;
also from this link

PHP display image BLOB from MySQL


text:
Q: Convert python list to javascript variable I am doing a webapp on Google App Engine.
Now, I have a python list 'bb' of image link, and when I passed it to javascript, I got the error message "Uncaught ReferenceError: bb is not defined".
So far, I have tried the following:

*

*json.dumps(bb) - didn't show any image at all with no error

*array.array('c',bb) - didn't show any image at all with no error

Any help? Thanks.
    <img id="output" src="" height="300" width="500" border="0" alt="image">
     <script>
      function loadImages(imgArr){
              for(var i=0; i< imgArr.length; i++) {
                   document.getElementById('output').src = imgArr[i];
              }
      }
      loadImages(bb);
     </script>

A: Your problem is that your variable bb is only known in python. Hence you need to populate it to the JavaScript.
There is no direct conversion between JavaScript and Python. You will need to provide a URL to a python (web) service which serves a JSON object. This URL will be queried by a (a)synchronous JavaScript call. As a result of this call you get the JSON object in JavaScript. Voila!


text:
Q: Drupal - Add class to menu of number of items it contains? How can I add a class to a menu of the number of items it contains?
My site has a menu that will always have either 7 or 8 items, as one will be regularly be enabled and disabled. I want to style the links slightly differently in either case. If the menu had a class of the number of items being used this would be easy.
Thanks

A: The solution is to override theme_menu_item_link, and add the mlid to the actual link.
Drop this snippet into your template.php file and as per usual, replace themeName with your themes name.
<?php
function themeName_menu_item_link($link) {
  if (empty($link['localized_options'])) {
    $link['localized_options'] = array();
  }
  if (empty($link['localized_options']['attributes']['class'])) {
    $link['localized_options']['attributes']['class'] = 'menu-'. $link['mlid'];
  }
  else {
    $link['localized_options']['attributes']['class'] .= ' menu-'. $link['mlid'];
  }
  return l($link['title'], $link['href'], $link['localized_options']);
}
?>

for reference ee that link
http://adaptivethemes.com/how-to-add-unique-classes-to-drupal-menus
My Reards


text:
Q: NoClassDefFoundError at Runtime on class inside .AAR in Android Studio I've been researching for many hours about a possible solution to this but whatever I try it just fails. Here's the explained situation:
I have this library project on Android Studio which generates the app-debug.aar file.
Then I add this new module in the implementing project, following the wizard to import .JAR/.AARs I pick the .aar and update the dependency for :app in the Project Structure.
Once the project is cleaned (even using ./gradlew clean--Mac OS X) I can make references of this class and its methods in any of the activities.
Now at runtime, once built and installed on the real devices the app will crash throwing the aforementioned Runtime Exception.
Note: I'm importing the .aar because I would need to protect the code and it has resources so a .jar is out of the question. And if I import the library module (with source and all instead of an.aar) then the app has no issues at runtime.
I've tried everything and if anyone can throw some light on what this could be, it'll be highly appreciated.
The class extends ViewGroup and is instantiated at runtime in case that implies anything. The code was given to me so major changes might not be possible unless it's absolutely necessary.
Thanks beforehand to all!
Armando

A: For those, who are still looking for the solution, following two options worked for me to solve the exact same problem as OP has mentioned.

*

*Include the (problematic) library dependency in the target module as well, i-e the in my case i was including the protobuf-lite as a dependency to my library module but getting noclassdefFound error when lib imported as .aar in app module. As a workaround, i added the protobuf-lite dependency to my app module too and it worked like charm.

*Second option that worked for me that instead of adding the gradle dependency `compile 'com.google.protobuf:protobuf-lite:3.0.1', i downloaded the protobuf-jar from maven and added manually to the libs of my library module, and the problem got solved.
Don't know what's wrong with the gradle plugin, but hope it helps someone else looking for the same problem.

A: The NoClassDefFound error has actually happening to a backward-compatibility library being used by this class I mentioned on the question ("Class A"). No details were given other than Class A couldn't be found and later on found out that another class had a similar issue BUT was pointing at that compat lib with the same exception and I noticed that Class A was also calling its methods and implementing its callbacks. By bumping up the min version (to use the native API) I could overcome that issue. It was indeed a problem of including that backward-comp library in the .aar or so it seems. Should I understand this issue a lot better I'll update this "answer."


text:
Q: Could not find property 'GROUP' on project Name File: build.gradle I'm new to Android Studio so do not know how gradle works. Maybe it is a silly question.
Whenever I tried to import the GitHub project as module in my project and try to build the project, I always get this error:

Could not find property 'GROUP' on project build.gradle

I know Group need to recognize the project name. I tried to find the answer for this question but there is not much reference available, so I am posting the question here.
Recently I tried to import Fresco as module in project and got the same error.
Question is

*

*Why am I getting this error?

*How does the gradle build project?

Here is my build.gradle:
apply plugin: 'com.android.library'
apply plugin: 'maven'

project.group = GROUP
version = VERSION_NAME

dependencies {
    compile "com.android.support:support-v4:${SUPPORT_V4_VERSION}"
    provided "com.google.code.findbugs:jsr305:${JSR_305_VERSION}"
    provided "javax.annotation:javax.annotation-api:${ANNOTATION_API_VERSION}"

    compile project(':fbcore')

    testCompile "junit:junit:${JUNIT_VERSION}"
    testCompile "org.mockito:mockito-core:${MOCKITO_CORE_VERSION}"
    testCompile("org.robolectric:robolectric:${ROBOLECTRIC_VERSION}") {
        exclude group: 'commons-logging', module: 'commons-logging'
        exclude group: 'org.apache.httpcomponents', module: 'httpclient'
    }
}

apply from: rootProject.file('release.gradle')

android {
    buildToolsVersion rootProject.ext.buildToolsVersion
    compileSdkVersion rootProject.ext.compileSdkVersion

    packagingOptions {
        exclude 'NOTICE'
        exclude 'LICENSE'
        exclude 'LICENSE.txt'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
    }
}

task sourcesJar(type: Jar) {
    from android.sourceSets.main.java.srcDirs
    classifier = 'sources'
}
artifacts.add('archives', sourcesJar)

A: Replace GROUP and VERSION_NAME with actual values, for example:
project.group = 'the.group.of.my.module'
version = '1.0'

EDIT: you can write value project.group anything. but it should unique and identify your module name. in my case i wrote   project.group = 'com.facebook.fresco'
Hope it will help future Visitors and save their time.
Credited goes to @Henry


text:
Q: I need a explaining for this short script I have this code :
    function list(target, letters, lvls) {
    var index = 0;
    (function iter(s, lvl) {
        if(lvl++ == lvls)
            return target.appendChild(document.createTextNode(
                ++index + ' - ' + s + '\n'
            ));
        for(var i=0; i<letters.length; ++i)
            iter(s + letters[i], lvl);
    })('', 0);
  }
  list(document.getElementById('output'), 'abc', 3);

But I don't know this type of function syntax.
Can some one explain to me the function behavior and what this code exactly do step by step.
And thanks in advance

A: This seems to be iterating through the string 'abc' and creating as many X letter strings as possible with the combination of all the characters in the string.
So the call is list([element ID to output strings], [string of all possible letters], [size of strings to generate])
So the following example -

will output all possible two letter strings (defined by param 3), using the characters from the input string (param 2) and will result in -
1 - aa 2 - ab 3 - ba 4 - bb
Explanation
Inside the method there is a second called iter with the arguments s and lvls. On
first run, the arguments parsed to the iter method are blank and 0. It hits the for
loop which runs until all of the letters in the string letters have been used up,
each time recursively calling the iter method. Each time it adds the current letter in
the iteration s, along with the next letter in the string letters[i]. Every time it
recursively calls itself it builds up the string until the number of specified levels have
been reached for that particular string and then returns the result, along with the index
value. This is just a numeric value to represent the string count.


text:
Q: CodeIgniter Phil Sturgeon's template library error I'm using a template library from Phil Sturgeon.
I also use modules.
Module blog only works when I add
$this->template->set_theme('nvc');
$this->template->set_layout('theme');

But I don't want that, I want to set that in the core file. How should I fix this?
Module welcome works perfectly
class Welcome extends NVC_Controller {

function index()
{
    $this->template->build('theme');
}
}

But module blog gives an error (template):

Unable to load the requested file: default.php

class Blog extends NVC_Controller {

var $num = 10;

function __construct()
{
    $this->load->model('blog_model', 'blog');
}

function index()
{
    $data["result"] = $this->blog->get_all_posts($this->num);
    $this->template->build('blog', $data);
}

}

core/NVC_Controller.php
class NVC_Controller extends MX_Controller {
function __construct(){
    if(nvc_site_open()){
        $this->template->set_theme('nvc');
        $this->template->set_layout('theme');
    } else {
        show_error("De site is momenteel gesloten.");
    }
}
}

What is going wrong? Setting the config layout to "theme" also doesn't work.
The template is stored in application/themes/nvc/views/layouts/theme.php.

A: A file in your CI installation is trying to call default.php which doesn't exist in the given location. Can you please investigate which file it is and post that code here?


text:
Q: GeoServer OS MasterMap WMS topoarea error SLD I'm getting an error when displaying Ordnance Survey MasterMap data through GeoServer as a WMS in QGIS.
The error is:
<?xml version="1.0" encoding="UTF-8"?>
<ServiceExceptionReport version="1.3.0" xmlns="http://www.opengis.net/ogc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/ogc http://localhost:8080/geoserver/schemas/wms/1.3.0/exceptions_1_3_0.xsd">
    <ServiceException>
  java.lang.RuntimeException: org.xml.sax.SAXException: Entity resolution disallowed for SYSTEM org.xml.sax.SAXException: Entity resolution disallowed for SYSTEM Entity resolution disallowed for SYSTEM
    </ServiceException>
</ServiceExceptionReport>

Exception report:
<xsd:schema targetNamespace="http://www.opengis.net/ogc" elementFormDefault="qualified" version="1.3.0 2010-02-03">
<!--

      WMS is an OGC Standard.
      Copyright (c) 2004,2010 Open Geospatial Consortium, Inc. All Rights Reserved.
      To obtain additional rights of use, visit http://www.opengeospatial.org/legal/ -->

    <xsd:element name="ServiceExceptionReport">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="ServiceException" type="ogc:ServiceExceptionType" minOccurs="0" maxOccurs="unbounded"/>
            </xsd:sequence>
            <xsd:attribute name="version" type="xsd:string" fixed="1.3.0"/>
        </xsd:complexType>
    </xsd:element>
    <xsd:complexType name="ServiceExceptionType">
        <xsd:simpleContent>
            <xsd:extension base="xsd:string">
                <xsd:attribute name="code" type="xsd:string"/>
                <xsd:attribute name="locator" type="xsd:string"/>
            </xsd:extension>
        </xsd:simpleContent>
    </xsd:complexType>
</xsd:schema>

I'm very new at Geoserver and not sure about the error at all. When researching the error a lot of people get SAXParseException but can't find something similar to what I get.
I think it's something to do with the colour hex in the SLD file I'm using, sample below:
 <FeatureTypeStyle>
    <Rule>
      <Name>Unclassified - 1:0 to 1:4,000</Name>
      <ogc:Filter>
        <ogc:PropertyIsEqualTo>
          <ogc:PropertyName>style_code</ogc:PropertyName>
          <ogc:Literal>99</ogc:Literal>
        </ogc:PropertyIsEqualTo>
      </ogc:Filter>
      <MinScaleDenominator>0</MinScaleDenominator>
      <MaxScaleDenominator>4000</MaxScaleDenominator>
      <PolygonSymbolizer>
        <Fill>
          <CssParameter name="fill">#F7F5F0</CssParameter>
        </Fill>
      </PolygonSymbolizer>
    </Rule>
  </FeatureTypeStyle>

A: I found the answer for anyone else using these SLD files.
There were too many  arguments in the xml. Only one is required at the top and bottom of the complete SLD file.


text:
Q: Change decimal to integer in SQL I need to round off decimal value to integer in SQL
Eg : 748.444645 to 749

A: You don't want to round.  You want the ceiling.  In most databases, this would be a function called ceil() or ceiling():
select ceiling(col)

A: for round off decimal value to an integer
you need to use ceiling() function of sql.
for eg: SELECT CEILING(27.445) AS CeilValue;
the answer will be 28
if you want 748 as result use Floor() please check below image I have executed the query.

*

*FLOOR() function returns the largest integer value that is smaller than or equal to a number.

if you want 749 as a result use Ceiling please check the image below

*

*CEILING() function returns the smallest integer value that is larger than or equal to a number.


text:
Q: how to call a number from a url I am making an affiliate program where I count a number of clicks based on this link fridgeblasteraffiliate.freeiz.com/affiliate/?numberherebasedonid but I have this
    <?php
$conn = mysqli_connect("redacted", "redacted", "redacted",
"redacted");
 if (!$conn) {
     die("Connection failed: ".mysqli_connect_error());
 }
 session_start();
  $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
 $sql = "SELECT clicks FROM affiliate WHERE ID='$ID'";
 $add = 1;
 $ID = strpos($url, needle)
 ?>

but as you can see I can't figure out how to call the number in the url to count the clicks

A: You want to use a GET variable. Try the following URL:
fridgeblasteraffiliate.freeiz.com/affiliate/?id=numberherebasedonid

Then use $_GET['id'] in your script to access the value.
$sql = "SELECT clicks FROM affiliate WHERE ID='$_GET['id']'";

Please note, though, that this code is vulnerable to SQL injection. As Magnus Eriksson noted in the comments, you can negate this by either typecasting $_GET['id'] to the int type, or by using prepared statements:
Casting:
$id = (int)$_GET['id'];
$sql = "SELECT clicks FROM affiliate WHERE ID='$id'";

Prepared statements:
$statement = $conn->prepare('SELECT clicks FROM affiliate WHERE ID=?');
$statement->bind_param('s', $_GET['id']);
$statement->execute();


text:
Q: Generics issue: clone() attempting to assign weaker access privileges Let's have this class structure:
public interface TypeIdentifiable {}

public interface TypeCloneable extends Cloneable {
  public Object clone() throws CloneNotSupportedException;
}

public class Foo implements TypeCloneable, TypeIdentifiable {

   @Override
   public Object clone() throws CloneNotSupportedException {
      // ...
      return null;
   }
}

public abstract class AbstractClass<T extends TypeCloneable & TypeIdentifiable> {

   public void foo(T element) throws Exception {
      TypeCloneable cloned = (TypeCloneable) element.clone();
      System.out.println(cloned);
   }
}

I have this compilation error (although the IDE, Intellij in my case, is unable to show the error while coding)
Error:(4, 37) java: clone() in java.lang.Object cannot implement clone() in foo.TypeCloneable attempting to assign weaker access privileges; was public

I know that the compiler is trying to call clone() method from Object instead of TypeCloneable, but I don't understand why. I also tried it casting to TypeCloneable (I suposed the compiler would know which clone() method call in this case, but the same problem).
   public void foo(T element) throws Exception {
      TypeCloneable typeCloneable = (TypeCloneable) element;
      TypeCloneable cloned = (TypeCloneable) typeCloneable.clone();
   }

I'm a bit confused...Can I do something here to force callling clone() from TypeCloneable?
Thanks for the hellp

A: This works for me, (I am guessing it is a problem with the Type & Type upperbound syntax):
interface TypeIdentifiable {}

interface TypeCloneable extends Cloneable {
  public Object clone() throws CloneNotSupportedException;
}

class Foo implements TypeCloneable, TypeIdentifiable {

   @Override
   public Object clone() throws CloneNotSupportedException {
      // ...
      return null;
   }
}

interface TypeCloneableAndIndetifiable extends TypeCloneable, TypeIdentifiable  {

}
abstract class AbstractClass<T extends TypeCloneableAndIndetifiable> {

   public void foo(T element) throws Exception {
      TypeCloneable cloned = (TypeCloneable) element.clone();
      System.out.println(cloned);
   }
}