text:
Q: Unable to connect Service with GoogleApi Client I wanna make a Service Class which cannot be destroy and tells about the location using Google play Services after regular intervals
Getting error:
java.lang.RuntimeException: Unable to start service com.gmaker.glocator.gps_trackers.Service_location@db35d39 with Intent { cmp=com.gmaker.glocator/.gps_trackers.Service_location }: java.lang.IllegalStateException: GoogleApiClient is not connected yet.

This is my Service class ondestroy it creates  Brodcastservice
public class Service_location extends Service implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener {
    // LogCat tag
    private static final String TAG = "Service_location";

    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;

    private Location mLastLocation;

    // Google client to interact with Google API
    private GoogleApiClient mGoogleApiClient;

    // boolean flag to toggle periodic location updates
    private boolean mRequestingLocationUpdates = false;

    private LocationRequest mLocationRequest;

    // Location updates intervals in sec
    private static int UPDATE_INTERVAL = 10000; // 10 sec
    private static int FATEST_INTERVAL = 5000; // 5 sec
    private static int DISPLACEMENT = 10; // 10 meters

     // Method to display the location
    private void displayLocation() {

        mLastLocation = LocationServices.FusedLocationApi
                .getLastLocation(mGoogleApiClient);

        if (mLastLocation != null) {
            double latitude = mLastLocation.getLatitude();
            double longitude = mLastLocation.getLongitude();
            Log.d(TAG, "Lat: "+latitude+"Long: "+longitude);
        } else {
            Log.d(TAG, "(Couldn't get the location. Make sure location is enabled on the device)");
        }
    }

    /**
     * Method to toggle periodic location updates
     * */
    private void togglePeriodicLocationUpdates() {
        if (!mRequestingLocationUpdates) {
            mRequestingLocationUpdates = true;

            // Starting the location updates
            startLocationUpdates();
            Log.d(TAG, "Periodic location updates started!");

        }
    }

    //Creating google api client object

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();
    }

    //Creating location request object
    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FATEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
    }

    // Method to verify google play services on the device

    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {

            } else {
                Log.d(TAG, "This device is not supported.");

            }
            return false;
        }
        return true;
    }
     //Starting the location updates
    protected void startLocationUpdates() {

        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);

    }

    /**
     * Google api callback methods
     */
    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
                + result.getErrorCode());
    }

    @Override
    public void onConnected(Bundle arg0) {

        // Once connected with google api, get the location
        displayLocation();

        if (mRequestingLocationUpdates) {
            startLocationUpdates();
        }
    }

    @Override
    public void onConnectionSuspended(int arg0) {
        mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        // Assign the new location
        mLastLocation = location;

        Toast.makeText(getApplicationContext(), "Location changed!",
                Toast.LENGTH_SHORT).show();

        // Displaying the new location on UI
        displayLocation();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        // First we need to check availability of play services
        if (checkPlayServices()) {

            // Building the GoogleApi client
            buildGoogleApiClient();

            createLocationRequest();
        }
        // Show location button click listener

        displayLocation();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        togglePeriodicLocationUpdates();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Intent intent = new Intent("com.gmaker.glocator");
        sendBroadcast(intent);
    }

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

Broadcast Receiver
public class Reciever_location extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("Service Stops", "Ohhhhhhh");
        context.startService(new Intent(context, Service_location.class));;
    }

}

In Manifest I have declared the service
<service android:name=".gps_trackers.Service_location" />

I have initialize my Service on main activity in function onCreate

A: According to your error, you're approaching GoogleApiClient before onConnected is called.
You're calling togglePeriodicLocationUpdates from onStartCommand before the GoogleClientApi is connected.


text:
Q: In App Purchase is not appearing on AppStore version on iOS We're are currently having issues with our app being rejected because the AppStore reviewer can't see our in-app purchases. We can't seem to find why this is occurring. Does the in-app purchases have to be approved before the app. Though this is a new release of the app, not an update. When we run in development mode, it works perfectly fine. The bundle identifier isn't different for development or app store version. Not sure what's going on here.

A: In iTunes Connect you need to submit your In App Purchases of the app for the review.
When you are selecting option 'Ready to upload binary', then you should see options to submit new in app purchases, turn them on and upload your binary. (in the "In-App Purchases" section use the link "Manage In-App Purchase" and select all those IAP's which are to be reviewed).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jquery Jcarousel not working with PHP I have this code:

        <button type="button" class="close" data-dismiss="modal">x</button>

Which is inside an HTML document. When I click on any of the images, then the Jcarousel shows up correctly, like this:

The problem is that this gallery needs to be filled from a database, and I've achieved this with this code:
<?php
    include("FuncionesBaseDatos.php");
    $bd = new FuncionesBaseDatos();

    $idVisita = $_POST['t1'];

    $queryImagenes = pg_query("
        SELECT
            ID_IMAGEN,
            NOMBRE,
            RUTA
        FROM IMAGEN
        WHERE ID_VISITA = $idVisita
    ");

    while($imagen = pg_fetch_row($queryImagenes)){
        $aux = str_replace('\\', '/',$imagen[2]) . '/' . $imagen[1];
        echo "

        ";
    }
?>

But, despite of this, when I click on these new images, Jcarousel does not show up, instead of that, the image is opened by the browser, like this:

And I don't have a clue of why this is happening.
Any ideas will be very appreciated.
Thanks!


text:
Q: How to schedule a job for every 2:30 hours between 1:00 AM and 5:00 AM using quartz I want to schedule a job for every 2:30 hours between 1:00 AM and 5:00 AM using only single cron expression. Is it possible to achieve this?

A: according to my understanding of your question. just try this
0 150 1-5 ? * * *
for more information you can take help of following link. may be this helps you.
http://sanjaal.com/java/tag/cron-expression-ever-hours/

A: I am modifying answer please check with this. may be this is correct but not sure. just try
0 30 2 1-5 * * *


text:
Q: How to access global variable from inside class's function I have file init.php:
<?php
     require_once 'config.php';
     init::load();
?>

with config.php:
<?php
     $config = array('db'=>'abc','host'=>'xxx.xxx.xxx.xxxx',);
?>

A class with name something.php:
<?php
     class something{
           public function __contruct(){}
           public function doIt(){
                  global $config;
                  var_dump($config); // NULL
           }
     }
?>

Why is it null?
In php.net, they told me that I can access but in reality is not .
I tried but have no idea.
I am using php 5.5.9.

A: The variable $config in config.php is not global.
To make it a global variable, which i do NOT suggest you have to write the magic word global in front of it.
I would suggest you to read superglobal variables.
And a little bit of variable scopes.
What I would suggest is to make a class which handles you this.
That should look something like
class Config
{
    static $config = array ('something' => 1);

    static function get($name, $default = null)
    {
        if (isset (self::$config[$name])) {
            return self::$config[$name];
        } else {
            return $default;
        }
    }
}

Config::get('something'); // returns 1;

A: Use Singleton Pattern like this
<?php
     class Configs {
        protected static $_instance;
        private $configs =[];
        private function __construct() {
        }

        public static function getInstance() {
            if (self::$_instance === null) {
                self::$_instance = new self;
            }
            return self::$_instance;
        }

        private function __clone() {
        }

        private function __wakeup() {
        }
        public function setConfigs($configs){
         $this->configs = $configs;
        }
        public function getConfigs(){
         return $this->configs;
        }
    }

Configs::getInstance()->setConfigs(['db'=>'abc','host'=>'xxx.xxx.xxx.xxxx']);

     class Something{
           public function __contruct(){}
           public function doIt(){
                  return Configs::getInstance()->getConfigs();
           }
     }
var_dump((new Something)->doIt());

A: Include the file like this:
 include("config.php");
     class something{ ..

and print the array as var_dump($config); no need of global.

A: Change your class a bit to pass a variable on the constructor.
<?php
     class something{
           private $config;
           public function __contruct($config){
               $this->config = $config;
           }
           public function doIt(){
                  var_dump($this->config); // NULL
           }
     }
?>

Then, if you

*

*include config.php

*include yourClassFile.php
and do,
<?php
$my_class = new something($config);
$my_class->doIt();
?>

It should work.
Note: It is always good not to use Globals (in a place where we could avoid them)


text:
Q: Woocommerce custom plugin, WC_Order error inside a custom plugin placed this code to get an order:
 global $woocommerce;
 $order = new WC_Order(5273);

(and i have the order with 5273 in the database), but the result is:

Fatal error:  Cannot use object of type WP_Error as array in D:\www\htdocs..\wp-content\plugins\woocommerce\includes\class-wc-order.php on line 83
What is the problem?

A: I finally figured out the problem. I called the code above inside the initialization hook, like this:
add_action('init', 'my_init', 1);
function my_init(){
    $order = new WC_Order(5273);
}

the last argument in add_action is the priority and that was the point. 1 is the highest priority and my function is being called before the taxonomy registrations. I changed 1 to 100 and the code is working perfectly.


text:
Q: How to get all has_many associations from an active record collection I have two models with has_many through associations; Taskflows and Datasets. They has a join table called DatasetAssignments.
I get all Taskflows using:
@taskflows = Taskflows.all
I know it's possible to get associations from a single ActiveRecord object, eg:
@taskflow.datasets
but is it possible to get all associated Datasets from the @taskflows ActiveRecord collection? Such as @taskflows.datasets
Any help would be much appreciated.
Models:
class Dataset < ActiveRecord::Base
  has_many :dataset_assignments
  has_many :taskflows, :through => :dataset_assignments
end

class Taskflow < ActiveRecord::Base
  has_many :dataset_assignments
  has_many :datasets, :through => :dataset_assignments
end

class DatasetAssignment < ActiveRecord::Base
  belongs_to :dataset
  belongs_to :taskflow
end

A: Given that @taskflows is an ActiveRecord::Relation, you can do this:
@datasets = Dataset.joins(:dataset_assignments).
    where(dataset_assignments: {taskflow: @taskflows.joins(:datasets) })

or, in the other direction:
@taskflows = Taskflow.joins(:dataset_assignments).
    where(dataset_assignments: {dataset: @datasets.joins(:taskflows) })

joins generates INNER JOINs through many-to-many table and having the receiver being an instance of ActiveRecord::Relation will preserve other conditions.
As @oreoluwa suggested, you can avoid N+1 queries when enumerating by using includes:
@taskflows = Taskflow.joins(...).includes(:datasets)

A: I don't think there is a way to do this, unless you have an outer model, let's call it User, where:
User
  has_many :taskflows
  has_many :datasets, through: :taskflows

or better let your DatasetAssignment belong to the user and fetch all dataset_assignments of a particular User.
Another approach would be to do a @taskflows.map(&:datasets), but it's not effecient.
Or if you only need the datasets to render somewhere and are bothered about effeciency, you should use the AR#includes method like:
@taskflow.includes(:datasets)


text:
Q: Why does my View.findViewById return null? I am currently practising on using Fragment and RecyclerView, and working on a RecyclerView.Adapter class. When I tried to run the project, the app does not run correctly. I found that in the logcat stack trace, there was an error saying
    java.lang.NullPointerException: Attempt to invoke virtual method 'void
    android.widget.ImageView.setImageResource(int)' on a null object reference

I tried debugging, and found out that in my code:
public class LanguageAdapter extends RecyclerView.Adapter<LanguageAdapter.LanguageViewHolder> {

    private List<Language> mLanguageList;

    public LanguageAdapter(List<Language> languageList) {
        mLanguageList = languageList;
    }

    @NonNull
    @Override
    public LanguageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item_language, parent, false);

        return new LanguageViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull LanguageViewHolder holder, int position) {
        Language language = mLanguageList.get(position);
        holder.bind(language);
    }

    @Override
    public int getItemCount() {
        return mLanguageList.size();
    }

    public class LanguageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private ImageView mLanguageLogoImageView;
        private TextView mLanguageNameTextView;
        private TextView mLanguageRankTextView;
        private Language mLanguage;

        public LanguageViewHolder(@NonNull View itemView) {
            super(itemView);
            mLanguageLogoImageView = itemView.findViewById(R.id.language_logo);
            mLanguageNameTextView = itemView.findViewById(R.id.language_name);
            mLanguageRankTextView = itemView.findViewById(R.id.language_rank);
        }

        @Override
        public void onClick(View v) {

        }

        private void bind(Language language) {
            mLanguage = language;
            mLanguageLogoImageView.setImageResource(mLanguage.getLanguageLogo());
            mLanguageNameTextView.setText(mLanguage.getLanguageName());
            mLanguageRankTextView.setText(mLanguage.getLanguageRank());
        }
    }
}

This part
    mLanguageLogoImageView = itemView.findViewById(R.id.language_logo);
    mLanguageNameTextView = itemView.findViewById(R.id.language_name);
    mLanguageRankTextView = itemView.findViewById(R.id.language_rank);

returns null. But the itemView, which I inflated from
    View itemView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.list_item_language, parent, false);

does indeed returned a View. But when I try to View.findViewById(), it returns null. I read already the other threads, including this. But it did not solve my problem as I am working with an adapter. Am I missing some steps here?

A:   mLanguageLogoImageView = itemView.findViewById(R.id.language_logo);
  mLanguageNameTextView = itemView.findViewById(R.id.language_name);
  mLanguageRankTextView = itemView.findViewById(R.id.language_rank);

NullPointerException is thrown when an application attempts to use an object reference that has the null value.
At first check your all findViewById elements present in respective xml (R.layout.list_item_language) or not.


text:
Q: How to add extra column with values based on previous rows in Pandas data frame? I have this data frame:
'C1'|'C2'
 0  | x
 1  | x1
 1  | x2
 2  | x3
 0  | y
 1  | y1
 2  | y2
 0  | z
 1  | z1

I need to create an extra column like this:
'C1'|'C2'|'C3'
 0  | x  | x
 1  | x1 | x
 1  | x2 | x
 2  | x3 | x
 0  | y  | y
 1  | y1 | y
 2  | y2 | y
 0  | z  | z
 1  | z1 | z

Basically when ever I find 0 in the C1 column, I have to put in all the sub rows (until the next 0) the corresponding value from the C2 column.
I am new to Pandas and I read that I should avoid manipulating the data frame using iterations.
How can a get this result without iterating? Is it possible?

A: Use Series.where for mising values if not match condition with Series.eq (==) and forward filling missing values by ffill:
df['C3'] = df['C2'].where(df['C1'].eq(0)).ffill()
print (df)
   C1  C2 C3
0   0   x  x
1   1  x1  x
2   1  x2  x
3   2  x3  x
4   0   y  y
5   1  y1  y
6   2  y2  y
7   0   z  z
8   1  z1  z

A: You may try this also:
df['C3']=df['C2'].astype(str).str[0]
print(df)


text:
Q: Opening MXD saved in one version using earlier version Working in an enterprise system. We need to determine if everyone needs to update to 10.6 at the same time for mxd cross-compatibility or can we update from 10.5 as needed.

A: You need to save a copy of the mxd to an earlier version if you have saved the mxd in ArcGIS latest version 10.6.
Based on ArcGIS help: Saving a map:

New documents cannot be opened in earlier versions of the software;
  however, you can use the Save A Copy command to make a copy of a map
  document so you can open and work with it in previous versions of
  ArcGIS.

A: The MXD Doctor will also work. The tool can be found here..
C:\Program Files (x86)\ArcGIS\Desktop10.6\Tools

A: As @JordanMiller mentioned, the MXD Doctor can fix the mxds, but not just looking backwards, but from future releases.  I just used the 10.5 MXD Doctor to backward save some 10.6 mxds for use in 10.5 (I had to downgrade for HEC-GeoHMS and HEC-GeoRAS, and didn't think to save as before uninstalling 10.6).

A: I have had a similar issue and I used Python script to fix it... You need to open a blank document in ArcMap, then open the Python window. Then copy/paste the following code, just repoint the path to the proper mxds...
mxd_path=r"path/to/the/10_5_mxd.mxd"
mxd= arcpy.mapping.MapDocument(mxd_path)
mxd.saveACopy(r"path/to/the/new/10_4_mxd.mxd","10.1")

In ArcMap 10.6 the list of options for the version parameter are: ['10.1', '10.0', '8.3', '10.3', '9.0', '9.2', '9.3']


text:
Q: Transaction atomic needed for bulk create? I'm using the bulk_create method from Django to create many entries at once.
To ensure that the changes are only committed if there is no exception I'm thinking about adding transaction.atomic() to the code blocks but I'm not sure if I need to add it.
From my understanding I only need to add it in Scenario 2 because in this case I'm executing more than one query.
Scenario 1
Create 1.000 entries in one query
Entry.objects.bulk_create([
    Entry(headline='This is a test'),
    Entry(headline='This is only a test'),
    # ...
])

Scenario 2
Create 10.000 entries in in batches of 1.000
Entry.objects.bulk_create([
    Entry(headline='This is a test'),
    Entry(headline='This is only a test'),
    # ...
], batch_size=1_000)

A: No, you don't have to for either scenario. According to the Django source code, using transaction atomic would be redundant for bulk_create as that method already uses atomic transactions.


text:
Q: Unable to start new Nextjs application Failed to load next.config.js I pulled a nextJS application from git and tried starting it using npm run dev ,npx next dev npm run start, matter of fact, every single command I ran gave me the same error.
To further troubleshoot, I followed a youtube tutorial and I started a brand new project ran npx create-next-app appname and again. Same error.
H:\Documents\Projects\React\NextTutorial\ninjalist>npm run dev ninjalist@0.1.0 dev next dev ready - started server on 0.0.0.0:3000, url: http://localhost:3000 error - Failed to load next.config.js, see more info here https://nextjs.org/docs/messages/next-config-error Error: Not supported at Object.loadConfig [as default] (H:\Documents\Projects\React\NextTutorial\ninjalist\node_modules\next\dist\server\config.js:399:74) at async NextServer.loadConfig (H:\Documents\Projects\React\NextTutorial\ninjalist\node_modules\next\dist\server\next.js:110:22) at async NextServer.prepare (H:\Documents\Projects\React\NextTutorial\ninjalist\node_modules\next\dist\server\next.js:92:24) at async H:\Documents\Projects\React\NextTutorial\ninjalist\node_modules\next\dist\cli\next-dev.js:126:9
Most prominent is it's failing to load next.config.js
and the contents of that file is simply
/** @type {import('next').NextConfig} */ module.exports = { reactStrictMode: true, }
Appreciate if I could be informed on what i'm missing cause I have not written any code, this is straight from the create app and I am getting this error.
Gratitude for the assistance.

A: Dont waste even a single minute. Just update to the latest version of node

A: Solved it by upgrading to the latest version of NodeJS


text:
Q: Реализация хеш-таблицы Мне нужно реализовать хеш-таблицу и сравнить её с STL unordered_map. Мои показатели как-то сильно отличаются от unordered_map. Прошу подсказать, где я ошибся. Вот мой код:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <time.h>
#include <cstring>
#include <unordered_map>

using namespace std;

long long generateRandLong() { //генератор большого(12 цифрового) ключа для хеш-функции

    int num = 12;
    long long a = 1;
    long long r = 0;
    for (int i = 0; i < num; i++)
    {
        if (i == (num - 1))
        {
            r += a * ((long long)(rand() % 9) + 1);
            break;
        }
        r += a * (rand() % 10);
        a *= 10;
    }
    return r;

}

struct Data { // структура данных
    char name[10];
    int amountOfStudents;
    bool turnstiles;

    Data() {  // генератор случайных данных для структуры Data
        char* name1 = new char[10];
        for (int i = 0; i < 9; i++)
        {
            name1[i] = 'a' + rand() % 26;
        }
        name1[9] = '\0';
        strcpy(name, name1);

        this->amountOfStudents = rand() % 30;
        this->turnstiles = rand() % 2;
        delete[] name1;
        name1 = nullptr;
    }
        Data(const char a[], int b, bool c){ // конструктор Data
            strncpy(name, a, 10);
            amountOfStudents = b;
            turnstiles = c;
        }

};

struct HashNode { узел, необходимый для реализации односвязного списка
    long long key;
    Data data;
    HashNode* next;
    HashNode(Data data, long long key, HashNode* next) {
        this->data = data;
        this->key = key;
        this->next = next;
    }

};

struct LinkedList { // односвязный список для каждой ячейки в массиве

    HashNode* head = NULL;
    HashNode* tail = NULL;

    void push_back(Data data, long long key) // метод, необходимый для "insert" в таблицу
    {
        HashNode* newHashNode = new HashNode(data, key, NULL);

        if (head == NULL)
        {
            head = newHashNode;
            tail = newHashNode;
        }
        else
        {
            tail->next = newHashNode;
            tail = newHashNode;
        }
    }
};

struct HashTable { // сама хеш-таблица
    int m = 8;
    LinkedList* bucketsArray = new LinkedList[m];

    const int alpha = 2;
    int realsize = 0;
    float LoadFactor = 3;

    int hash(long long key) { // хеш-функция
        //cout << key % m << endl;
        return key % m;
    }

    void insert(long long key, Data value) // добавление элемента в таблицу
    {

        if (LoadFactor < ((float)realsize / m))
        {
            m *= alpha;
            LinkedList* NewbucketsArray = new LinkedList[m];
            for (int i = 0; i < m / alpha; i++)
            {
                NewbucketsArray[i] = bucketsArray[i];
            }
            delete[] bucketsArray;
            bucketsArray = NewbucketsArray;
        }
        int index = hash(key);
        HashNode* currentNode = bucketsArray[index].head;
        while (currentNode != NULL) {
            if (currentNode->key == key) {
                currentNode->data = value;
                return;
            }
            currentNode = currentNode->next;
        }

        bucketsArray[index].push_back(value, key);

        realsize++;
    }

    Data* find(long long key) // поиск элемента по таблице
    {
        int index = hash(key);
        HashNode* currentNode = bucketsArray[index].head;
        if (currentNode == NULL)
        {
            //cout << "There is no such an element with such a key" << endl;
            return NULL;
        }
        if (currentNode->key == key)
        {
            return &currentNode->data;
        }

        while (currentNode != NULL)
        {
            if (currentNode->key == key)
                return &currentNode->data;
            currentNode = currentNode->next;
        }
        return NULL;
    }
    Data erase(long long key) // удаление элемента из таблицы
    {
        int index = hash(key);
        if(bucketsArray[index].head == NULL)
        {
            //cout << "There is no such an element in the list" << endl;
            Data a("\0", 0, 0);
            return a;
        }
        else
        {
            HashNode* tempNode = bucketsArray[index].head;
            if (tempNode->key == key)
            {
                if (tempNode->next == NULL)
                {

                    bucketsArray[index].head = NULL;
                    Data a = tempNode->data;
                    delete tempNode;
                    realsize--;
                    return a;
                }

                bucketsArray[index].head = bucketsArray[index].head->next;
                Data a = tempNode->data;
                delete tempNode;
                realsize--;
                return a;
            }

            HashNode* prevNode = bucketsArray[index].head;
            HashNode* currentNode = bucketsArray[index].head->next;
            while (currentNode != NULL)
            {
                if (currentNode->key == key)
                    break;

                prevNode = currentNode;
                currentNode = currentNode->next;
            }
            if (currentNode == NULL)
            {
                //cout << "There is no such an element with such a key" << endl;
                Data a("\0", 0, 0);
                return a;
            }
            prevNode->next = currentNode->next;
            realsize--;
            Data a = currentNode->data;
            delete currentNode;
            return a;
        }
    }

    int size() // размер таблицы
    {
        return realsize;
    }
};

bool testHashTable() // сравнение моей таблицы с unordered_map
{
    const int iters = 500000;
    const int keysAmount = iters * 1;
    // generate random keys:
    long long* keys = new long long[keysAmount];
    long long* keysToInsert = new long long[iters];
    long long* keysToErase = new long long[iters];
    long long* keysToFind = new long long[iters];
    for (int i = 0; i < keysAmount; i++)
    {
        keys[i] = generateRandLong();
    }
    for (int i = 0; i < iters; i++)
    {
        keysToInsert[i] = keys[generateRandLong() % keysAmount];
        keysToErase[i] = keys[generateRandLong() % keysAmount];
        keysToFind[i] = keys[generateRandLong() % keysAmount];
    }
    // test my HashTable:
    HashTable hashTable;
    clock_t myStart = clock();
    for (int i = 0; i < iters; i++)
    {
        hashTable.insert(keysToInsert[i], Data());
    }
    int myInsertSize = hashTable.size();
    for (int i = 0; i < iters; i++)
    {
        hashTable.erase(keysToErase[i]);
    }
    int myEraseSize = hashTable.size();
    int myFoundAmount = 0;
    for (int i = 0; i < iters; i++)
    {
        if (hashTable.find(keysToFind[i]) != NULL)
        {
            myFoundAmount++;
        }
    }
    clock_t myEnd = clock();
    float myTime = (float(myEnd - myStart)) / CLOCKS_PER_SEC;
    // test STL hash table:
    unordered_map<long long, Data> unorderedMap;
    clock_t stlStart = clock();
    for (int i = 0; i < iters; i++)
    {
        unorderedMap.insert({ keysToInsert[i], Data() });
    }
    int stlInsertSize = unorderedMap.size();
    for (int i = 0; i < iters; i++)
    {
        unorderedMap.erase(keysToErase[i]);
    }
    int stlEraseSize = unorderedMap.size();
    int stlFoundAmount = 0;
    for (int i = 0; i < iters; i++)
    {
        if (unorderedMap.find(keysToFind[i]) != unorderedMap.end())
        {
            stlFoundAmount++;
        }
    }
    clock_t stlEnd = clock();
    float stlTime = (float(stlEnd - stlStart)) / CLOCKS_PER_SEC;
    cout << "My HashTable:" << endl;
    cout << "Time: " << myTime << ", size: " << myInsertSize << " - " << myEraseSize << ", found amount: " << myFoundAmount << endl;
    cout << "STL unordered_map:" << endl;
    cout << "Time: " << stlTime << ", size: " << stlInsertSize << " - " << stlEraseSize << ", found amount: " << stlFoundAmount << endl << endl;
    delete [] keys;
    delete [] keysToInsert;
    delete [] keysToErase;
    delete [] keysToFind;

    if (myInsertSize == stlInsertSize && myEraseSize == stlEraseSize && myFoundAmount == stlFoundAmount)
    {
        cout << "Сompleted" << endl;
        return true;
    }
    cerr << ":(" << endl;
    return false;
}

int main() {
    srand((unsigned)time(NULL));

    testHashTable();

    return 0;
}

Принцип работы:
Создать специальный ключ для каждого элемента, найти индекс для вставки через хеш-функцию и через insert вставить элемент. Если LoadFactor(количество элементов в таблице разделенное на размер массива) меньше 3, то увеличить длину массива в 2 раза. Если под индексом в массиве есть уже данные, то проверить если ключ совпадает, то заменить старые на новые, если нет, то добавить элемент в односвязный список.


text:
Q: node module - aes256 - crypto.createHash is not a function So I have this Angular 5 application which uses aes256 library from NPM for encrypting password for login form. Inside that aes256 library, theres var crypto = require('crypto'). When I run my application and try the login form, I encountered crypto.createHash is not a function error.
When I debugged my app to find out whats wrong, I see that var crypto was just an empty object.
crypto.createHash is not a function
crypto - empty object

A: You cannot use crypto module in angular application nor aes256 since it is build on crypto module. crypto module is a node native module you can't use any node native module from nodejs in angular application as it is running on the browser. Checkout some fronted encryption libraries here

A: You should use crypto-js library, this works for me
npm install crypto-js
npm install --save @types/crypto-js

Use it
import { SHA256, enc } from 'crypto-js';

const password = SHA256(this.loginForm.value.password).toString(enc.Hex);


text:
Q: Non-invasive current sensor noise problem I'm working on a project where I'm measuring current with a split core CT and feed the signal to an Arduino analog input.
The problem I'm facing is that I get noise from nearby systems.
Example is when I wire up a small electrical pump (about 250mA), and hold my split core current transformer next to it (without clipping it onto the wire!) I still get readings on the analog input.
This will be a big problem as I'm planning on sensing current at locations where there will be other wires conducting current around.
The split core CT I'm using is the SCT-013-005.
Does anyone have any solution for this problem? Is it simply a poor quality current sensor that is not isolated from outside electrical noise?
I have not yet tried to measure current with the CT, and have another component nearby drawing current.

A: OK so you've got this pump that presumably has got hundreds of turns to create enough magnetism to rotate the armature. The pump takes 250mA and the magneto motive force (MMF) is amps multiplied by turns. The magnetic field emanating from this pump has a driving force of 25 ampere turns (that's 0.25 amps x 100 turns) and maybe there are more like a thousand turns. It could be as high as 250 ampere turns.
On the other hand, when you feed a single wire (that's one turn) through the CT to measure maybe 40 amps peak\$^1\$ of household consumption, the MMF is 40.
You hold the CT close to the pump and you get a reading - are you still surprised? It's called leakage flux and the CT's core is not a perfect rejector of leakage flux that hits it.

\$^1\$ this will be different depending what your AC voltage is.


text:
Q: Ruby on Rails + jQuery Mobile + phonegap - All server side HTML rendering - Will it work? In an attempt to be able to create a rich application using ROR3 Jquery Mobile and phonegap after reading this article - http://fuelyourcoding.com/getting-started-with-jquery-mobile-rails-3/
I was wondering if it would be possible to render all of the apps content on the server side while jquery mobile handled all of the nice transitions?
Would the work as a phonegap app? (considering that no JSON is being used at all)

A: Yes, you can use ROR with jQM, no problem there. jQM will be used only to handle a HTML GUI restyling. But you are not going to have transitions with an ajax turned off.
Then again this should not worry you because transitions don't work well with the older Android platform's. Even versions 4+ have a few problems.
And yes, this app will work with phonegap, as I said previously just without transitions.
EDIT :
If you still want to use ajax (it can be done) you will only have a problem with form submitting.

A: It will certainly work, proof is my example rails / ember.js Application that is exported with Phonegap. It comes with token authentication (ember-auth) + OAuth (Google, LinkedIn,..) and Devise.
See it in de the devel branch of my base App project: https://github.com/joscas/base_app/tree/devel
Life deploy: https://starter-app-staging.herokuapp.com (the desktop version)
It uses a gem (phonegap-rails) I've created to export assets, fix paths etc.

A: I think you can actually render everything server side and have it still work. This is how basecamp does it, using turbolinks, and how we're attempting to do it. GoNative.io handles this all for you, but you can also just create a webpage in phonegap that just opens an external URL to your site (the user can't tell). I don't see this on their docs but we've done it and it works. There are a few issues with file upload and the UI which are solvable, but GoNative.io claims to do it all for you while handing those. We originally did ours using PhoneGap, which probably would have worked but ended up switch to GoNative. There may be an issue with getting into apple store using this method, but we're being optimistic that we can get in (GoNative.io claim to have no problem with it)


text:
Q: Counter-intuitive date command I've been using date in a script in order to add one year to a specific date the following way:
date '+%Y-%m-%d %H:%M:%S' -d "$DATE + 1 year"

In this example, DATE looks like 2022-05-11 14:20.
Everything is working well. However it turns out that adding one single year, week, or day works fine, but adding multiples returns a bogus result.
Correct result for a singular year, week, or day:
$ date '+%Y-%m-%d %H:%M:%S' -d "2022-05-11 14:20 +1day"
2022-05-12 15:20:00
$ date '+%Y-%m-%d %H:%M:%S' -d "2022-05-11 14:20 +1week"
2022-05-18 15:20:00
$ date '+%Y-%m-%d %H:%M:%S' -d "2022-05-11 14:20 +1year"
2023-05-11 15:20:00

Bogus result for adding multiple years, weeks, or days:
$ date '+%Y-%m-%d %H:%M:%S' -d "2022-05-11 14:20 +2days"
2022-05-12 14:20:00
$ date '+%Y-%m-%d %H:%M:%S' -d "2022-05-11 14:20 +3weeks"
2022-05-18 13:20:00
$ date '+%Y-%m-%d %H:%M:%S' -d "2022-05-11 14:20 +4years"
2023-05-11 12:20:00

The first unit is valid, and the others decrease the hour.
The workaround I've found for my case was to add several times the same unit:
$ date '+%Y-%m-%d %H:%M:%S' -d "2022-05-11 14:20 +1day +1day"
2022-05-13 15:20:00
$ date '+%Y-%m-%d %H:%M:%S' -d "2022-05-11 14:20 +1week +1week +1week"
2022-06-01 15:20:00
$ date '+%Y-%m-%d %H:%M:%S' -d "2022-05-11 14:20 +1year +1year +1year +1year"
2026-05-11 15:20:00

You may have also noted that what I've called "correct results" also increase the date by one hour.
Has anybody have an explanation about why this isn't working as I would expect?
Best regards.


text:
Q: How to fetch month and year at the same time from date where date column is in varchar datatype. Using snowflake tool I am trying to fetch both the months and years from the Column (MISSUE) while introducing an "_"  in snowflake. For example (6_2021, 7_2021 etc).
This can be archive in MS Access query as:
Month([MISSUE]) & "_" & Year([MISSUE]) AS Month_Year
My current Code in Snowflake shows:
EXTRACT(Month, TO_DATE(MISSUE)) &'_'& EXTRACT(Year, TO_DATE(MISSUE)) AS Month_Year
Can someone please tell me what I am during wrong?
Thank you!

A: Alternatively save yourself some typing (dad joke) :
select to_char(MISSUE::DATE,'MM_YYYY') from tbl

Copy|Paste|Run|In Snowflake:
with tbl as (select $1 as MISSUE from values ('2017-04-10'), ('2017-06-10'))
select
    to_char(MISSUE :: DATE, 'MM_YYYY') cleaner
from
     tbl

A: You can use CONCAT_WS() for this.
with tbl as (select $1 as MISSUE from values ('2017-04-10'), ('2017-06-10'))

select concat_ws('_', month(to_date(MISSUE)), year(to_date(MISSUE))) from tbl;

CONCAT_WS('_', MONTH(TO_DATE(MISSUE)), YEAR(TO_DATE(MISSUE)))
4_2017
6_2017


text:
Q: How to sample data with unknown size into a limited number of subset? my question is the following, let's assume that we do not know the size of full data set ahead(it could be 100m or just 10,000), and I want to sample it based on an "ID" column, for example we hash "ID" values into "abcd", and we could easily sample 1/26 of it by selecting hash values starting with "a"(or 1/26 * 1/26 when selecting values starting with "aa", etc). The question is that I want to have a limited number of subset say 100,000 max. Is it possible to apply some hash trick to the origin dataset to achieve such result?
Thanks.


text:
Q: SwiftUI - data source as struct - performance and redundancy through copies - why still use it? I have a minimal working example of something I'm still not sure about:
import SwiftUI

struct Car {
    var name: String
}

class DataModel: ObservableObject {
    @Published var cars: [Car]

    init(_ cars: [Car]) {
        self.cars = cars
    }
}

struct TestList: View {
    @EnvironmentObject var dataModel: DataModel

    var body: some View {
        NavigationView {
            List(dataModel.cars, id: \.name) { car in
                NavigationLink(destination: TestDetail(car: car).environmentObject(self.dataModel)) {
                    Text("\(car.name)")
                }
            }
        }
    }
}

struct TestDetail: View {
    @EnvironmentObject var dataModel: DataModel
    var car: Car

    var carIndex: Int {
        dataModel.cars.firstIndex(where: {$0.name == self.car.name})!
    }

    var body: some View {
        Text(car.name)
            .onTapGesture {
                self.dataModel.cars[self.carIndex].name = "Changed Name"
        }
    }
}

struct TestList_Previews: PreviewProvider {
    static var previews: some View {
        TestList().environmentObject(DataModel([.init(name: "A"), .init(name: "B")]))
    }
}

It's about the usage of structs as data models. The example is similar to the official SwiftUI tutorial by Apple (https://developer.apple.com/tutorials/swiftui/handling-user-input).
Basically, we have a DataModel class that is passed down the tree as EnvironmentObject. The class wraps the basic data types of our model. In this case, it's an array of the struct Car:
class DataModel: ObservableObject {
    @Published var cars: [Car]
    ...
}

The example consists of a simple list that shows the names of all cars. When you tap on one, you get to a detail view. The detail view is passed the car as property (while the dataModel is passed as EnvironmentObject):
NavigationLink(destination: TestDetail(car: car).environmentObject(self.dataModel)) {
    Text("\(car.name)")
}

The property car of the detail view is used to populate it. However, if you want to e.g. change the name of the car from within the detail view you have to go through the dataModel because car is just a copy of the original instance found in dataModel. Thus, you first have to find the index of the car in the dataModel's cars array and then update it:
struct TestDetail: View {
    ...
    var carIndex: Int {
        dataModel.cars.firstIndex(where: {$0.name == self.car.name})!
    }
    ...
    self.dataModel.cars[self.carIndex].name = "Changed Name"

This doesn't feel like a great solution. Searching for the index is a linear operation you have to do whenever you want to change something (the array could change at any time, so you have to constantly repeat the index search).
Also, this means that you have duplicate data. The car property of the detail view exactly mirrors the car of the viewModel. This separates the data. It doesn't feel right.
If car was a class instead of a struct, this would no be a problem because you pass the instance as reference. It would be much simpler and cleaner.
However, it seems that everyone wants to use structs for these things. Sure, they are safer, there can't be reference cycles with them but it creates redundant data and causes more expensive operations. At least, that's what it looks like to me.
I would love to understand why this might not be a problem at all and why it's actually superior to classes. I'm sure I'm just having trouble understanding this as a new concept.


text:
Q: How to make reusable scrollbars in Tkinter? I'd like to create an easy way to add scrollbars to any frame I like. So far, only one works. What's wrong with this script? What's a proper way to do this? I still only have a faint grasp of all the concepts hidden in this, sorry.
import Tkinter as tk

def data(parent):
    for i in range(50):
       tk.Label(parent,text=i).grid(row=i,column=0)
       tk.Label(parent,text="my text"+str(i)).grid(row=i,column=1)
       tk.Label(parent,text="..........").grid(row=i,column=2)

class ScrollBar():
    #def __init__(self, tk):
    #    self.canvas = tk.Canvas()

    def myfunction(self, event):
        self.canvas.configure(scrollregion=self.canvas.bbox("all"), width=200, height=200)
        print("orig: ",self.canvas)

    def makeScrollBar(self, tk, parent):

        self.outerframe = tk.Frame(parent, relief="groove", width=50, height=100, bd=1)
        self.outerframe.pack()

        self.canvas = tk.Canvas(self.outerframe)
        self.innerframe = tk.Frame(self.canvas)
        self.myscrollbar = tk.Scrollbar(self.outerframe, orient="vertical", command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=self.myscrollbar.set)

        self.myscrollbar.pack(side="right",fill="y")

        self.canvas.pack(side="left")
        self.canvas.create_window((0,0), window=self.innerframe, anchor="nw")

        self.innerframe.bind("<Configure>", self.myfunction)
        print("orig: ",self.canvas)
        return self.innerframe

root = tk.Tk()
root.wm_geometry("800x600+100+100")

scrollbargenerator = ScrollBar()
b = scrollbargenerator.makeScrollBar(tk, root)
c = scrollbargenerator.makeScrollBar(tk, root)
data(b)
data(c)
root.mainloop()

A: First, you manage to create your scrollbars. If you scroll your mouse over the first scrollbar it will actually scroll the canvas. The thumb does not appear (or do not move) because the scrollregion is never set for this canvas.
In fact, your use of classes and objects is broken. Your Scrollbar class is instantiated once and this only instance update its fields each time makeScrollBar is called. Thus in myfunction callback, self.canvas always refer to the lastly created canvas.
You can easily fix your code my using different scrollbar generators
scrollbargenerator = ScrollBar()
b = scrollbargenerator.makeScrollBar(tk, root)
scrollbargenerator = ScrollBar()
c = scrollbargenerator.makeScrollBar(tk, root)

or capturing the canvas in a closure
def myfunction(self, canvas):
    canvas.configure(scrollregion=canvas.bbox("all"), width=200, height=200)

def makeScrollBar(self, tk, parent):
    #(...)
    self.innerframe.bind("<Configure>", (lambda canvas: (lambda event: self.myfunction(canvas)))(self.canvas))

or relying on the information already present in event
@staticmethod
def myfunction(event):
    event.widget.master.configure(scrollregion=event.widget.master.bbox("all"), width=200, height=200)


text:
Q: Javascript not waiting for onclick I am trying to execute this code but for some reason that I cannot figure out the RoundRobin function will execute onload rather than onclick. I have tried removing window.onload or replacing it with document.onload. All I want is for this line document.getElementById("tableButton").onclick  = RoundRobin(teamsIn); to wait for the onclick trigger.
var selectedTeams = [];

window.onload = function() {
// JavaScript Document

// add selected teams to array

var teamList = document.getElementById("teamDropdown");
teamList.onchange = function addTeams() {

    if (selectedTeams.length > 7) {

        alert("no more teams")

    } else {
        var county = document.getElementById("teamDropdown").value;
        selectedTeams.push(county);
    }

    alert("counties selected are: " + selectedTeams);
}

var teamsIn = 0;
teamsIn = selectedTeams.length;

document.getElementById("tableButton").onclick = RoundRobin(teamsIn);

// slideshow.
var imageArray = new Array();
imageArray[0] = new Image()
imageArray[0].src = "Sponsors/aib.png"

imageArray[1] = new Image()
imageArray[1].src = "Sponsors/centra.jpg"

imageArray[2] = new Image()
imageArray[2].src = "Sponsors/eircom.png"

imageArray[3] = new Image()
imageArray[3].src = "Sponsors/etihad.png"

imageArray[4] = new Image()
imageArray[4].src = "Sponsors/liberty.jpg"

imageArray[5] = new Image()
imageArray[5].src = "Sponsors/supervalu.png"

var step = 0;

function slideShow() {
    document.getElementById('slideshow').src = imageArray[step].src
    if (step < 5)
        step++
        else
            step = 0
    setTimeout("slideShow()", 4000)
}

function RoundRobin(teams) {

    alert(teams);
    var i;
    var ret = "";
    var round;
    var numplayers = 0;
    numplayers = parseInt(teams) + parseInt(teams % 2);
    numplayers = parseInt(numplayers);
    alert(numplayers);
    var a = new Array(numplayers - 1);
    var alength = a.length;
    for (var x = 0; x < (numplayers); x++) {
        a[x] = "Team " + (x + 1);
    }
    if (numplayers != parseInt(teams)) {
        a[alength] = "BYE";
    }
    var pos;
    var pos2;
    ret = "----- ROUND #1-----
"
    for (var r1a = 0; r1a < (numplayers / 2); r1a++) {
        ret += a[r1a] + " vs. " + a[alength - r1a] + "
"
    }
    for (round = 2; round < alength + 1; round++) {
        ret += "

----- ROUND #" + round + "-----
"
        ret += a[0] + " vs. " + a[alength - (round - 1)] + "
"

        for (i = 2; i < (numplayers / 2) + 1; i++) {
            pos = (i + (round - 2))
            if (pos >= alength) {
                pos = ((alength - pos)) * -1
            } else {
                pos = (i + (round - 2))
            }

            pos2 = (pos - (round - 2)) - round
            if (pos2 > 0) {
                pos2 = (alength - pos2) * -1
            }

            if (pos2 < (alength * -1)) {
                pos2 += alength
            }
            ret += a[(alength + pos2)]
            ret += " vs. " + a[(alength - pos)] + "
"
        }
    }
    var text = document.getElementById('fixtures');
    text.innerHTML = ret;
    return ret
}

// round robin format

}

A: What's happening is that you call the function, then you assing the return value to the onclick property. For the event handler to work you need to assign a function to the property.
Wrap the call in a function expression:
document.getElementById("tableButton").onclick = function(){
  RoundRobin(teamsIn);
};


text:
Q: changing colors of HTML elements with skeleton can someone tell me how I can change for example the background-color globaly.
I made it with ''. Whitout skeleton I would do it classic with a style.css file based in css directory.
When I try to change the body entrys in the skeleton.css file, nothing happened :(
What is the to do for skeleton?
Thank you in advance.

A: Skeleton doesn't change anything about how html and css will interact. Skeleton is basically just pre-built css file. You can still include styles.css with a second link tag, i.e.
<link rel="stylesheet" href="css/skelton.css"/>
<link rel="stylesheet" href="css/styles.css"/>


text:
Q: Doxygen undocumented string value Doxygen (1.8.10) is complaining that the value of my string is not documented. Here's a minimal example that demonstrates the problem
#include <string>

struct MyStruct ///< Docs for struct
{
    std::string a; ///< Docs for a
    std::string b; ///< Docs for b
};

class MyClass ///< Docs for class
{
    static struct MyStruct instance; ///< Docs for instance
};

struct MyStruct MyClass::instance = {"firstVal", "secondVal"};

This results in the warning
/tmp/example.cpp:10: warning: Member firstVal (variable) of class MyClass is not documented.

If I reduce the struct to a single member and remove "secondVal" from the initializer, then the warning disappears, but obviously that's not a solution...

A: Just delete the extra struct. As in:
#include <string>

struct MyStruct ///< Docs for struct
{
    std::string a; ///< Docs for a
    std::string b; ///< Docs for b
};

class MyClass ///< Docs for class
{
    static struct MyStruct instance; ///< Docs for instance
};

MyStruct MyClass::instance = {"firstVal", "secondVal"};

C++ doesn't require you to use struct MyStruct and instead allows you to use just plain MyStruct. Making this tiny change makes the warning go away with doxygen 1.8.13.

A: Try to set the EXTRACT_ALL tag in the doxyfile to YES, then the warning should disappear.
Also note the comment to the EXTRACT_ALL setting:
# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in
# documentation are documented, even if no documentation was available. Private
# class members and static file members will be hidden unless the
# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.
# Note: This will also disable the warnings about undocumented members that are
# normally produced when WARNINGS is set to YES.
# The default value is: NO.

BTW one further tip:
Don't use the ///< comments for multi-line entities. The result of your documentation will look better if you comment your code this way:
/**
 * Docs for struct
 */
struct MyStruct
{
    std::string a; ///< Docs for a
    std::string b; ///< Docs for b
};

/**
 * Docs for class
 */
class MyClass
{
    static struct MyStruct instance; ///< Docs for instance
};

Otherwise, if you want to use the ///< comments, you have to put the comment after the semicolon of the declaration:
struct MyStruct
{
    std::string a; ///< Docs for a
    std::string b; ///< Docs for b
}; ///< Docs for struct

class MyClass
{
    static struct MyStruct instance; ///< Docs for instance
}; ///< Docs for class


text:
Q: open and resize an image from a folder on the server in PHP and save it back Is there anyway select an image from a folder inside the server, instead of submitting from HTML on a client side, and work on it using PHP?
Then I want to resize the image and save as a different name to the same folder on the server. This gonna be by clicking a button from client side.

A: You can use this class.
// get image for manipulate from temp folder
$image = new Image($sourcePath);
// manipulate
$image->resize($targetWidth, $targetHeight, Image::AUTO)->sharpen(1)->quality(95)->save($resultPath);


text:
Q: How do I update a table with the max value of a different table? I need to update col1 in table1 with the highest value in val in table2 that is lower than
col2 in table1.  I am trying this:

    update table1 set col1 = max(t2.val)
    from table2 t2 where t2.VAL < col2
I am getting this error:
An aggregate may not appear in the set list of an UPDATE statement.
Here is sample data

Table1
Col1    Col2
2   null
3   null
4   null
6   null
7   null
8   null
9   null
10  null

Table2
Val
1
5

after I run the query I would want it to look like this:

Table1
Col1    Col2
2   1
3   1
4   1
6   5
7   5
8   5
9   5
10  5

A: UPDATE t1
    SET col2 = (SELECT MAX(Val) FROM dbo.Table2 WHERE Val < t1.col1)
    FROM dbo.Table1 AS t1;

A: UPDATE   t1     SET
       modified = a.ddd from  t1 t  CROSS APPLY (SELECT MAX(t2.price) AS ddd  from t2 WHERE t2.price<t.val) a

lets initialize t1 (the modified field is the one that will have the max value from t2 but less than its val value)

this is your table1 (t2) with values ...

run the query : ...
UPDATE   t1     SET
       modified = a.ddd from  t1 t  CROSS APPLY (SELECT MAX(t2.price) AS ddd  from t2 WHERE t2.price<t.val) a

edit
for your values here is the result :


text:
Q: "char(a)" issue in C++ I don't know why the code below works? and why is it completed compile?
Code : b = char(a);
I wonder if it's one of the ways to use "char" or if it's a bug.
printf("Start Test\n");

int a = 0xF30;
char b = 0;
char c = 0;
char d = 0x30;
char e = 0xF30;
b = char(a);        // <- Why??
c = (char)a;

printf("%c, %c, %c, %c, %c\n", a, b, c, d, e);

printf("End Test\n");

getchar();

return 0;

Console Result
Start Test

0, 0, 0, 0, 0

End Test

A: This is covered under the section "Explicit type conversion (functional notation)" in the C++11 standard.
Given your code,
b = char(a);

is the same as
b = a;

More generally, it can be used to explicitly convert an expression to another type. E.g.
b = char(10);

Here, 10 is of type int. By using char(10), 10 is explicitly converted to char before the assignment.

A: C++ (unlike C) has more than one notation for explicit type conversions (casts).
C++ inherits C's cast notation:
int i = some_value;
char c;
c = (char)i;

It also has a functional notation:
c = char(i);

as well as several cast operators which are more restrictive than a C-style cast.
c = static_cast<char>(i);

These all (in this case) specify the same conversion.
Note that for conversions between numeric types, a cast is not necessary (and is probably a bad idea). An assignment (or a function argument, or a return statement) will perform an implicit conversion, so you can just write:
c = i;

By using a cast, you risk specifying the wrong type, resulting in an additional implicit conversion and possibly a wrong result:
c = (unsigned char)i; // explicitly converts to unsigned char,
                      // then implicitly converts to char

A: As mentioned in comments, b = char(a); It is Invalid operation in c, but valid in c++.In c++ it will be considered as a ascii value. so it is same as this notation b = (char)a;


text:
Q: Trying to implement JW Player on iOS I am a newbi in JW and can't seem to implement to simplest player. Help me, please.
I have created an html and put it in my project. in the same place with the jwplayer.flash.swf, jwplayer.html5.js, jwplayer.js
My html file looks like this (Home.html):

  <title>Title of the document</title>

in the controller class:
- (void)viewDidLoad
{
    [super viewDidLoad];
    htmlPlayerWebView=[[UIWebView alloc]initWithFrame:CGRectMake(20, 51, 674,381)];
    [self.view addSubview:htmlPlayerWebView];
}
-(void)loadVideo
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Home" ofType:@"html"];
    NSString *HTMLString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    [htmlPlayerWebView loadHTMLString:HTMLString baseURL:[NSURL URLWithString:path]];
}

The functions are called. But nothing happens.

A: I found the problem:
UIWebView doesn't have access to project files. So the jwplayer.js is not loaded.
So either load the player to some web server, or replace

with

A: You actually can access local files from within the HTML of a UIWebview. Just change your code as such:
-(void)loadVideo
{
    NSString *basePath = [[NSBundle mainBundle] bundlePath];
    NSURL *baseURL = [NSURL fileURLWithPath:basePath];

    NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"Home" ofType:@"html"];
    NSString *HTMLString = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];

    [htmlPlayerWebView loadHTMLString:HTMLString baseURL:baseURL];
}

Any relative paths in your HTML will then be referenced from your project files.

A: In the years since this question was originally posted, JWPlayer has implemented a mobile SDK for iOS, which was at first freely available, and now is maintained exclusively for Enterprise users. There is also a new "Developer Class" account which gives full access for 6 months, free.
This post, and related issues, are perhaps the main motivator for such a move; exchanging the slippery moving target of web views, with their opaque implementation details, in favor of the controlled native environment available to a framework project was a clear win.


text:
Q: Mouse hit lost on popup menu transparent background in xaml I have run into a very strange issue today:
I have a popup menu that opens when I hover above an image. The popup menu is positioned right of the image.
this popup menu is templated to look like a rectangle with a little arrow pointing to the image
the menu contains clickable elements, so I need to be able to move the mouse from the image to the menu without it closing in between, and this is where I get confused: if I move the mouse right over the tip of the arrow and then the menu, everything works fine. If I move the mouse over the transparent space between the image and the menu (above or under the arrow), the menu disappears.
Here is the template for the menu:
<Popup AllowsTransparency="True" Name="c_popup" Width="300" PlacementTarget="{Binding RelativeSource={RelativeSource TemplatedParent}}" Placement="Right">
    <Grid Background="Transparent">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="10"  />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <Path Data="M 0 10 L 10 0 10 20 Z" Stroke="#252C37" Fill="#252C37" Margin="0,18,0,0" Grid.Column="0" />

        <Grid Grid.Column="1" Background="#252C37">

            <TextBlock Text="{Binding Name}" Margin="20,10,0,0" FontSize="18" Foreground="White" HorizontalAlignment="Stretch" VerticalAlignment="Top" TextWrapping="WrapWithOverflow" />

        </Grid>
    </Grid>
</Popup>

you'll notice that I specifically put Background="Transparent" and not Null (I am aware of the effect this as on the hitTesting, see this question)
funny thing is, though: If I put Background="#01000000", it works as expected. (And I get almost what I want, since this is almost a transparent background)
but I would still like to know what is going on there...
I suspect it has something to do with the fact that this is a popupmenu. I assume WPF does something to remove the hitTesting on any surface that is transparent in a popup menu, either when the background is null (which is expected) or even if it is specifically set to transparent (not expected). Can anyone confirm this?

A: Converting my comment to an answer.
This seems to be more of a "Windows OS" issue than WPF specifically in the way AllowTransparency="True" at a Window level makes the system ignore the element for mouseover events when Background="Transparent" or Opacity="0" on the element..
A detailed explanation of this behavior can be found Here
Adding the MSDN answer just in case the link goes missing later:

Windows supports transparency at the HWND level through a feature called "layered windows".
  Layered windows are represented by a bitmap.
  The Operation System(OS) renders the bitmap whenever it needs to.
  For the OS need to respond very quickly to mouse movement, Windows uses a dedicated Raw Input Thread (RIT).
  RIT runs in the kernel and handles the singals from mouse hardware.
  RIT can scan over the HWND hierarchy to detect which window the mouse is over.
  For normal windows, the RIT checks the mouse position against the window's rectangle.
  For layered windows, the RIT looks in the bitmap that specifies the content for the window and checks the effective transparency at that location. The effective transparency can be affected by opacity, color and alpha channel.
  If the pixel is 100% transparent, the RIT skips the window and keeps looking.  This point is the reason that MouseMove event is not fired.
  If the Background of window and control are both Transparent, all the pixels that represent this control(Canvas in your example) in the layered windows are totally transparent. As described above, RIT will skip them and never send WM_MOUSEMOVE message.
  So if you want only show up the control only when the mouse is over and otherwise and the window is transparent, you have to make the control not 100% transparent.

Something to note in this case is, even though Popup is within a Window that does not have AllowTransparency="True", Popup generates a Chrome-less window itself and the AllowTransparency="True" on the Popup affect this new chromeless-Window the same way as mentioned in the MSDN link above.
If this control were just a standard control like Button/Rectangle... then just setting the Background="Transparent" would make it work fine and not have this issue.


text:
Q: problems installing openvpn client following the instructions on the official vpn page (instructions install openvpn client) in the second step:
curl -fsSL https://swupdate.openvpn.net/repos/openvpn-repo-pkg-key.pub | gpg --dearmor > /etc/apt/trusted.gpg.d/openvpn-repo-pkg-keyring.gpg
I get the following error message:
sudo curl -fsSL https://swupdate.openvpn.net/repos/openvpn-repo-pkg-key.pub | gpg --dearmor > /etc/apt/trusted.gpg.d/openvpn-repo-pkg-keyring.gpg
-bash: /etc/apt/trusted.gpg.d/openvpn-repo-pkg-keyring.gpg: Permission denied
(23) Failed writing body
Thanks in advance!!!

A: I had a similar issue recently. Use
sudo wget https://swupdate.openvpn.net/repos/openvpn-repo-pkg-key.pub
and
sudo apt-key add openvpn-repo-pkg-key.pub
Reference -
https://openvpn.net/cloud-docs/openvpn-3-client-for-linux/

A: The tutorial you posted is still valid, but as it was pointed out in the comments, you have to run the commands as superuser (I just tested sudo but it wouldn't work either).
Moreover, apt-key is mostly deprecated, so be careful with the accepted solution. If you follow the steps there, you will get a deprecation warning every time you run apt update.


text:
Q: Inserting into model from controller - Odoo 10 I need to create a form in my Odoo website so external users can register for a newsletter that is sent from my Odoo. So far I have created a website template and a controller. Thus far I have managed to display the form and do a Post as well as preload some additional many2many fields I need to fill the form but the data is not saved to the database when I hit submit. I have seen the website_portal and website_hr_recruitment models that have forms for people to fill out but I can't figure out where is the data saved and how it is done.
I include the following code from my own controller for reference:
My controller:
@http.route('/contact/register', type='http', auth='public', website='true')
def register(self, redirect=None, **post):

    areas_interest = request.env['iica_contacts.area_interest'].sudo().search([])
    topics_interest = request.env['iica_contacts.topic_interest'].sudo().search([])
    products_interest = request.env['iica_contacts.products_interest'].sudo().search([])
    countries = request.env['res.country'].sudo().search([])

    if post:
        return request.redirect('/contact/register/success')

    values = {
        'areas_interest' : areas_interest,
        'topics_interest' : topics_interest,
        'products_interest' : products_interest,
        'countries' : countries,
    }

    return request.render("iica_contacts.register", values)

My Template:
<template id="register">
<t t-call="website.layout">
  <t t-set="title">Register</t>
  <form action="/contact/register" method="post">
    <input type="hidden" name="csrf_token" t-att-value="request.csrf_token()"/>

            First name:
            <input type="text" name="first_name" class="form-control" t-att-value="first_name" />

            Last name:
            <input type="text" name="last_name" class="form-control" t-att-value="last_name" />

Location information

                    Country:
                    <select name="country_id" class="form-control">
                      <option value=""> -- Select country -- </option>
                      <t t-foreach="countries" t-as="country">
                        <option t-att-value="country.id">
                          <t t-esc="country.name" />
                        </option>
                      </t>
                    </select>

                    Company:
                    <input type="text" name="company" class="form-control" t-att-value="company" />

                    Sector:
                    <select name="sector" class="form-control">
                      <option value=""> -- Select sector -- </option>
                      <option value="1">Public</option>
                      <option value="2">Private</option>
                      <option value="3">ONG</option>
                      <option value="4">International Organization</option>
                      <option value="5">Financial</option>
                      <option value="6">Other</option>
                    </select>

                    Language:
                    <select name="sector" class="form-control">
                      <option value=""> -- Select language -- </option>
                      <option value="1">Spanish</option>
                      <option value="2">English</option>
                    </select>

Contact information

                    Email:
                    <input type="email" name="email" class="form-control" />

                    Phone number:
                    <input type="tel" name="phone" class="form-control" />

                    Contact preference:
                    <select name="contact_preference" class="form-control">
                      <option value=""> -- Select preference -- </option>
                      <option value="1">Telephone</option>
                      <option value="2">Email</option>
                      <option value="3">Text message (SMS)</option>
                      <option value="2">All of the above</option>
                      <option value="2">Dont contact me</option>
                    </select>

Products of interest

Areas of interest

Topics of interest

Products of interest

                <select name="products_interest" multiple="multiple" class="form-control">
                  <t t-foreach="products_interest" t-as="product">
                    <option t-att-value="product.id">
                      <t t-esc="product.name" />
                    </option>
                  </t>
                </select>

Areas of interest

                <select name="areas_interest" multiple="multiple" class="form-control">
                  <t t-foreach="areas_interest" t-as="area">
                    <option t-att-value="area.id">
                      <t t-esc="area.name" />
                    </option>
                  </t>
                </select>

Topics of interest

                <select name="topics_interest" multiple="multiple" class="form-control">
                  <t t-foreach="topics_interest" t-as="topic">
                    <option t-att-value="topic.id">
                      <t t-esc="topic.name" />
                    </option>
                  </t>
                </select>

            <button type="submit" class="btn btn-default btn-primary">
              Register
            </button>

  </form>
</t>

I will really appreciate any help.

A: After investigating and trying a lot of stuff I managed to do this the following way:
def register(self, redirect=None, **post):

    areas_interest = request.env['iica_contacts.area_interest'].sudo().search([])
    topics_interest = request.env['iica_contacts.topic_interest'].sudo().search([])
    products_interest = request.env['iica_contacts.products_interest'].sudo().search([])
    countries = request.env['res.country'].sudo().search([])

    values = {
        'areas_interest' : areas_interest,
        'topics_interest' : topics_interest,
        'products_interest' : products_interest,
        'countries' : countries,
    }

    if post:
        error_message, valid = self._validate_form(post)
        if valid == 1:
            self._process_registration(post)
            return request.redirect('/contact/register/success')
        else:
            return request.redirect('/contact/register/error')
    else:
        contact = request.env['iica_contacts.contact']
        values.update({
            'contact' : contact,
        })

    return request.render("iica_contacts.register", values)

The function that inserts to the model:
def _process_registration(self, post):
    request.env['iica_contacts.contact'].create({
        'name' : post.get('name'),
        'company' : post.get('company'),
        'country_id': post.get('country_id'),
        'sector' : post.get('sector'),
        'language' : post.get('language'),
        'email' : post.get('email'),
        'phone' : post.get('phone'),
        'area_interest_ids' : self._process_many2may(request.httprequest.form.getlist('areas_interest')),
        'product_interest_ids' : self._process_many2may(request.httprequest.form.getlist('products_interest')),
        'topic_interest_ids' : self._process_many2may(request.httprequest.form.getlist('topics_interest')),
    })


text:
Q: The very last part of theorem 5.4(pg.356) of TPE by Lehmann and Casella
I am struggling with the very last part of theorem 5.4(pg.356) of TPE by Lehmann and Casella.
It is the theorem that proves the inadmissibility of the James Stein Estimator dominated by the positive part James Stein Estimator.
What I am struggling with is the last part of the proof of the theorem.
The followings are the TWO PARTS that I am struggling with.
1.
I can't derive the last equality from the bottom third line of the proof.
I've carefully read the explanation(by S.Catterall Reinstate Monica) but I am
still confused whether it is possible to derive the conditional expectation of continuous random variable by treating it as discrete.
2.
Also I can't understand the bottom two lines of the proof.
I've found that it is an increasing function of the absolute value of |$\theta_1 y$|, but I can't understand how it completes the proof.
Thank you.

A: Part 1. The equality towards the end of the proof requires computing a conditional expectation $E_\theta (X_1 | X_1^2=y^2)$ where, earlier in the text, we are told that $X_1$ is normally distributed with mean $\theta_1$ and variance $1$ ($\theta_1$ being the first component of the vector $\theta$). The condition $X_1^2=y^2$ implies that either $X_1=y$ or $X_1=-y$. The conditional probability that $X_1$ takes value $y$ is equal to $\frac{f(y)}{f(y)+f(-y)}$ where $f$ is the (normal) pdf of $X_1$. So $E_\theta (X_1 | X_1^2=y^2)=y\frac{f(y)}{f(y)+f(-y)}+(-y)\frac{f(-y)}{f(y)+f(-y)}$. Substitute the formula for $f$ into this and you get the expression stated in the printed proof, namely $$E_\theta (X_1 | X_1^2=y^2)=y\frac{e^{\theta_1 y}-e^{-\theta_1 y}}{e^{\theta_1 y}+e^{-\theta_1 y}}$$
Note: this is an intuitive derivation of the conditional expectation. For a more rigorous approach see this answer. The answer uses a lemma to obtain a certain function $g$; this lemma is proved on pages 206-207 of the book Probability with Martingales.
Part 2. The computed conditional expectation is found to be an increasing function of  $|\theta_1 y|$ which is zero when $\theta_1 y=0$. This means that it must be non-negative. Finally, $$ E_\theta (\theta_1 X_1 | \hat{B})=E(E(\theta_1 X_1|\hat{B}, X_2,\cdots,X_r)|\hat{B})$$ by the tower property for conditional expectations (pages 88-89 in the above book) so $E_\theta (\theta_1 X_1 | \hat{B})$ is also non-negative, which is what they were trying to prove.


text:
Q: If $X^2$ follows the exponential distribution, how to prove that $X$ obeys what kind of distribution? If $X^2$ follows the exponential distribution, how to prove that $X$ obeys what kind of distribution?
As we all know, if $X$ follows the Rayleigh, then $X^2$ follows the exponential distribution. Otherwise, if $X^2$ follows the exponential distribution, will $X$ only obey Rayleigh distribution?

A: You need $Y=\sqrt{X}, X \sim Exp(\lambda)$, then derive CDF of $Y$:
$$
P(Y<y) = P(\sqrt{X}<y) = P(X<y^2) = P(0<X<y^2)
$$
Can you handle from here?

A: If $X^2$ follows an exponential distribution (a chi-squared distribution with $2$ degrees of freedom and a suitable scale factor), then you can conclude that $|X|$ follows the Rayleigh distribution (i.e. the chi distribution with $2$ degrees of freedom and a suitable scale factor).  You can use cumulative distribution functions to prove this.
You need to believe $X$ is non-negative to conclude this also is the distribution for $X$; if not then there are many possibilities.


text:
Q: How to replace entries in a dataframe column with ordering I have the following dataframe:

Item
Produce Group

Mango
Fruit

Spinach
Vegetable

Peach
Fruit

Squash
Vegetable

Orange
Fruit

Cauliflower
Vegetable

How do I create the following dataframe from the previous dataframe?

Item
Produce Group

Mango
Fruit1

Spinach
Vegetable1

Peach
Fruit2

Squash
Vegetable2

Orange
Fruit3

Cauliflower
Vegetable3

A: You can groupby and cumcount elements in each group:
df['Produce Group'] + df.groupby('Produce Group').cumcount().add(1).astype(str)

Output:
0        Fruit1
1    Vegetable1
2        Fruit2
3    Vegetable2
4        Fruit3
5    Vegetable3


text:
Q: AWS redirect URL with AngularJS running in Node.js server I´m trying to config a website hosted in AWS EC2 instance. But Im a bit mixed!!
I have an AngularJS application running in a Node.js server listening on port 1234. This site is deployed correctly, so when I get the url in a browser ec2-instance-public-dns:1234/app/index.html I see my site perfectly.
In the other hand, I registered a domain name in GoDaddy. I set up a Route 53 and the DNS names in GoDaddy.
I see, I also have a load balancer listening in port 80, that is redirecting to port 1234.
What I need is to link my domain with my site in the path ec2-instance-public-dns:1234/app/index.html
All this stuff is not working. How can I achieve this?

A: *

*Is there is reason why you don't have Node listen to 80 or 8080 ?

*Does the DNS redirection work ? -> Can you access your site with www.yourdomainname.com:1234 ?
-> If no, then check your dns config, you should not have to deal with port routing at that level.

*Are you using Linux as your EC2 instance ? If yes, reroute port 80 toward port 1234 as explained here (http://www.cyberciti.biz/faq/linux-port-redirection-with-iptables/).

That how I do it, hope that helps.


text:
Q: Gracefully stopping generators Consider the following code:
Loop::run(function() {
    Loop::onSignal(SIGINT, function () use ($w) {
        echo "Caught SIGINT! exiting ...\n";
        Loop::stop();
    });

    while([$jobId, $jobData] = yield $beanstalk->reserve()) {
        $response = yield $httpClient->send($request);
        yield $beanstalk->delete($jobId);
    }
});

To my understanding, when this code receives a SIGINT, the callback in Loop::onSignal will be executed on the next tick and thus the loop will stop and the program exit.
In this case, if $httpClient->send() in the while loop has not yet finished, the next line will not be executed and the Beanstalk message will not get deleted. The Beanstalk job will then be retried and that might cause a problem if the HTTP request is not idempotent. We can substitute an HTTP request with a database call.
Is there a way to tell the loop to not execute new generators and wait for the generators in-progress to finish when a SIGINT is received?
I've been trying to wrap my head around this but couldn't find a solution.

A: There's no such option, but you can achieve what you want in your simple application pretty easily by adding a flag.
Loop::run(function() {
    $running = true;

    Loop::onSignal(SIGINT, function () use (&$running) {
        echo "Caught SIGINT! exiting ...\n";
        $running = false;
    });

    while($running && [$jobId, $jobData] = yield $beanstalk->reserve()) {
        $response = yield $httpClient->send($request);
        yield $beanstalk->delete($jobId);
    }
});

This will simply continue with the current request and exit afterwards.


text:
Q: Why has the feld become undefined? I attempted to building a class for a slider but when I try to use its feld they are undefined

class Slider {
    constructor() {
        this.nextButton = document.getElementById("next");
        this.previousButton = document.getElementById("previous");
        this.imageDivs =document.querySelectorAll(".img-continer .img");
        this.index = 0;
    }

    SlideNext() {
        console.log(this.imageDivs); //the output is undefined;
        this.index++;
    }

    SlidePrevious() {

    }

    init() {
        this.nextButton.addEventListener("click" , this.SlideNext);
        this.previousButton.addEventListener("click", this.SlidePrevious);
    }
}


text:
Q: What is the reason to use "should be" instead of "is" here? I read a sentence as below

Now, these results are not quite as bad as they sound. Although such adversarial examples are common, they're also unlikely in practice. Nonetheless, it is distressing that we understand the theory so poorly that this kind of result should be a recent discovery. Of course, a major benefit of the results is that they have stimulated much followup work.

This paragraph comments on an experiment of the theory. This theory works very well for most (i.e., more than 98%) examples, but fails on some so-called adversarial examples. People don't understand why the theory fails on them, because people thought they are easy examples.
I have a shallow feeling about the meaning of the sentence:

We understand the theory very poorly. This fact is distressing.

First, I don't understand why this kind of result should be a recent discovery can emphasize we understand the theory poorly. Then, I'm not clear why should be is used here. What is the difference between should be and is in this context ?

A: I'm convinced that this is just a poorly worded sentence. I think the author means:

Nonetheless, it is distressing that we understand the theory so poorly that this kind of result was discovered only recently. That is, it should have been discovered a long time ago.

I think that the author's usage of "should be" was a failed attempt to (unnecessarily) complicate the sentence. Academic papers often do this.


text:
Q: SharePoint Client Object Model and the PredicateBuilder I am trying to dynamically build a predicate to only hydrate a subset of lists. But I am getting and error.
var predicate = PredicateBuilder.False<SP.List>();
var listTitles = new[] { "List One", "List Two" };
foreach (var listTitle in listTitles)
{
    predicate = predicate.Or(x => x.Title == listTitle);
}
var lists = ctx.LoadQuery(ctx.Web.Lists.Where(predicate));
ctx.ExecuteQuery();

Error: The expression x is not supported
What am I missing?


text:
Q: Exponential decrease I am stuck getting an exponential decrease from 100 to 0.
This is what I managed to get:

var time_data = [];
var value_data = [];
var left = 100;
var  i = 1;

while (i <= 30)
{
 left = left-Math.pow(i,i);

 if(left < 0)
 {
  left = 0;

 }

 value_data.push(left);
 time_data.push(i);

 i+=1;
}

var canvas = document.getElementById('myChart');
var data = {
    labels: time_data,
    datasets: [
        {
            label: "My First dataset",
            fill: false,
            lineTension: 0.1,
            backgroundColor: "rgba(75,192,192,0.4)",
            borderColor: "rgba(75,192,192,1)",
            borderCapStyle: 'butt',
            borderDash: [],
            borderDashOffset: 0.0,
            borderJoinStyle: 'miter',
            pointBorderColor: "rgba(75,192,192,1)",
            pointBackgroundColor: "#fff",
            pointBorderWidth: 1,
            pointHoverRadius: 5,
            pointHoverBackgroundColor: "rgba(75,192,192,1)",
            pointHoverBorderColor: "rgba(220,220,220,1)",
            pointHoverBorderWidth: 2,
            pointRadius: 5,
            pointHitRadius: 10,
            data: value_data,
        }
    ]
};

var option = {
 showLines: true
};
var myLineChart = Chart.Line(canvas,{
 data:data,
  options:option
});

function adddata(){
 myLineChart.data.datasets[0].data[7] = 50;
  myLineChart.data.labels[7] = "test add";
  myLineChart.update();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.min.js"></script>
<canvas id="myChart" width="400" height="250"></canvas>

while (i <= 30)
{
    left = left-Math.pow(i,i);

    if(left < 0)
    {
        left = 0;

    }

And this is what I need to get

The problem is that don't know how to get a reverse version of Math.pow.
I would appreciate any help.

A: According to the graph, what you want is to start at (0,10) and then divide y by 2 every time x is incremented by 1.
Try this:
var time_data = [];
var value_data = [];

for (let i=0;i<=10;++i) {
    time_data.push(i);
    value_data.push(10/Math.pow(2,i));
}

This can be mathematically written as a decreasing exponential: 10 * 2^(-x) or if you prefer 10 * exp(-ln(2) * x)

A: If you're looking for exponential decay, do you need to use Math.pow()?  What's wrong with something like
left = left*factor

Where 0 < factor < 1?
Looking at some documentation for Math.pow(), the two arguments are base and exponent.  In your example, left - 30^30 doesn't make much sense because it will result in a vastly negative number and then default to 0.
An expression using Math.pow() that will give the ith term of an exponential decay sequence is
start_value * Math.pow(factor, i)
Where again, 0 < factor < 1.  The reduction in the value that you start with is compounded exponentially over each iteration.


text:
Q: Node JS - Should i do "return cb(..)" or first cb(..) and then return? This may be a dumb question but I just want to know the implications on doing this:
Whenever I get an error or I want to finish some function flow I have instructions such as:
if(err) {
    cb(err);   // or for example res.json({...});
    return;
}

However I've seen some codes with the following format:
if(err) {
    return cb(err);
}

Are there any memory or other kind of risks on doing that? Carrying on the function value over all the functions?
Which is the recommended approach?

A: If the host function and the caller is not expecting a return value, then either of your two choices will execute identically.  The second one:
return cb(err);

is often done purely for short-hand reasons (putting the return on the one line).  Personally, I don't like this shorthand because when one reads this code, it implies that cb() is returning a value that you want to return from the host function, but that isn't the case at all.
So, I prefer:
if(err) {
    cb(err);   // or for example res.json({...});
    return;
}

or even sometimes:
if(err) {
    cb(err);   // or for example res.json({...});
} else {
    // other code here
}

Because both of these make it a lot clearer that there is no return value intended from the host function or from the callback.  But, this my opinion about code clarity - there is no material difference in execution.

Are there any memory or other kind of risks on doing that? Carrying on the function value over all the functions?

A plain return statement or a function that just ends without any return statement returns undefined.  If the cb() returns undefined, thenreturn cb()also returnsundefined` from the host function.  So, there should be no difference in return value there either.  With no difference in return value, there should be no difference in memory usage.
The return cb() code does allow the callback to return a value that also becomes the return value of the host function. If that's what you want, then you would have to code it this way, but that is typically not what you're intending so using return cb() allows the caller to perhaps use the callback return value in a way you don't intend which you might inadvertently break in the future because it wasn't an intended feature.


text:
Q: android expandablelistview, expand the view only on click of group indicator, open new activity if clicked any where but groupindicator I have a ExpandableListView on my Activity, where group contains image and name, while child contains variant of group (name, id etc). Regardless I click on the expand/collapse button, or on the any where in group, it expands/collapses always. What I want, the list to expand/collapse only if user clicks on the indicator. How can I do this? For clicking on the TextView, I want to open the different activity. Unfortunately OnGroupClickListener does not provide this info.
Can anyone help me on this?
Thanks

A: You can do that by doing some modification in your custom Adapter getGroupView method  and adding two more method in your custom Adapter which will be called depending on the view clicked. Here I am posting an example code:
    //Add these two methods in your Custom Adapter
    public void OnIndicatorClick(boolean isExpanded, int position){

     }

    public void OnTextClick(){

    }

    //this is the getGroupView code
    @Override
    public View getGroupView(final int groupPosition, final boolean isExpanded,
            View convertView, ViewGroup parent) {
        String headerTitle = (String) getGroup(groupPosition);
        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.list_group, null);
        }

        TextView lblListHeader = (TextView) convertView
                .findViewById(R.id.lblListHeader);

        lblListHeader.setText(headerTitle);

        lblListHeader.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(_context, "text Clicked", Toast.LENGTH_LONG).show();

            }
        });

        ImageView indicator = (ImageView) convertView.findViewById(R.id.imageview_list_group_indicator);
        indicator.setSelected(isExpanded);
        indicator.setTag(groupPosition);

        indicator.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = (Integer)v.getTag();
                Toast.makeText(_context, "Indicator Clicked", Toast.LENGTH_LONG).show();
                OnIndicatorClick(isExpanded,position);

            }
        });
        return convertView;
    }

And now from the Activity you can call the Custom Adapter like as below code which will override those two methods which we have added in Custom Adapter
ExpandableListAdapter listAdapter = new ExpandableListAdapter(MainActivity.this,
                    listDataHeader, childDataList){
       @Override
       public void OnIndicatorClick(boolean isExpanded, int position) {
          if(isExpanded){
             expandableListView.collapseGroup(position);
          }else{
             expandableListView.expandGroup(position);
          }
      }

      @Override
      public void OnTextClick() {
          //Do whatever you want to do on text click
      }
 };

 expandableListView.setAdapter(listAdapter);

A: Just set setOnGroupClickListener() to your ExpandableListView and return true, Like :
@Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
    return true;
}

this will disable click of group and then set onclicklistener() on which you want to expand group.


text:
Q: Parsing through an object not an array for values Here's what I have....
settings: Object
color: "#858789"
cursor: "cursors/coin.png"
height: 100
image1: "images/slide3.png"
image2: "images/slide5.png"
image3: "images/slide5.png"
image4: "images/slide2.png"
image5: "images/slide7.png"
image6: "images/slide6.png"
image7: "images/slide6.png"
image8: "images/slide1.png"
image9: "images/slide1.png"
imageCover: "images/scratchimg2.gif"
overlay: "none"
realtimePercent: true
scratchDown: null
scratchMove: function (e, percent)
scratchUp: null
size: 10
width: 100

What I NEED/WANT to do is simply access the images...
I'm using UNDERSCORE to filter through and populate an array with ONLY image1 - image9.  The rest of the junk I could care less about.
Any ideas?
Here's my underscore code:
        //Populate the image array
        imgID = "image" + (parseFloat(i) + 1);

        var imgName = _.filter({imgID: "images/"}, function(imgnmid) {

            imgArray.push(imgnmid)
            return imgnmid = "images/";

        });

Yeah, I know, it's a mess...
This is inside a closure function
like this:
 (function($)
 {
   $.fn.someFuncName = function(option, settings)
   {

    .....

  }

})(Jquery);

thanks...

A: How about this? Fairly simple iteration over the object's keys. You could probably use underscore as well, but I don't think you need it.
Live Demo
JS
var obj = {
    settings: {},
    color: "#858789",
    cursor: "cursors/coin.png",
    height: 100,
    image1: "images/slide3.png",
    image2: "images/slide5.png",
    image3: "images/slide5.png",
    image4: "images/slide2.png",
    image5: "images/slide7.png",
    image6: "images/slide6.png",
    image7: "images/slide6.png",
    image8: "images/slide1.png",
    image9: "images/slide1.png",
    imageCover: "images/scratchimg2.gif",
    overlay: "none",
    realtimePercent: true,
    scratchDown: null,
    scratchMove: function (e, percent){},
    scratchUp: null,
    size: 10,
    width: 100
};

function extractImages(obj){
    var imgArray = [],
        num = 0;

    //Iterate over the object's keys (no need for underscore to do this).
    for(var key in obj){

        //http://stackoverflow.com/a/10003709/402706
        //Get the number off the key (if there is one)
        num = parseInt(key.replace( /^\D+/g, ''), 10);

        //is the text 'image' part of the key and is number 1-9
        if(key.indexOf('image') > -1 && num > 0 && num < 10){
            imgArray.push(obj[key]);
        }
    }
    return imgArray;
}

alert(extractImages(obj));

A: You can do this:
var i = 1;
_.filter(images, function (value, index) { // images is your full object
    if ( 'image' + i == index ) {
        imgArray.push(value); // push value
        ++i;
    }
});

Demo


text:
Q: Parsing string using regexp_extract using pyspark I am trying to split the string to different columns using regular expression
Below is my data
decodeData = [('M|C705|Exx05','2'),
('M|Exx05','4'),
('M|C705 P|Exx05','6'),
('M|C705 P|8960 L|Exx05','7'),('M|C705 P|78|8960','9')]

df = sc.parallelize(decodeData).toDF(['Decode',''])

dfNew = df.withColumn('Exx05',regexp_extract(col('Decode'), '(M|P|M)(\\|Exx05)', 1)).withColumn('C705',regexp_extract(col('Decode'), '(M|P|M)(\\|C705)', 1)) .withColumn('8960',regexp_extract(col('Decode'), '(M|P|M)(\\|8960)', 1))
dfNew.show()

Result
+--------------------+---+-----+----+-----+
|              Decode|   |Exx05|C705| 8960|
+--------------------+---+-----+----+-----+
|        M|C705|Exx05 | 2  |     |   M|    |
|             M|Exx05 | 4  |    M|    |    |
|      M|C705 P|Exx05 | 6  |    P|   M|    |
|M|C705 P|8960 L|Exx05| 7  |    M|   M|   P|
|    M|C705 P|78|8960 | 9  |     |   M|    |
+--------------------+---+-----+----+-----+

Here I am trying to extract the Code for string Exx05,C705,8960 and this can fall into M/P/L codes
eg: While decoding 'M|C705 P|8960 L|Exx05' I expect the results as L M P in respective columns. However I am missing some logic here,which I am finding difficulty to crack
Expected results
  +--------------------+---+-----+----+-----+
    |              Decode|   |Exx05|C705| 8960|
    +--------------------+---+-----+----+-----+
    |        M|C705|Exx05 |   |    M|   M|    |
    |             M|Exx05 |   |    M|    |    |
    |      M|C705 P|Exx05 |   |    P|   M|    |
    |M|C705 P|8960 L|Exx05|   |    L|   M|   P|
    |    M|C705 P|78|8960 |   |     |   M|   P|
    +--------------------+---+-----+----+-----+

When I am trying to change  the reg expression accordingly , It works for some cases and it wont  work for other sample cases, and this is just a subset of the actual data I am working on.
eg: 1. Exx05 can fall in any code M/L/P and even it can fall at any position,begining,middle,end etc

*One Decode can only belong to 1 (M or L or P) code per entry/ID ie M|Exx05 P|8960 L|Exx05 - here Exx05 falls in M and L,This scenario will not exist.

A: You can add ([^ ])* in the regex to extend it so that it matches any consecutive patterns that are not separated by a space:
dfNew = df.withColumn(
    'Exx05',
    regexp_extract(col('Decode'), '(M|P|L)([^ ])*(\\|Exx05)', 1)
).withColumn(
    'C705',
    regexp_extract(col('Decode'), '(M|P|L)([^ ])*(\\|C705)', 1)
).withColumn(
    '8960',
    regexp_extract(col('Decode'), '(M|P|L)([^ ])*(\\|8960)', 1)
)

dfNew.show(truncate=False)
+---------------------+---+-----+----+----+
|Decode               |   |Exx05|C705|8960|
+---------------------+---+-----+----+----+
|M|C705|Exx05         |2  |M    |M   |    |
|M|Exx05              |4  |M    |    |    |
|M|C705 P|Exx05       |6  |P    |M   |    |
|M|C705 P|8960 L|Exx05|7  |L    |M   |P   |
|M|C705$P|78|8960     |9  |     |M   |P   |
+---------------------+---+-----+----+----+

A: What about we use X(?=Y) also known as lookahead assertion. This ensures we match X only if it is followed by Y
from pyspark.sql.functions import*
dfNew = df.withColumn('Exx05',regexp_extract(col('Decode'), '([A-Z](?=\|Exx05))', 1)).withColumn('C705',regexp_extract(col('Decode'), '([A-Z](?=\|C705))', 1)) .withColumn('8960',regexp_extract(col('Decode'), '([A-Z]+(?=\|[0-9]|8960))', 1))
dfNew.show()

+--------------------+---+-----+----+----+
|              Decode|  t|Exx05|C705|8960|
+--------------------+---+-----+----+----+
|        M|C705|Exx05|  2|     |   M|    |
|             M|Exx05|  4|    M|    |    |
|      M|C705 P|Exx05|  6|    P|   M|    |
|M|C705 P|8960 L|E...|  7|    L|   M|   P|
|    M|C705 P|78|8960|  9|     |   M|   P|
+--------------------+---+-----+----+----+


text:
Q: Dynamically loading js, css files by html tag data attributes Can we realize dynamically loading, of js, css and other files, process?
By getting all needed info (what we must to load) from html tags data attributes?
For example:

        <title>Our app</title>

                Header

                Body

                Footer

So, maybe you have some ideas how do it in best way? With the best performance and flexibility.
Or I just need to use require js, and don't worry about some "new things"?
If just require js, then how do it best with this js plugin? To load all stuff most dynamically?
And how solve problem with js async, defer loding? Where some scripts must be loaded in specific order.
Here is my continued version 2 of current question: https://stackoverflow.com/questions/34413940/dynamically-load-js-files-by-html-data-attr-dependencies

A: Following are few ways to load scripts dynamically:

*

*Javascript: Write a custom load function.

*jQuery: $.getScript(). For css refer SO-Post.

*require.js: require(moduleName)

*ECMA 6: import
Following is a pure javascript function to load scripts dynamically:
function(url, callback) {
  var scripts = utils.getLoadedScripts(); // Read all scripts and push names in array.
  var lastIndex = url.lastIndexOf("/");
  var isLoaded = false;
  scripts.forEach(function(row, index) {
    if (row == url.substring(lastIndex + 1)) {
      isLoaded = true;
      return;
    }
  });
  if (!isLoaded) {
    //$(".reveal").addClass("loading");
    // Adding the script tag to the head as suggested before
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;
    script.name = "url";

    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;

    // Fire the loading
    head.appendChild(script);
  }
};

A: You could make use of web workers in your case. You can process the code asynchronously to do the task asynchronously.
Main script:
var worker = new Worker('doWork.js');

worker.addEventListener('message', function(e) {
  console.log('Worker said: ', e.data);
}, false);

worker.postMessage(); // Starts the worker to work;

doWork.js (the worker):
self.addEventListener('message', function(e) {
  self.postMessage("Hi, loaded async."); // send the data via postMessage to main script.
}, false);

So, what it means you can put your logic inside doWork.js and put the scripts asynchronously to the user's screen.