text:
Q: Failing boot, accessing windows repair or factory reset on Windows 8.1 dell laptop So my 8.1 dell laptop decided he doesn't want to boot anymore.
When it's trying to boot normally, I see windows sad-face-blue-screen for 100ms and then it restarts and loads automatic repair.
The automatic repair doesn't actually load and I'm stuck with a black screen with the cursor working, but nothing more.
Trying to go into advanced boot using F8, Shift+f8, Fn+F8, before and after the dell logo appears - all failed. It's just keep trying to boot or trying to go into automatic repair window without success.
I ran dell diagnostics tests and everything passed successfully with no errors or issues - so the hardware is good.
Also checked the bios and changed the Function key configuration from Multimedia to Function (and backwards) but it didn't help.
Searched google for 3 hours or so trying to understand whats going on.
I'm pretty experienced with PCs and IT but never faced anything like that...
Will be glad to get some advices! Thank you!

A: You can download a Windows 8.1 ISO (if you don't have installation media) and put it to USB for example.
Create Windows 8.1 installation media
You can try fixing boot using "start-up repair" from USB or try a quick fix
from recovery console:
bcdboot c:\windows

where c:\windows should exist else change drive letter accordingly.


text:
Q: Slack API: how to add `users:read` scope to a bot token I have a bot token (begins with xoxb) and am trying to make a request to https://slack.com/api/users.list which is returning a response of {'ok': False, 'error': 'missing_scope', 'needed': 'users:read'...}
I can't seem to find how to add this missing scope to the provided list of scopes my bot token has already, nor anything indicating something like "bot token cannot be used for this request".
Any advice on how to make the above request would be useful.

A: You can add new scopes to your app from the OAuth & Permissions page on the developer configuration site (https://api.slack.com/apps). Make sure to re-install the app after adding new scopes.

A: You can add the permission directly to the apps manifest file in YAML or JSON format as so:
...other stuff
"oauth_config": {
            "scopes": {
                "bot": [
                   ...other Permissions
                    "users:read"
                ]
            }
        },

You will need to reinstall to workspace after making changes

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sqlite3 window frame partition by datetime not working I'm struggling with a window frame coding with Python's sqlite3. Basic I have this dataframe:

And I want to group all the clients (buy and sell) made in the same day and week.
I'm working with the follow sqlite3 code:
pd.read_sql_query("""SELECT strftime('%Y-%m-%d', execution_time) AS dia,
                            COUNT(customer_id) AS cons_dia,
                            SUM(cons_dia) OVER
                                PARTITION BY dia
                                ROWS BETWEEN 7 PRECEDING AND CURRENT ROW) AS seven_day
                        FROM trades
                        ORDER BY dia DESC;""", conn)

I'm not sure what am I doing wrong, it says there is a problem around "dia" (I think it means the line PARTITION BY dia. Sqlite3 does not recognize daytime, that's why I need to to the strftime('%Y-%m-%d', execution_time) in the first row.
Thank you for the help!

A: The derived columns cons_dia and dia can't be used in the same SELECT statement.
Instead you should use the expressions from which they are derived:
SELECT date(execution_time) AS dia,
       COUNT(customer_id) AS cons_dia,
       SUM(COUNT(customer_id)) OVER (
         ORDER BY date(execution_time)
         ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
       ) AS seven_day
FROM trades
GROUP BY dia
ORDER BY dia DESC;

Note that you need an ORDER BY clause inside the OVER() clause of the SUM() window function and not a PARTITION BY clause, which should be extended to 6 rows before the current row if you want a 7 day window.
Also, this will work only if there are no gaps between the dates in the table.


text:
Q: How can ISO 9660 coexist with a Linux filesystem on a Live CD partition? I'm confused by this.  My understanding is that a live CD is sometimes accessed through the ISO 9660 driver (like when you're accessing the file without booting), but obviously a different filesystem is used when the system is booted up.  Let's take for example a Linux Live CD with the Ext3 filesystem that is to be accessible by Windows when not booting.  When Windows accesses it, it needs to have some kind of formatting that Windows can read; I assume this would be ISO 9660.  But to be bootable, the partition needs to be formatted as a Linux filesystem.  How can a partition be formatted as both an ISO 9660 filesystem and a Linux filesystem?  I know there's something fundamental that I'm getting wrong here, but this isn't the sort of question you can just Google and expect to get an answer.

A:
But to be bootable, the partition needs to be formatted as a Linux filesystem

Well, for one, no – it just needs to be a filesystem understood by Linux and capable of storing basic POSIX permission bits. ISO 9660 with the Rock Ridge extensions would do the job. (So would NTFS with ntfs-3g, or the weird "umsdos" in the early days.)
But for most live CDs, the OS root filesystem isn't directly kept on the CD – it's inside a image file (more commonly squashfs, not ext3) which is mounted using losetup.
If you run findmnt inside a running live CD, you'll see that / is some kind of overlayfs/unionfs which has a squashfs image as the lower layer (containing the read-only files), and a tmpfs/ramdisk as the upper layer (containing volatile changes).


text:
Q: Removing an attribute from a parent element but not a child element I want to remove the href attribute from the second li but not the child li's, how can that be done?
At the moment it's removing the attribute from the second li and the li with "Anaesthesia Breathing Systems" in it.
Where am I going wrong?
Here's my jquery:
$('.primary-menu-1 li:nth-child(2) > a').removeAttr('href');

Here's the menu's html (it's generated by Wordpress):

    Home

    Products

          Airway Management

          Anaesthesia Breathing Systems

          Anaesthesia Components

          Breathing Filters

          Oxygen & Aerosol Therapy

          Ventilator Breathing Systems

          Resuscitation

          Suction

          Urology

A: You need to change your selection from:
$('.primary-menu-1 li:nth-child(2) > a')

to:
$('.primary-menu-1 > li:nth-child(2) > a')

Child Selector: ("parent > child")

Select all the a elements having the href attribute belonging to the child ul/li. Hence you can get the second one:

$('.primary-menu-1 > li:nth-child(2) > a').addClass('red');
.red {
  background-color: red;
}

        Home

        Products

                    Airway Management

                    Anaesthesia Breathing Systems

                    Anaesthesia Components

                    Breathing Filters

                    Oxygen & Aerosol Therapy

                    Ventilator Breathing Systems

                    Resuscitation

                    Suction

                    Urology

A: Try this:
$('.primary-menu-1 > li:nth-child(2) > a').removeAttr('href');


text:
Q: Python PCA on Matrix too large to fit into memory I have a csv that is 100,000 rows x 27,000 columns that I am trying to do PCA on to produce a 100,000 rows X 300 columns matrix. The csv is 9GB large. Here is currently what I'm doing:
from sklearn.decomposition import PCA as RandomizedPCA
import csv
import sys
import numpy as np
import pandas as pd

dataset = sys.argv[1]
X = pd.DataFrame.from_csv(dataset)
Y = X.pop("Y_Level")
X = (X - X.mean()) / (X.max() - X.min())
Y = list(Y)
dimensions = 300
sklearn_pca = RandomizedPCA(n_components=dimensions)
X_final = sklearn_pca.fit_transform(X)

When I run the above code, my program is killed while doing the .from_csv in step. I've been able to get around that by spliting the csv into sets of 10,000; reading them in 1 by 1, and then calling pd.concat. This allows me to get to the normalization step (X - X.mean()).... before getting killed. Is my data just too big for my macbook air? Or is there a better way to do this. I would really love to use all the data I have for my machine learning application.

If i wanted to use incremental PCA as suggested by the answer below, is this how I would do it?:
from sklearn.decomposition import IncrementalPCA
import csv
import sys
import numpy as np
import pandas as pd

dataset = sys.argv[1]
chunksize_ = 10000
#total_size is 100000
dimensions = 300

reader = pd.read_csv(dataset, sep = ',', chunksize = chunksize_)
sklearn_pca = IncrementalPCA(n_components=dimensions)
Y = []
for chunk in reader:
    y = chunk.pop("virginica")
    Y = Y + list(y)
    sklearn_pca.partial_fit(chunk)
X = ???
#This is were i'm stuck, how do i take my final pca and output it to X,
#the normal transform method takes in an X, which I don't have because I
#couldn't fit it into memory.

I can't find any good examples online.

A: Try to divide your data or load it by batches into script, and fit your PCA with Incremetal PCA with it's partial_fit method on every batch.
from sklearn.decomposition import IncrementalPCA
import csv
import sys
import numpy as np
import pandas as pd

dataset = sys.argv[1]
chunksize_ = 5 * 25000
dimensions = 300

reader = pd.read_csv(dataset, sep = ',', chunksize = chunksize_)
sklearn_pca = IncrementalPCA(n_components=dimensions)
for chunk in reader:
    y = chunk.pop("Y")
    sklearn_pca.partial_fit(chunk)

# Computed mean per feature
mean = sklearn_pca.mean_
# and stddev
stddev = np.sqrt(sklearn_pca.var_)

Xtransformed = None
for chunk in pd.read_csv(dataset, sep = ',', chunksize = chunksize_):
    y = chunk.pop("Y")
    Xchunk = sklearn_pca.transform(chunk)
    if Xtransformed == None:
        Xtransformed = Xchunk
    else:
        Xtransformed = np.vstack((Xtransformed, Xchunk))

Useful link

A: PCA needs to compute a correlation matrix, which would be 100,000x100,000. If the data is stored in doubles, then that's 80 GB. I would be willing to bet your Macbook does not have 80 GB RAM.
The PCA transformation matrix is likely to be nearly the same for a reasonably sized random subset.


text:
Q: Error with homestead when try to vagrant up Actually I'm trying to use Laravel Homestead on Windows.
When I try to make the vagrant up I get this error:
C:/Users/Lluis/Homestead/scripts/homestead.rb:125:in `configure': undefined method `each' for "\u00D4\u00C7\u00F6 ~/.ssh/id_rsa":String (NoMethodError)
        from C:/Users/Lluis/Homestead/Vagrantfile:35:in `block in <top (required)>'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-2.0.1/lib/vagrant/config/v2/loader.rb:37:in `load'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-2.0.1/lib/vagrant/config/loader.rb:125:in `block (2 levels) in load'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-2.0.1/lib/vagrant/config/loader.rb:119:in `each'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-2.0.1/lib/vagrant/config/loader.rb:119:in `block in load'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-2.0.1/lib/vagrant/config/loader.rb:116:in `each'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-2.0.1/lib/vagrant/config/loader.rb:116:in `load'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-2.0.1/lib/vagrant/vagrantfile.rb:28:in `initialize'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-2.0.1/lib/vagrant/environment.rb:810:in `new'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-2.0.1/lib/vagrant/environment.rb:810:in `vagrantfile'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-2.0.1/lib/vagrant/environment.rb:556:in `host'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-2.0.1/lib/vagrant/environment.rb:214:in `block in action_runner'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-2.0.1/lib/vagrant/action/runner.rb:33:in `run'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-2.0.1/lib/vagrant/environment.rb:543:in `hook'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-2.0.1/lib/vagrant/environment.rb:792:in `unload'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-2.0.1/bin/vagrant:141:in `ensure in <main>'
        from C:/HashiCorp/Vagrant/embedded/gems/gems/vagrant-2.0.1/bin/vagrant:141:in `<main>'

I read in others questions it's a error cause can't found the .ssh files.
I check my homestead.yaml file but think all it's good I will put here the file:
---
ip: "192.168.10.10"
memory: 2048
cpus: 1
provider: virtualbox

authorize: c:/Users/Lluis/.ssh/id_rsa.pub

keys:
     — c:/Users/Lluis/.ssh/id_rsa

folders:
    - map: d:/Homestead_Projects
      to: /home/vagrant/code

sites:
    - map: homestead.app
      to: /home/vagrant/code/Laravel/public

databases:
    - homestead

How can I fix the error? Someone see some error on homestead.yaml file?
Thanks

A: Check if in home directory ~, There is an old directory .vagrant and .vagrant.d, you have to delete these and add the laravel/homestead box again.
cheers!


text:
Q: Is it possible to change the font in cmd for one app and retain the default font for other programs? I want to change the default font for a console text editor I am using on Windows. Looking on the internet, it seems I need to change cmd's font by right-clicking the title bar. However, that changes the font for all programs that use cmd. I want to change the font only for the Text editor, and retain the default font for other apps. How do I achieve this?

A: You can create a shortcut of CMD and then set the settings on exactly that shortcut. Right click properties. So you have the changed font / font-color settings only for that shortcut and retain the default setting for the other ways of opening CMD (e.g. startmenu, run dialog, etc.). But I'm not sure if this sufficiently answers your question.

PS.: Sorry it's the German properties dialog but it should work the same for the English version.


text:
Q: Nested inner joins in linq to sql? After quick overview I didn't find how to deal with linq to sql if I have several nested inner joins.
That's what I'd like to have in linq
SELECT Booking.BookingId, Booking.EventId, Booking.StartDate, Event.Name, Person.FirstName
FROM Booking
    INNER JOIN Event
        INNER JOIN Asset
        ON Asset.AssetId = Event.AssetId
        INNER JOIN Person
        ON Person.PersonId = Event.ContactPersonId
    ON Event.EventId = Booking.EventId AND Event.State = 4

Does anyone know how to translate it to LINQ?
Thanks.

A: var q1= from a in booking,b in event,c in asset, d in person where a.eventid=b.eventid and b.state=4 and c.assetid = b.assetid and b.contactpersonid=d.personid select a,b,c,d

you can replace a,b,c,d at then with the column names you want
another way is to use the join keyword:
var w1= from a in booking join b in event on a.eventid equals b.eventid join c in asset on ...

A: var query = from b in context.Bookings
    from e in context.Events
    join a in context.Assets on e.AssetId equals a.AssetId
    join p in context.People on e.ContactPersonId equals p.PersonId
    where e.State == (byte)States.Approved && e.EventId == b.EventId
    select new { EventName = e.Name, BookingDate = b.StartDate };


text:
Q: jquery then and fetch src - upload images to server I want to pass a list of image files to the server at once.
This is my code, where the function srcToFile is for creating a new file as image.
var formData = new FormData();

// Iterate all td's in second column
$("#table-image tbody tr:not(:first-child)").each(function (index, value) {
  var blob = value.cells[4].innerText;
  var fileName = (index + 1) + ".jpg";
  srcToFile(blob, fileName, "image/jpeg")
    .then(function (file) {
      formData.append("file", file);
      alert(formData.getAll("file").length); ** // I know that I can use aJax jquery to pass one by one at here**
    }, function (error) {
      //
    });
});

function srcToFile(src, fileName, mimeType) {
    return (fetch(src)
        .then(function (res) { return res.arrayBuffer(); })
        .then(function (buf) { return new File([buf], fileName, { type: mimeType }); })
    );
}

How can I use formData in this case?

A: Put all the promises returned by srcToFile into an array, then use $.when() to wait for all of them.
var promises = $("#table-image tbody tr:not(:first-child)").map(function (index, value) {
  var blob = value.cells[4].innerText;
  var fileName = (index + 1) + ".jpg";
  return srcToFile(blob, fileName, "image/jpeg")
    .then(function (file) {
      formData.append("file[]", file);
    }, function (error) {
      //
    });
}).get();
$.when(promises).then(function() {
    alert(formData.getAll("file[]").length);
    return $.ajax({
        url: "yourURL",
        type: "post",
        processData: false,
        data: formData
    });
}).then(...)


text:
Q: How to run dmalloc in linux(OPENSUSE)? file : main.c
to run dmalloc I have done the following step.
1)   gcc -ldmalloc -o test main.c
2)  function dmalloc { eval command dmalloc -b $*; }
dmalloc -l logfile -i 100 low

3)  ./test
where  will I get the result?
Even i could not get the logfile.

A: make sure that your environment actually contains the DMALLOC_OPTIONS variable before running the program. Different shells may be different with the eval. Make sure you actually do a malloc in your test program, else it may not have initialized properly.


text:
Q: How to Optimize PDF and PCL creation in C# using active reports3 I am working on Optimizing performace for one my batch process at work.
This batch process reads data from couple of tables,
Person --> employment
Assemble the domain objects
 Person
{
//person fields
List<IEmployment> EmploymentList
}
IEmployment
{
//employment fields
}

, create PDF and PCL files.
I need to create a PCL and PDF file for each person.
Currently I am looping through each peson, creating instance of ActiveReport setting person as data source to ActiveReport, Creating PCL, creating PDF and exit.
I am loading 500 person records at a time, create pcl's and pdf's and read next 500 unprocessed person records.
This is taking around 5 mins to complete 500 records, at times we might have 30,000 records to process which is equating to 5 hrs. I am trying to optimize if. Please let me know if there is a better way of generating this bulk pdf's and pcl's.


text:
Q: Проблема с загрузкой товаров facebook pixel имеется проблема по автозагрузке товаров в facebook, необходимые микроданные подгружены через open graph теги, но в личном кабинете отображается ошибка (см. скрин)
Пишет что требуется внести сайт в список доверенных, но домен уже вписан в этот список
Может кто сталкивался с такой проблемой, помогите решить


text:
Q: Android, mapFragment.getMapAsync errors occur with null object reference I tried to use google map at here by fragment.
I used SupportMapFragment, and get that Fragment by R.id.map.
And finally I used mapFragment.GetMapAsync(this).
But, It's keep making errors. I don't know why......
Plz, someone give me help over here.
// MainActivity.java
package com.example.fleago;

import androidx.annotation.NonNull;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.daimajia.swipe.SwipeLayout;
import com.daimajia.swipe.util.Attributes;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;

import net.daum.android.map.MapView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import adapter.ListViewAdapter;

import static com.example.fleago.ARActivity.REQUEST_LOCATION_PERMISSIONS_CODE;

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
    private GoogleMap mMap;
    private static final String TAG = "MarketListView";

    private SlidingUpPanelLayout mLayout;
    private ListViewAdapter mAdapter;
    private ArrayList<Market> list;

    private Location currentLocation;
    private LocationManager locationManager;
    boolean isGPSEnabled;
    boolean isNetworkEnabled;
    boolean locationServiceAvailable;
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
    private static final long MIN_TIME_BW_UPDATES = 100;//1000 * 60 * 1; // 1 minute
    private static final int MAX_DISTANCE = Integer.MAX_VALUE;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        LatLng SEOUL = new LatLng(37.56, 126.97);

        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(SEOUL);
        markerOptions.title("Seoul");
        markerOptions.snippet("Korea's Center");
        mMap.addMarker(markerOptions);

        mMap.moveCamera(CameraUpdateFactory.newLatLng(SEOUL));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(10));
    }
}

This is XML layout code
//activity_main.xml
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:sothree="http://schemas.android.com/apk/res-auto"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical">

    <com.sothree.slidinguppanel.SlidingUpPanelLayout
        android:id="@+id/sliding_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="bottom"

        sothree:umanoDragView="@+id/btn_handle"
        sothree:umanoPanelHeight="@dimen/default_small_list_height"
        sothree:umanoShadowHeight="0dp"
        sothree:umanoParallaxOffset="100dp">

        <!-- MAIN CONTENT -->
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".MainActivity" >

            <fragment
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/map"
                tools:context=".MapsActivity"
                android:name="com.google.android.gms.maps.SupportMapFragment" />

        </LinearLayout>
        <!-- SLIDING LAYOUT -->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="@dimen/default_full_list_height"
            android:background="@color/seoul_default_light"
            android:orientation="vertical"
            android:focusable="false"
            android:clickable="false">

            <!--- 손잡이 -->
            <Button
                android:id="@+id/btn_handle"
                android:background="#00ff0000"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:layout_gravity="right"
                android:layout_marginRight="10dp"
                android:clickable="true"    >
            </Button>

            <ListView
                android:id="@+id/marketList"
                android:layout_width="match_parent"
                android:layout_height="match_parent" >
            </ListView>
        </LinearLayout>
    </com.sothree.slidinguppanel.SlidingUpPanelLayout>
</LinearLayout>

and this is error coming from Logcat
2019-09-28 17:35:13.911 18564-18564/com.example.fleago E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.fleago, PID: 18564
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fleago/com.example.fleago.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3114)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3257)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1948)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7050)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
        at com.example.fleago.MainActivity.onCreate(MainActivity.java:74)
        at android.app.Activity.performCreate(Activity.java:7327)
        at android.app.Activity.performCreate(Activity.java:7318)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3094)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3257)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1948)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7050)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)

I can't understand why getMapAsync(this) is null at here
Plz anybody can tell me why this things happen?

A: Set supportfragment like this
<fragment android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/map" tools:context=".MapsActivity" class="com.google.android.gms.maps.SupportMapFragment" />

A: What I have observed from your issue, is that you might be facing naming convention of your Activity class.
You might have declared it MapsActivity in your manifest file. Whereas, you are using MainActivity name above in your given code.
Change that to MapsActivity and check your Manifest file that it is also not showing any error.
If it showing error then change the name same to the name which you are using for Activity class.


text:
Q: using watson discovery to access publically accessible URL we are using watson discovery service to find answer for travel related questions. Unfortunately the documents set to be used here are not static but the travel related forum on the web. So we need Discovery to access those URL for annotating various components (entities, relations, sentiments etc) and later we can query based on the same to find the right link which has the answers. However I see discovery only support files as documents set and not an URL. I remember alchemy API and the new service NLU both has support for URL. Is there any way discovery can access the URL ? We have selected discovery service for our solution because of the query support it has which seems to be not there in NLU or Alchemy.

A: In order to access a public URL, you would need to create some kind of web crawler which converts the web site to the correct format that the data crawler can access.
More details here: https://www.ibm.com/watson/developercloud/doc/discovery/data-crawler-seeds.html


text:
Q: How to self union a GeoDataFrame? I have a GeoPandas dataframe with lines all originating in the same location. I want to partition the lines into segments and merge them to get a dataframe containing all the unique segments.
I tried overlay with union, which seems to solve my described problem. However, this only supports polygons. I am looking for a solution lines.

import geopandas as gpd

lines_gdf = gpd.read_file('input.geojson')
lines_union_gdf = gpd.overlay(lines_gdf, lines_gdf, how='union')

Example input file: input.geojson
Expected output file: output.geojson

A: For the geometry you can use the unary_union (Shapely unary_union) predicate. The method will split all self-intersection geometries (Planar Graph)
# unary union of all the geometries of the GeoDataFrame
lines_gdf.geometry.unary_union
<shapely.geometry.multilinestring.MultiLineString object at 0x10cc20e10>
lines_gdf.geometry.unary_union.wkt
'MULTILINESTRING ((13.39825630187988 52.50709252547882, 13.40160369873047 52.50617828126911), (13.40160369873047 52.50617828126911, 13.40518712997437 52.50513340745842), (13.40518712997437 52.50513340745842, 13.40799808502197 52.50440198101236), (13.40518712997437 52.50513340745842, 13.40608835220337 52.50564278654393), (13.40160369873047 52.50617828126911, 13.40445756912231 52.50790226875552))'
 for geom in lines_gdf.geometry.unary_union:
     print(geom)
 LINESTRING (13.39825630187988 52.50709252547882, 13.40160369873047 52.50617828126911)
 LINESTRING (13.40160369873047 52.50617828126911, 13.40518712997437 52.50513340745842)
 LINESTRING (13.40518712997437 52.50513340745842, 13.40799808502197 52.50440198101236)
 LINESTRING (13.40518712997437 52.50513340745842, 13.40608835220337 52.50564278654393)
 LINESTRING (13.40160369873047 52.50617828126911, 13.40445756912231 52.50790226875552)


text:
Q: How we can use html content in title using vue.js? I have data like this:
 {
           "content": "Application Filed
April 2007 - 0.0 Years from filing",
        },
        {
            "content": "Non-Final  May 2009 - 2.06 Years from accident",
        },
        {
            "content": "Interview
 August 2009 - 2.29 Years from accident",
        },
        {
            "content": "Final
 November 2009 - 2.57 Years from accident",
        },
        {
            "content": "Request for Continuous
February 2010 - 2.82 Years from accident",
        },

And I want to use this content key value on hover ex:
In above data there is "br" tag appears like this (shown in picture).

But I want to use text like HTML means text after the br tag appears in the next line right now they appear in the same line with br tag.
And what I want in hover is shown below:
Final
November 2009 - 2.57 Years from accident

A: You can use v-html


text:
Q: Grasp Controller, Does it really need a UI to exist? I have a Domain model which can be in multiple states, and if these states go out of a given range the domain should automatically react.
For example I have a Car which is made of multiple things which have measurements
the Engine - Rev counter and Temperature
the Fuel Tank - capacity
It is plausible to have a CarStateController, which observes the engine and the tank, and if these states go out of range i.e. the engine temperature goes above range, turn the engine fan on.
There is no UI, (you could argue it would show a light on the dash board, but for this case it does not) is this a valid use of a GRASP controller pattern? if not what is this CarStateController Called?
Or have I completely missed the point and this should be the State Pattern?

A: Have you thought about sending this question to Craig Larman, the one who coined the GRAS Patterns??? He may or may not respond to your question. The way I understand Facade controller in his book APPLYING UML and Patterns, a facade controller should not 'maintain significant information about the system or domain' PG 311 3rd edition. Otherwise you get a bloated controller.  Sounds like you need an additional domain object called a 'Regulator' that monitors other domain objects and reacts when levels are too high or too low. I realize I am not addressing your State pattern that's because I am not familiar with it.


text:
Q: How to map multiple beans in Spring @RestController? How can I map multiple beans in my @RestController?
I'm using spring-web-4.3.8.RELEASE.jar
I tried everything: @RequestParam @RequestBody, @RequestAttribute, @RequestPart but nothing works...
package com.example.demo;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RestService {

    @RequestMapping(value = "demo", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public Object[] demo(Foo foo, Bar bar) {
        return new Object[]{foo, bar};
    }

    public static class Bar {
        public Long id;
        public String bar;
    }

    public static class Foo {
        public Long id;
        public String foo;
    }
}

My (encoded) payload is:

foo=%7B%22id%22%3A123%2C%22foo%22%3A%22foo1%22%7D&bar=%7B%22id%22%3A456%2C%22bar%22%3A%22bar1%22%7D

Decoded payload:

foo={"id":123,"foo":"foo1"}&bar={"id":456,"bar":"bar1"}

Request Headers:

Content-Type: application/x-www-form-urlencoded

With the above code, it returns:

[{"id":null,"foo":null},{"id":null,"bar":null}]

But what I want is:

[{"id":123,"foo":"foo1"},{"id":456,"bar":"bar1"}]

Thanks

A: You are creating static inner class in your RestController. Spring wont be able to auto map the properties from received request with the mentioned bean. Please define your bean in separate package or outside controller. Then you will be able to map it with @RequestBody.
            @RestController
            public class RestService {

                @RequestMapping(value = "demo", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
                public Object[] demo(@RequestBody FooBar foobar) {
                      // your custom work
                }
            }

                public class Bar {
                    public Long id;
                    public String bar;
                }

                public class Foo {
                    public Long id;
                    public String foo;
                }

// created wrapper as @RequestBody can be used only with one argument.
                public class FooBar {
                      private Foo foo;
                      private Bar bar;
                }

for referece please check requestBody with multiple beans
also ensure that the request params names are matching with the properties of your bean.(i.e Foo and Bar).


text:
Q: I want to query by date stamp which is not a ISODate format.The date is the following format Datestamp: 2016-03-08T02:20:20 I am new to Mongodb. I want to query by DateStamp. The date stamp is as follows
Datestamp: 2016-03-08T02:20:20
I used ISODate query which didn't work
db.GeneralLiability.find({ "session._Datestamp":{"$gte":ISODate("206-03-08T02:20:20")}})

Also I tried using:
db.GeneralLiability.find({ "session._Datestamp": {'$regex':'2016-03-08'}})

I am not sure if this is the right way to query. Please help me with this..

A: Show the output of the query.
You have written 206 instead of 2016.
db.GeneralLiability.find({ "session._Datestamp":{"$gte":ISODate("206-03-08T02:20:20")}})

Try this it should work:
db.GeneralLiability.find({ "session._Datestamp":{"$gte":ISODate("2016-03-08T02:20:20")}})


text:
Q: allow duplicate value for parameters I want my parameter to have 2 possible values (Value_1, Value_2) but 3 possible labels (Label_1, Label_2, Label_3), i.e:
Label_1 Value_1
Label_2 Value_2
Label_3 Value_1
If I select Label_3 in the parameter drop down menu, SSRS will change it automatically to Label_1 (since Label_3 and Label_1 have the same value). Is there a way to prevent it?

A: The answer is that there is no way for you to do what you are asking. When you select "Label_3" what you are actually doing in the background is setting the parameter value to "Value_1". The displayed label for the parameter is then updated, based on the value, but it will display the first match which is "Label_1". If both Label_1 and Label_3 have the same value, then they are functionally indistinguishable from one another so you can combine them into a single option e.g. "Label_1 / Label_3".


text:
Q: Sitecore 6.4 - publishing clones From my understanding of how cloning works, when a change to a parent of a clone is published to the web database that change should be immediately apparent for the clone as well, as the clone fields merely reference the fields of the parent.
However, while I can see changes immediately in clones in the content tree (already on the save event) publishing the parent doesn't seem to affect the clone in the web database - old values are maintained - at least temporarily. Publishing the clone will push the change to the clone on the web.
Incremental publish of entire site didn't force update.
Viewing the clone in the content tree in the web database showed the clone with old data (unsurprisingly).
Saving the clone, then incrementally publishing did force the update to the clone on the web.
From all of this I surmise that what actually happens with clones is that their data is read into the web database when the clones themselves are saved/published, rather than that they are truly just reference pointers. Though the master database clones are apparently functioning as references.
This would seem to allow for a fair amount of flexibility, and the functionality I'd like to see could feasibly be built on top of this - that when a parent of a clone is updated an owner of the clone receives a notification and can choose whether to accept the update. This notification is currently only possible when the clone owner has overwritten a field.
Can anyone shed any light on this?
Edit: cross posted to SDN forum, no response there.

A: There is some semi-official information regarding clones and publishing and also regarding cross-database clones (which aren't supported, yet).
Regarding publishing:

Publishing converts cloned data to field values.

Regarding cross-database clones:

The Sitecore 6.4 UI does not support cross-database clones, but this seems inevitable.

ref: http://www.sitecore.net/Community/Technical-Blogs/John-West-Sitecore-Blog/Posts/2010/10/Sitecore-CMS-6-4-Cloning.aspx


text:
Q: Using Kafka Producer inside oracle DB I am trying to post Messages from Oracle to Kafka broker directly using custom java class for that I uploaded the required library in oracle and calling java function using oracle function/procedure. Basic java function is working fine but function in which Kafka is getting initialized and used throwing uncaught exception. Even I put whole function body inside try-catch block but still not getting my customized exception as message.
I am having Oracle 12C that have JVM version 1.8.
This message got popup on oracle SQL prompt at java function call (java.lang.NoClassDefFound Error).
I created a jar file for my custom classes and uploaded it with it's respected libraries to oracle DB.
I uploaded library files using below command.
loadjava -u <user>/<Password>@DB -resolve <library>.jar

Please tell how to get Kafka Producer initialized and start sending message, from inside oracle
How to debug the java function that is loaded inside the oracle DB.
My custom classes are given below
public class KafkaPublisher {
static ProducerRecord<String, String> PR = null;
static Producer<String, String> producer = null;
static Properties prop = new Properties();

public static void init() {
prop.put("bootstrap.servers", "111.11.11.11:9092");
prop.put("acks", "1");
prop.put("retries", "0");
prop.put("batch.size", "16384");
prop.put("linger.ms", "1");
prop.put("buffer.memory", "33554432");
prop.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
prop.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

}

public static String push(String data) {
String response = "No responce";
init();
try {
producer = new KafkaProducer<String, String>(prop);
PR = new ProducerRecord<String, String>("topic1", data);
Future<RecordMetadata> future = producer.send(PR);
RecordMetadata rMetaData = future.get();
response = "Current Offset: " + rMetaData.offset();
} catch (Exception e) {
response = "Message: " + e.getMessage() + " Cause: " + e.getCause();
}
return response;
}

public static String getProperties(String msg) {
return "My message: " + msg + prop.toString();
}
}

function getProperties(String msg) is working fine but function
  push(String data) is not working.

A: Exactly what libraries you have loaded to database?
For me i have missing the slf4j-simple jar lib.
Also you need to grant to your dbuser those permissions:
exec dbms_java.grant_permission( <DB_USER>, 'SYS:javax.management.MBeanServerPermission', 'createMBeanServer', '' )
exec dbms_java.grant_permission( <DB_USER>, 'SYS:javax.management.MBeanTrustPermission', 'register', '' )
exec dbms_java.grant_permission( <DB_USER>, 'SYS:javax.management.MBeanPermission', '*', '*' )


text:
Q: Query a listValue in an Entity using Google Datastore API Is it possible to query a listValue from an Entity using the Google Cloud Datastore API.
For example if I had a Post Entity for a blog:
[
  {
    "title": "My First Post",
    "tags": ["google", "android"]
  },
  {
    "title": "My Second Post",
    "tags": ["google"]
  }
]

Obviously the data above would be tag properly (e.g. with listValue, stringValue etc). Can a query be made to give me all Post entities who have a tag that equals "android".
I've tried several things with no success. Both Standard and GQL queries. I've even tried to apply some GQL queries that would normally work when using Datastore from a Google App Engine instance(python) but they don't seem to work with Google Cloud Datastore API.
Any help would be greatly appreciated.

A: Found the problem. I started debugging this morning and discovered that the filter that was being sent was undefined.
You always miss stuff like that during late night coding sessions.


text:
Q: How to set Crystal Report's FormulaFiled value from TextBox's form Value I'm using this code to set the value of FormulaField:
xreport.DataDefinition.FormulaFields("AllMost1").Text = 30

But it gives me the next Error:

Update:
This is the property panel that I take the name from:

thanks

A: Do you mean the property panel of the formula field placed on the report canvas? If so, the answer is NO.  You need to simply use the formula name.
Based on the new image you posted, you are indeed using the wrong name. You need to use the name of the formula, not the name of the formula field placed on the report canvas. Most likely, you need to drop the '1' at the end of the name. So change to:
xreport.DataDefinition.FormulaFields("AllMost").Text = Chr(39) & 30 & Chr(39)

A: The formula text must be text rather than a number. So test something like:
xreport.DataDefinition.FormulaFields("AllMost1").Text = Chr(39) & 30 & Chr(39)

A: Most likely, the problem is with the reference to the formula name. Make sure it is indeed "AllMost1".


text:
Q: Data sent as ArrayBuffer is being recieved as Blob I'm using the ws module for a WebSocket server in nodejs. On the server side, I have a Uint8Array that I send to the client using code very much like this,
var data = new Uint8Array([1, 2, 3, 4, 5]);
clientSock.send(data, {
    binary: true
});

However, on the client side (both the latest Chrome and Firefox), the data is recieved as a Blob object. I know I can process this back into a Uint8Array using the FileReader API. But I want to receive it as an ArrayBuffer in the first place. How can I do this?

A: Just as I finished writing this question, I happened to find the answer on my own. According to the MDN documentation for WebSocket, there is a binaryType property that has to be set to either "blob" or "arraybuffer", and it determines the format in which the data is received. By changing the client-side code like so,
var sock = new WebSocket("<the server address>");
sock.binaryType = "arraybuffer";

Now all the binary data from the server is received as ArrayBuffers, as expected.


text:
Q: How to fetch data from array of list in xslt I am using xslt 3.0(saxon-HE v11.4 library) to convert json to xml in Java.
Need help to extract value from an array
Sample Input json
{
"Details":{
"name":["a","b","c"]
}
}

Require output in below format
<Details>
<name indexarray="0">a</name>
<name indexarray="1">b</name>
<name indexarray="2">c</name>
</Details>

A: Well, with Saxon 11 you can literally feed the JSON with e.g. -json:input.json to the XSLT, then match e.g. .[. instance of map(*)]
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="3.0"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes="#all"
  expand-text="yes">

<xsl:output indent="yes"/>

<xsl:template match=".[. instance of map(*)]">
  <Details>
    <xsl:iterate select="?Details?name?*">
      <name indexarray="{position() - 1}">{.}</name>
    </xsl:iterate>
  </Details>
</xsl:template>

</xsl:stylesheet>


text:
Q: Unable to properly parse json file I'm working on a random quote app, and I need to parse ajson file through an http connection. I'm succesfully stablishing the connection; and fetching json data, but when I try parsing it, it seems I'm getting the keys, value, or object not mapped correctly. Or maybe I'm not using the correct code. Any help appreciated. Thanks
package com.example.george.radonquote;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    Toolbar myToolbar;
    String randQuote;
    String author;
    TextView quoteTextView;
    ImageView bgImageView;
    ImageView nextImageView;
    String url = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&_jsonp=mycallback";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //setting the ActionBar for the activity
        myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(myToolbar);

        quoteTextView = (TextView) findViewById(R.id.quote_text);
        nextImageView = (ImageView) findViewById(R.id.next_quote);

        /*onclick listener for next quote*/
        nextImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FetchQuote fetchQuote = new FetchQuote();
                fetchQuote.execute();
            }
        });
    }

    /*
    * async class to get random quote in background
    */
    class FetchQuote extends AsyncTask<Void, Void, Void> {
        String quote = "";
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(MainActivity.this,"Fetching Quote!",Toast.LENGTH_LONG).show();
        }

        /*
        * making connection and parsing json data
        */
        @Override
        protected Void doInBackground(Void... voids) {
            try {
                URL uri = new URL(url);
                HttpURLConnection urlConnection = (HttpURLConnection) uri.openConnection();
                InputStream inputStream = urlConnection.getInputStream();
                BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream));
                String line = "";
                while(line != null) {
                    Log.v("line: ",line);
                    line = bf.readLine();
                    quote += line;
                }
            }
            catch (MalformedURLException ex) {
                ex.printStackTrace();
            }
            catch (IOException ex) {
                ex.printStackTrace();
            }

            try {
                JSONArray ja = new JSONArray(quote);
                JSONObject jo = (JSONObject) ja.get(0);
                randQuote = jo.get("content").toString().replaceAll("\\<[^>]*>","");
                author = jo.get("title").toString();
                Log.v("QUOTE", randQuote+" "+author);
            }
            catch (JSONException ex){
                ex.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
//            Log.v("Post Exec", randQuote);
            quoteTextView.setText(randQuote);

        }
    }
}

A: You are not getting a valid json from the url. First rectify your string then parse the json . try below code. This is only a temporary solution.
try {
                String requiredString = quote.substring(quote.indexOf("(") + 1, quote.indexOf(")"));
                JSONArray ja = new JSONArray(requiredString );
                JSONObject jo = (JSONObject) ja.get(0);
                randQuote = jo.get("content").toString().replaceAll("\\<[^>]*>","");
                author = jo.get("title").toString();
                Log.v("QUOTE", randQuote+" "+author);
            }

A: The problem is the _jsonp=mycallback parameter in the url.  Using this parameter is causing malformed JSON to be returned to you.
As you can see in the documentation, the JSONP parameter is used in JavaScript in order to execute a callback.
Since you're using Java in an Android app, there is no need to specify a callback.
All you need to do is modify the url so that it doesn't define a callback:
String url = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1";

Then, the response will be valid formatted JSON, for example:
[
   {
      "ID":1572,
      "title":"Si Scott",
      "content":"
I really like looking at design and thinking: that attention to detail must have taken absolutely ages.<\/p>\n",
      "link":"https:\/\/quotesondesign.com\/si-scott\/",
      "custom_meta":{
         "Source":"article<\/a>"
      }
   }
]

Then, your existing code should work.  I just tested it, and it logged the correct response:
10-06 12:35:52.522 4606-4624/com.example.ex V/QUOTE: Graphic designers find themselves in a role of visual dishwashers for the Information Architects’ chefs.
                                                                Gunnar Swanson

A: Use JSOUP library and follow the given code
String content;
content = Jsoup.parse(content).text();


text:
Q: Android app crash with putExtra I'm trying to do a little app for myself and I can't do a putExtra on an intent, it crashes when I try to do it. After some search I can't find what I'm doing wrong, I'm pasting code who works perfectly and still crash
Main Activity Code to put extras :
Intent i = new Intent(getApplicationContext(), ShinyCounter.class);

i.putExtra("pokemon", poke);
i.putExtra("method", meth);
i.putExtra("methodAbrev", methAbrev);
startActivity(i);

All variables comes from EditText like this :
String poke = pokeName.getText().toString();

And the get Extras on my ShinyCounter Activity :
Bundle extras = getIntent().getExtras();

String pokeName = extras.getString("pokemon");
String method = extras.getString("method");
String methodAbrev = extras.getString("methodAbrev");

The error is : java.lang.RuntimeException: Unable to instantiate activity ComponentInfo: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference

A: You can do something like below in main activity
 Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
      i.putExtra("Value1", "Android ExplicitIntent");
      // Set the request code to any code you like, you can identify the
      // callback via this code
      startActivity(i);

You can do something like below in ActivityTwo
 Bundle extras = getIntent().getExtras();
String value1 = extras.getString("Value1");


text:
Q: How to add Highcharts on UIWebView in iOS? I am totally new to HighCharts and I referred example http://blog.li-labs.com/developing-ios-apps-with-custom-charting/ and tried same, but on iPad simulator I am getting a blank screen.
I have referred questions on stack-overflow, but still it is not working.
Can anyone tell where am I going wrong.
EDIT : Code in My HTML file :
 <!DOCTYPE HTML>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Highcharts Example</title>

How to add and use the Javascript libraries in XCode
Here is a simple view of how I handle the code and data within XCode.

*

*Download the Javascript reporting package from your preferd chart site. In my case: http://www.highcharts.com/download

*Add or import the files into XCode resources. (I suggest creating a group called JS).

*When adding a resource to XCode it will generally be marked as being needed to be compiled. Ensure that the files are not listed as
  being "Compiled". The easiest way is to simply drag the files from
  Targets -> Your Project Name -> Compiled Sources  into Targets -> Your
  Project Name -> Copy Bundle Resources.

*Create a test html file or simply import one from your HighChart (or any other javascript chart library) examples folder. In my case I
  name it hcpie.html

*Ensure that any file references in the  tags do not recurse or move into any folder (even if they are in one in your project).
  e.g.
RIGHT =
WRONG =

*

*Create a UIWebView within Interface Designer and link it to your view (in my case I named it chart1). e.g.

  @interface FirstViewController : UIViewController { IBOutlet UIWebView
  *chart1; }
@end

*

*Simply reference the HTML example file when loading.

*

*(void)viewDidLoad {

  NSString *pathOfFile = [[NSBundle mainBundle] pathForResource:@"hcpie"
  ofType:@"html"]; NSString *htmlText = [NSString
  stringWithContentsOfFile:pathOfFile encoding:NSUTF8StringEncoding
  error:nil];
NSURL *baseURL = [NSURL fileURLWithPath:pathOfFile];
[chart1 loadHTMLString: htmlText baseURL:baseURL];
[super viewDidLoad];
}

A: Steps:-
1) First just creat one html file and do the needful code or for trial can copy html code from examples that you get from package http://www.highcharts.com/download
2) Make sure that the scripts in html should have proper .js links
for e.g:-
or
if you want to give it locally you can write
But make sure that the .js files are there in your application folder.
3) NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"graph" ofType:@"html"];
   NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
   [obj loadHTMLString:htmlString baseURL:nil];  // Webview *obj;

Hope this help you. In my case its working.

A: I tried the suggestions in this post and couldn't get the HighChart load.
The problem ended up being the "loadHTMLString" call.  Passing nil for the baseURL was incorrect.  Here's what worked for me - I needed to pass the actual baseURL:
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:url ofType:@"html"];
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];

NSURL *baseURL = [NSURL fileURLWithPath:htmlFile];

[webView loadHTMLString:htmlString baseURL:baseURL];

A: Useful code for calling .html in UIWebView.
-(void)viewDidLoad
   {
     NSString *pathOfFile = [[NSBundle mainBundle]  pathForResource:@"chart" ofType:@"html"];

     NSString *htmlText =[NSString stringWithContentsOfFile:pathOfFile encoding:NSUTF8StringEncoding error:nil];

     NSURL *baseURL = [NSURL fileURLWithPath:pathOfFile];

    [UIWebView loadHTMLString: htmlText baseURL:baseURL];
   }


text:
Q: Filter with multiple geopoints in elasticsearch This might be simple, however I am not able to implement or find out the expected query format.
I was able to create the mapping of the geo_point data type right from my application. I am also able to query the indices with the geopoint by sending the following query as a part of request body:
{
    "query": {
        "bool" : {
            "must" : {
                "match_all" : {}
            },
            "filter" : {
                "geo_distance" : {
                    "distance" : "5km",
                    "field_location" : "9.0194,-79.4509"
                }
            }
        }
    }
}

Here, field_location is the name of the field which is of type geo_point. This works perfectly fine.
I am not able to find a way in which I can provide multiple lat/lon values to the filter and use a OR between them. I tried using the SHOULD in the query, but not able to find a right way. Any pointers on how to achieve this would be really helpful.

A: It seems that I was on the right path. The Bool query for elasticsearch supports the operators. I was just not using it right.
The following query works:
{
    "query": {
        "bool": {
            "should": [
                {
                    "geo_distance": {
                        "distance": "1km",
                        "field_location": "9.0194,-79.4509"
                    }
                },
                {
                    "geo_distance": {
                        "distance": "1km",
                        "field_location": "8.9972,-79.4985"
                    }
                }
            ]
        }
    }
}


text:
Q: How to store data from Axios response? I'm trying to store axios response but approach 1 seems to be the only one that works.
Approach 1: works ok from state
const [loadingData, setLoadingData] = useState(true);
const [data, setData] = useState([]);

  useEffect(() => {
    async function getData() {
      await axios
        .get("sampleApi")
        .then((response) => {
          setData(response.data);
          setLoadingData(false);
        });
    }
    if (loadingData) {
          getData();
        }
      }, []);

    ...

// This works fine from state
          {data.map(
              (i, index) => {
                return
{i.id}

          }
        )}

Approach 2: Attempting setting as a regular variable instead of state
const [loadingData, setLoadingData] = useState(true);
  let data;

  useEffect(() => {
    async function getData() {
      await axios
        .get("sampleApi")
        .then((response) => {
          data = response.data // <====== This
          setLoadingData(false);
        });
    }
    if (loadingData) {
          getData();
        }
      }, []);

    ...

// Following results in: Uncaught TypeError: Cannot read properties of undefined (reading 'map')
          {data.map(
              (i, index) => {
                return
{i.id}

          }
        )}

So, two questions:

*

*Is it "bad practice" to store data in the state (as I only plan to read it and not modify it)

*Any idea what am I doing wrong in approach 2?

A:
Is it "bad practice" to store data in the state

No, this is what the state is for.

(as I only plan to read it and not modify it)

You are modifying it: You are changing it from the default value to the value from the HTTP request.

Any idea what am I doing wrong in approach 2?

That is a FAQ


text:
Q: How to detect whether video gets paused or not? I have a question that how to check whether video get paused? means I want to call an Intent on Pausing a video so how can I detect whether Video gets paused or not?
Please help about this problem.
Thanks in advance.

A: If you're using the MediaPlayer in Android, you can use IsPlaying()

A: Are you playing the video using a VideoView class or an external application ?. If you have a visible button in your VideoView for pause action you can throw an intent in its setonClickListener method.


text:
Q: Regex spits out extra empty array $input = "some words go here priority: p1,p2 -rank:3 status: not delayed";

$pattern = "/(\S+):\s*(.*?)(?=\S+:|$)|(.*?)(?=\S+:|$)/";

preg_match_all($pattern, $input, $matches);

Example: http://regex101.com/r/yM0wO1#pcre
The above pattern ends up outputting an extra empty array at the end. (See Match 5 in the example)
Everything else is the way I expect it to be...
How can I prevent the extra empty array?
EDIT:
BACKGROUND INFO
I have data formatted as such:
some words go here priority: p1,p2 -rank:3 status: not delayed

Basically I need to retrieve each set of data that corresponds to the colon name.
Ideally if I could end up with an array structure such that
'' => 'some words go here'
priority => 'p1,p2'
-rank    => 3
status   => 'not delayed'

A few caveats:
keywords will not have a defining colon-word (keywords are just placed in the front)

keywords will not always exist (might just be colon-words)

colon-words will not always exist (might just be keywords)

A: A better way would be to split instead of matching it.
(?=\s\S+:)

Each string would contain the key-value pair or only value if there's no key

A: try this
(\S+):\s*(.*?)(?=\S+:|$)|(.*?)(?=\S+:)


text:
Q: One-Plaquette Action and SU(2)'s Irreducible Representations I have a typical single-plaquette partition function for a gauge-field
$$ Z=\int [d U_{\text{link}}] \exp[-\sum_{p} S_{p}(U,a)]$$
with $U$ as the product of the the $U$'s assigned to each link around a plaquette.  Now the $U$'s are irreducible representations of my group elements, which in my case is SU(2), and lets take the 1/2 representation as an example, then define the character as $\Xi_{r}\equiv \text{Tr}[U]$ which for our case is $\Xi_{1/2}=\text{Tr}[U]$.  Now I have to take the product of these representations, however (and here's my question), how do I know which group elements/that-element's-representation to assign to each link?
I'm not sure how to compute the Trace without knowing first how to do the product of the link's representations, but I don't even know how to assign the elements to the links.
Thanks,

A: I'm not completely sure what OP is asking(v1). However here is my interpretation.
OP asks:

How do I know which group elements [...] to assign to each link?

The group element $U_{\ell}\in SU(2)$ affiliated with a link $\ell\in L$ is not fixed. One is supposed to integrate over all possible group values of $U_{\ell}\in SU(2)$. Phrased differently, the link variables $(U_{\ell})_{\ell\in L}$ are the dynamical variables of the model.
The integration measure in the integral for $Z$ reads
$$ [dU]~=~  \prod_{\ell\in L} dU_{\ell}$$
Here $dU_{\ell}$ typically denotes the Haar measure for $SU(2)$.


text:
Q: C# .net integral constant in html actionlink is too large I currently am trying to pass a value to a controller action and the integer i am trying to pass is too long. To overcome this, I have tried using new { trackingNumber = 9374869903500896631228d } and changing the parameter type of my action to a double but then the value is passed in as 9.3748699035009E+21 instead of 937486990350089663128. How can I change the below Html.ActionLink and controller action so that I can pass the value 937486990350089663128to my action?
Action Link:
<div>@Html.ActionLink("Track Package", "TrackPackage", "Orders", new { trackingNumber = 9374869903500896631228 }, null)</div>
Controller Action:
public void TrackPackage(int trackingNumber) {
     // .....do stuff with trackingNumber
}

A: There is no simple type in c# that can hold a integral number that big (long resp. Int64 only have about 18 digits). And double, although it has the range for such a big number, lacks the precision. So you can only pass the value as a string. If you need arithmetic operations on the number on the server side, you can use the BigInteger structure. You can convert the string into a BigInteger using the Parse method.
public void TrackPage(string trackingnumber) {
    BigInteger tracker = BigInteger.Parse(trackingnumber);
    // do something with your number
}


text:
Q: How to unselect / unhighlight selected and highlighted text in QScintilla editor widget? I'm trying to write a search box, containing find/find previous/find next to interact with a QScintilla textEditor widget. I therefore wrote to methods, one for highlighting all matching words and then select first occurance, one for unselecting/unhighlighting them.
First run seams to do as it should, but if I repeat the search with another keyword, both the old and the new keyword are shown.

Here's my code fragment:
//
// search & replace:
// do_search_and_replace() - search for matching word
//
void MainWindow::do_search_and_replace(QString action_str)
{
    int line, index;
    qDebug() <<  "do_search_and_replace()";
    // just to be sure...
    if(action_str.isEmpty())
        action_str == "0";

    int action_nr = action_str.toInt();    // convert argument to int, so we can switch() on it...
    text = ui->lineEdit_find->text();
    docText = ui->textEdit->text();
    qDebug() <<  "action_nr: " << action_nr;

    //
    // first part: Mark all occurances of search term
    //
    if (!( text.isEmpty() ))
    {
        qDebug() << text;
        ui->textEdit->SendScintilla(QsciScintillaBase::SCI_INDICSETSTYLE, 0, QsciScintilla::INDIC_FULLBOX);
        ui->textEdit->SendScintilla(QsciScintillaBase::SCI_INDICSETFORE,0, QColor(Qt::darkBlue));

        int end = docText.lastIndexOf(text);
        int cur = -1;

        if(end != -1)
        {
            ui->textEdit->getCursorPosition(&line, &index);
            qDebug() << "line: " << line << " index: " << index;
            while(cur != end)
            {
                cur = docText.indexOf(text,cur+1);
                ui->textEdit->SendScintilla(QsciScintillaBase::SCI_INDICATORFILLRANGE,cur,
                    text.length());
            }
        }
    } // END text.isEmpty(), END mark ALL

    //
    // second part: Find firs occurance of search term
    //
    bool use_regular_expression, is_case_sensitive, match_whole_word_only, use_wrap, search_forward;
    use_regular_expression = false;
    is_case_sensitive = ui->checkBox_CaseSensitive->isChecked();
    match_whole_word_only = ui->checkBox_WholeWords->isChecked();
    use_wrap = true;
    search_forward = ui->radioButton_Forward->isChecked();

    ui->textEdit->SendScintilla(QsciScintillaBase::SCI_INDICSETSTYLE, 0, QsciScintilla::INDIC_FULLBOX);
    //ui->textEdit->SendScintilla(QsciScintillaBase::SCI_INDICSETFORE,0, QColor(Qt::darkBlue));

    bool found = ui->textEdit->findFirst(text, use_regular_expression, is_case_sensitive, match_whole_word_only, use_wrap, search_forward);
    qDebug() <<  "START: found = " << found;
    while(found)
    {
        ui->textEdit->getCursorPosition(&line, &index);

        qDebug() << "line: " << line << " index: " << index;
        qDebug() << text;

        // pattern: found = findFirst(pattern, use_regular_expression, is_case_sensitive, match_whole_word_only, use_wrap, search_forward)
        //found = ui->textEdit->findFirst(text, use_regular_expression, is_case_sensitive, match_whole_word_only, use_wrap, search_forward);

        if(found)
        {
            ui->textEdit->SendScintilla(QsciScintillaBase::SCI_INDICATORFILLRANGE, line, text.length());
            int start = ui->textEdit->positionFromLineIndex(line, index);
            int end = ui->textEdit->positionFromLineIndex(line, index + text.length());
            qDebug() << "line: " << line << " start: " << start << " end: " << end;

//            found = ui->textEdit->findNext();
//            ui->textEdit->SendScintilla(QsciScintillaBase::SCI_INDICATORFILLRANGE, line, text.length());

        }

        found = false;
    }
}

//
// unselect selected stuff
//
void MainWindow::reset_searchResult()
{
    int line, index;
    qDebug() <<  "in: reset_searchResult()";

    //QString text = ui->lineEdit_find->text();
    text.clear();
    docText.clear();

    //
    // first part: Mark all occurances of search term
    //
    if (( text.isEmpty() ))
    {
        qDebug() << text;
        ui->textEdit->SendScintilla(QsciScintillaBase::SCI_INDICSETSTYLE, 0, QsciScintilla::INDIC_PLAIN);
        ui->textEdit->SendScintilla(QsciScintillaBase::SCI_INDICSETFORE,0, QColor(Qt::white));

        //docText = text;
        docText = ui->lineEdit_find->text();
        int end = docText.lastIndexOf(text);
        int cur = -1;

        if(end != -1)
        {
            ui->textEdit->getCursorPosition(&line, &index);
            qDebug() << "line: " << line << " index: " << index;
            while(cur != end)
            {
                cur = docText.indexOf(text,cur+1);
                ui->textEdit->SendScintilla(QsciScintillaBase::SCI_INDICATORALLONFOR,cur, text.length());
                ui->textEdit->SendScintilla(QsciScintillaBase::SCI_INDICATORCLEARRANGE,cur, text.length());
            }
        }
    } // END text.isEmpty(), END mark ALL

    //
    // second part: Find firs occurance of search term
    //
    bool use_regular_expression, is_case_sensitive, match_whole_word_only, use_wrap, search_forward;
    use_regular_expression = false;
    is_case_sensitive = ui->checkBox_CaseSensitive->isChecked();
    match_whole_word_only = ui->checkBox_WholeWords->isChecked();
    use_wrap = true;
    search_forward = ui->radioButton_Forward->isChecked();

    ui->textEdit->SendScintilla(QsciScintillaBase::SCI_INDICSETSTYLE, 0, QsciScintilla::INDIC_PLAIN);
    //ui->textEdit->SendScintilla(QsciScintillaBase::SCI_INDICSETFORE,0, QColor(Qt::darkBlue));

    bool found = ui->textEdit->findFirst(text, use_regular_expression, is_case_sensitive, match_whole_word_only, use_wrap, search_forward);
    qDebug() <<  "START: found = " << found;
    while(found)
    {
        ui->textEdit->getCursorPosition(&line, &index);

        if(found)
        {
            ui->textEdit->SendScintilla(QsciScintillaBase::SCI_INDICATORCLEARRANGE, line, text.length());
            int start = ui->textEdit->positionFromLineIndex(line, index);
            int end = ui->textEdit->positionFromLineIndex(line, index + text.length());
            qDebug() << "line: " << line << " start: " << start << " end: " << end;

        }

        found = false;
    }
}

I'm pretty sure this isn't the best code ever written, but all I can afford... ;)
Maybe someone who is fit with QScintilla can correct my attempts or provide me with a working search & highlight example that can be called multiple times without keeping the old results?
Thanks in advance, people!

A: Perhaps it's easier than you think, assume that you used QsciScintilla  instance for your ui->textEdit :
#define MY_MARKER_ID 0

void MainWindow::clearMarkers()
{
    int lastLine = ui->textEdit->lines() - 1;
    ui->textEdit->clearIndicatorRange( 0, 0, lastLine, ui->textEdit->text( lastLine ).length() - 1, MY_MARKER_ID );
}


text:
Q: Python multiplication, exponent yields different precision I've got some Python code that I'd like to understand what's going on (see below). I've got the results of the calculations as well.
If I square radius by repeated multiplication I get a different result than if I square radius. If it were rounding, I'd expect a smaller gap between the two calculations. Can someone put me on the right path, please?
import math
diameter=float(input('Enter the diameter: '))
radius = diameter / 2.0

area_1 = math.pi * radius * radius
print ("The area is: ", area_1)

area_2 = math.pi * radius**2
print ("The area is: ", area_2)
=========================================================
Enter the diameter: 6.2

The area is:  30.19070540099791**3**

The area is:  30.19070540099791**7**

A: The difference comes from the different way both expressions were calculated:

*

*math.pi * radius * radius was calculated as:
a. tmp = math.pi * radius
b. tmp * radius

*math.pi * radius**2
a. tmp2 = radius**2
b. tmp2 * math.pi
Mathematically both are equivalent but not so when we are talking about finite precision of floating point types in a computer.
You can read more on the topic on Wikipedia or other sources. The field of numerical analysis (and numerical methods) deals mostly with these numerical rounding errors in the pursue of finding best algorithms for involved calculations.


text:
Q: ASP.NET Response.Redirect( ) Error Here is my code:
try
{
    Session["CuponeNO"] = txtCode.Text;
    txtCode.Text = string.Empty;
    Response.Redirect("~/Membership/UserRegistration.aspx");
}
catch(Exception ex)
{
   string s = ex.ToString();
   lblMessage1.Text = "Error Occured!";
}

I am getting an error, even though it redirects after catch.
Here is the error:

"System.Threading.ThreadAbortException:
  Thread was being aborted.\r\n   at
  System.Threading.Thread.AbortInternal()\r\n
  at
  System.Threading.Thread.Abort(Object
  stateInfo)\r\n   at
  System.Web.HttpResponse.End()\r\n   at
  System.Web.HttpResponse.Redirect(String
  url, Boolean endResponse)\r\n   at
  System.Web.HttpResponse.Redirect(String
  url)\r\n

Can anyone tell me why this error is occurring?

A: You could simply move ....
Response.Redirect("~/Membership/UserRegistration.aspx");

... outside of the Try / Catch block or you can try John S. Reid's newer solution below :

Response.Redirect(url) ThreadAbortException Solution
by John S. ReidMarch 31, 2004(edited October 28, 2006 to include greater detail and fix some inaccuracies in my analysis, though the solution at it's core remains the same)

... skipping down ...

The ThreadAbortException is thrown when you make a call to Response.Redirect(url) because the system aborts processing of the current web page thread after it sends the redirect to the response stream. Response.Redirect(url) actually makes a call to Response.End() internally, and it's Response.End() that calls Thread.Abort() which bubbles up the stack to end the thread. Under rare circumstances the call to Response.End() actually doesn't call Thread.Abort(), but instead calls HttpApplication.CompleteRequest(). (See this Microsoft Support article for details and a hint at the solution.)

... skipping down ...

PostBack and Render Solutions? Overrides.
The idea is to create a class level variable that flags if the Page should terminate and then check the variable prior to processing your events or rendering your page. This flag should be set after the call to HttpApplication.CompleteRequest(). You can place the check for this value in every PostBack event or rendering block but that can be tedious and prone to errors, so I would recommend just overriding the RaisePostBackEvent and Render methods as in the code sample1 below:
private bool m_bIsTerminating = false;

protected void Page_Load(object sender, EventArgs e)
{
    if (WeNeedToRedirect == true)
    {
        Response.Redirect(url, false);
        HttpContext.Current.ApplicationInstance.CompleteRequest();
        m_bIsTerminating = true;

        // Remember to end the method here if there is more code in it.
        return;
    }
}

protected override void RaisePostBackEvent
(
    IPostBackEventHandler sourceControl,
    string eventArgument
)
{
    if (m_bIsTerminating == false)
    base.RaisePostBackEvent(sourceControl, eventArgument);
}

protected override void Render(HtmlTextWriter writer)
{
    if (m_bIsTerminating == false)
    base.Render(writer);
}

The Final Analysis
Initially I had recommended that you should simply replace all of your calls to Response.Redirect(url) with the Response.Redirect(url, false) and CompleteRequest() calls, but if you want to avoid postback processing and html rendering you'll need to add the overrides as well. From my recent in depth analysis of the code I can see that the most efficient way to redirect and end processing is to use the Response.Redirect(url) method and let the thread be aborted all the way up the stack, but if this exception is causing you grief as it does in many circumstances then the solution here is the next best thing.
It should also be noted that the Server.Transfer() method suffers from the same issue since it calls Response.End() internally. The good news is that it can be solved in the same way by using the solution above and replacing the call to Response.Redirect() with Server.Execute().

1 - I modified the code formatting to make it fit inside SO boundaries so it wouldn't scroll.


text:
Q: React state: does changing state twice guarantees triggering render twice too? In React: Does changing state n times also triggering render n times too?
Is there any way to ignore some state changing based on the max browser fps rate?
I'm not sure using useTransition. It seem on experimental stage.

A: I recommend reading this article about batch update if you mean by different state object changes. But basically, no. It doesn't guarantees triggering render n times following state change.
As for limiting it using browser fps rate - it's an interesting question. I guess it can be implemented using requestAnimationFrame the way libraries like use-debounce are implemented


text:
Q: GeoIP redirect - loading after DOM ready the javascript below redirects based on GEOIP :
<script type="text/javascript">

        var script = document.createElement('script');
        script.src = "//freegeoip.net/json/?callback=nyGeoIP";
        document.getElementsByTagName('head')[0].appendChild(script);
        function nyGeoIP(d) {
            if (d.country_code === 'XX') {
                window.location = 'http://www.domain.com';
            }
        }
        </script>

Can someone please let me know how to amend this code so that it calls the FREEGEOIP server after dom ready (after page load).
The FreeGeoIP server often does not respond which blocks page rendering , and tools such as gtmetrix/webpagetest show loading times of 1-2 minutes when the FREEGEOIP server is not responding.

A: Include jquery library and use document ready function:
<script type="text/javascript">
$(document).ready(function(){
var script = document.createElement('script');
        script.src = "//freegeoip.net/json/?callback=nyGeoIP";
        document.getElementsByTagName('head')[0].appendChild(script);
        function nyGeoIP(d) {
            if (d.country_code === 'XX') {
                window.location = 'http://www.domain.com';
            }
        }
})

</script>

A: Which JQuery library do I include , currently use only :
1.7.2
1.8.18
the code you provided above does not work


text:
Q: Passing a PHP variable to JavaScript I am having problems passing any kind of variable from PHP to JavaScript. Here is a simple example at jsFiddle. Why does it not return my string?
http://jsfiddle.net/funinabox/VkNe2/1/
<?php
//create php test string
$teststring = "mystring";
?>

//Convert Php string to JavaScript string
var testvar = <?php echo $teststring; ?> ;
//Display output of the array elements;
alert(testvar);

A: You are missing "
var testvar = "<?php echo $teststring; ?>";

Here is a full example
<?php
//create php test string
$teststring = "mystring";
?>

<html>
   <head>
   <script>
   //Convert Php string to JavaScript string
    var testvar = "<?php echo $teststring; ?>" ;
    //Display output of the array elements;
    alert(testvar);
    </script>
    </head>
<body></body>
</html>

A: I reinstalled xampp and then made 1 change in c:\xampp\apache\conf\httpd.conf in the mime section section by adding (I did it in line 402 but anywhere in that section should be ok)... AddType application/x-httpd-php .html .htm
NOW IT WORKS!!!!!!!! This looks like a big mistake in the current xampp distribution for Win 7 32-bit.

A: try to do link below:
<?php
//create php test string
$teststring = "mystring";
?>

//Convert Php string to JavaScript string
var testvar = '<?php echo $teststring; ?>' ;
//Display output of the array elements;
alert(testvar);

A: My environment uses templates so this is not copy and paste code. However I was able to pass the variable to Javascript by doing this:
$teststring = 'mystring';

 $page_headers = <<<PAGEHEADERS
 <script>
    window.onload=function(){
        var testvar = '$teststring';
        alert(testvar);
    };
</script>
PAGEHEADERS;

As long as the php variable is defined first you should be able to get a value from it simply by calling it.


text:
Q: Turning a random number generating loop into a one equation? Here's some pseudocode:
count = 0
for every item in a list
    1/20 chance to add one to count

This is more or less my current code, but there could be hundreds of thousands of items in that list; therefore, it gets inefficient fast. (isn't this called like, 0(n) or something?)
Is there a way to compress this into one equation?

A: Let's look at the properties of the random variable you've described. Quoting Wikipedia:

The binomial distribution with parameters n and p is the discrete probability distribution of the number of successes in a sequence of n independent yes/no experiments, each of which yields success with probability p.

Let N be the number of items in the list, and C be a random variable that represents the count you're obtaining from your pseudocode. C will follow a binomial probability distribution (as shown in the image below), with p = 1/20:

The remaining problem is how to efficently poll a random variable with said probability distribution. There are a number of libraries that allow you to draw samples from random variables with a specified PDF. I've never had to implement it myself, so I don't exactly know the details, but many are open source and you can refer to the implementation for yourself.
Here's how you would calculate count with the numpy library in Python:
n, p = 10, 0.05                  # 10 trials, probability of success is 0.05
count = np.random.binomial(n, p) # draw a single sample

A: Apparently the OP was asking for a more efficient way to generate random numbers with the same distribution this will give.  I though the question was how to do the exact same operation as the loop, but as a one liner (and preferably with no temporary list that exists just to be iterated over).

If you sample a random number generator n times, it's going to have at best O(n) run time, regardless of how the code looks.
In some interpreted languages, using more compact syntax might make a noticeable difference in the constant factors of run time.  Other things can affect the run time, like whether you store all the random values and then process them, or process them on the fly with no temporary storage.
None of this will allow you to avoid having your run time scale up linearly with n.


text:
Q: Using 'height: 100%' and 'align-items: stretch' in flexbox I have a flexbox with a direct child that is declared with align-items: stretch.
Inside this flexbox's direct child, I would like to have a div container that also uses its parent's full height (by setting height: 100%).
However, the div container won't stretch to 100% height of its parent, unless I also set height: 100% on the flexbox's direct child.
Is it kind of bug? Must I set the flexbox's direct child with align-items: stretch AND height: 100% to achieve what I want? It seem redundant to me.
Here is an example:

html,
body {
  margin: 0;
  height: 100%;
}

.flexbox {
  display: flex;
  flex-direction: row;
  height: 100%;
  background-color: green;
}

.flexbox-child {
  // height: 100%; uncommenting this will get it to work
  align-items: stretch;
  background-color: blue;
}

.flexbox-grand-child {
  height: 100%;
  background-color: red;
}

      I want to be stretched till the bottom

http://plnkr.co/edit/FACkwsC2y65NcbOaceur?p=preview
Thanks!

A: It's a complicated case.
Your .flexbox-child is only a flex item, but not a flex container. Therefore, align-items: stretch, which only applies to flex containers, is ignored.
Then, .flexbox-grand-child has a percentage height, which behaves like this:

The percentage is calculated with respect to the height of the
  generated box's containing block. If the height of the containing
  block is not specified explicitly (i.e., it depends on content
  height), and this element is not absolutely positioned, the value
  computes to 'auto'.

The containing block is the flex item (.flexbox-child), which has no explicit height, and its height seems to depend on the content.
However, this dependency is only due to the new min-height: auto. But before taking min-height into account, the height of the flex item will be (due to the initial align-self: stretch) the height of the container, which is specified explicitly, ignoring the content.
Then, Firefox considers that the height of .flexbox-child does not depend on its contents, so height percentages in its children should work. And then your code works.
However, Chrome doesn't think so.
I'm not sure which one does it right. It doesn't help that height is only defined in the old CSS2.1 and in CSS basic box model, which is an inconsistent draft.
To be safe, better set the height of .flexbox-child explicitly. Or make it a flex container.

A: When you create a flex container only the child elements become flex items. Descendants beyond the children do not become flex items and flex properties don't apply to them.
Simply apply display: flex to the flex item, which converts it into a flex container, as well. Then default flex properties like align-items: stretch will apply to the children (now flex items).
You wrote:

I would like to have a div container that also uses its parent's full
  height...

You don't need to use height: 100% or add align-items: stretch (it's a default rule). Simply add display: flex to .flexbox-child, and .flexbox-grand-child will expand the full available height.
Modified demo: http://plnkr.co/edit/n0Wt3x3CUr1ZfBD2RrGo?p=preview

re: height: 100% possible bug
With regard to the need to specify height: 100% on child elements, I don't see any bug here. Everything seems to conform to the spec. Here's a complete explanation: Working with the CSS height property and percentage values


text:
Q: How to run a query with the properties from a stored document? Let's say we have a index with docs which contain the following fields: uid and hobbies.  How can I run a query to find similarities between 1 and the other users, without having to retrieve the user first and then run a new query with his hobbies?

A: You could use the more like this query and ask ES to retrieve documents that are like a given document (e.g. user with uid=1) (without having to retrieve that document first).
So in the like array below you simply give a reference to the document that needs to be used as a reference for the "more like this" query (you can give more than one document and also verbatim hobbies strings). ES will retrieve that document, check the hobbies field and perform a "more like this hobbies" query on all other documents.
POST /users/user/_search
{
    "query": {
        "more_like_this" : {
            "fields" : ["hobbies"],
            "like" : [
              {
                "_index" : "users",
                "_type" : "user",
                "_id" : "1"                <---- fill in the UID of the user here
              }
            ]
        }
    }
}


text:
Q: php codes comparison with classic asp Does anyone knows where to find a site that has a code comparison of php and classic asp? some sort of cheat sheet comparison guide. I need to convert a php site to classic asp.
please advise.
Thanks.

A: ASP is a framework so there is no direct comparison to PHP which is a language.  ASP does support vbscript and javascript languages.
Here is a comparison to vbscript/javascript/PHP languages
http://phplens.com/phpeverywhere/node/view/30

A: Have you tried this?
http://www.me-u.com/php-asp/conversionnotes.htm
It obviously has some limitations, but I hope it helps.
Cheers!


text:
Q: Variable name from a preprocessor concatenation"##" I would like to create a variable name from a template argument :
template<typename Name>
class NotWorking {
public:
  int var_ ## Name;
};

Which should work like so :
NotWorking nw<test>;
nw.var_test;

Is it possible ?


text:
Q: Deserialize only give me 0 as value my problem is simple, when I deserialise this file all values are set to 0.
Some code will be more explicit.
Main class :
 public partial class MainPage : PhoneApplicationPage
    {
        Elements file = null;
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            load_map("clxml.xml");
        }

        public void load_map(string path)
        {
            // deserialize xmlfile_config_map
            XmlSerializer serializer = new XmlSerializer(typeof(Elements));

            StreamReader reader = new StreamReader(path);
            try
            {
                file = (Elements)serializer.Deserialize(reader);

            }catch(Exception e){

            }
            MessageBox.Show((file.listObjet[1].id).ToString());
            MessageBox.Show((file.listObjet[2].pos_x).ToString());
            reader.Close();
        }
    }

class that I fill:
//[Serializable]
public class Element
{
    [System.Xml.Serialization.XmlElement("id")]
    public int id { get; set; }

    [System.Xml.Serialization.XmlElement("pos_x")]
    public int pos_x { get; set; }

    [System.Xml.Serialization.XmlElement("pos_y")]
    public int pos_y { get; set; }

    [System.Xml.Serialization.XmlElement("rot")]
    public int rot { get; set; }
}

//[Serializable()]
[System.Xml.Serialization.XmlRoot("droot")]
public class Elements
{
    [XmlElement("Element")]
    public List<Element> listObjet { get; set; }

and the xml file :
 <Element id="4" pos_x="85" pos_y="43" rot="34"/>

which is line like this, but I don't think the problem comes from here.

A: The serializer is expecting elements in the XML. Try change [XmlElement] to [XmlAttribute].
The quickest way to find out deserialize issues is by reverting the process. Try serializing a dummy object and verify whether the output is correct.
        Elements elements = new Elements
        {
            listObjet = new List<Element>
            {
                new Element
                {
                    id = 1,
                    pos_x = 10,
                    pos_y = 20,
                    rot = 8
                }
            }
        };

        var serializer = new XmlSerializer(typeof(Elements));
        string output;
        using (var writer = new StringWriter())
        {
            serializer.Serialize(writer, elements);
            output = writer.ToString();
        }

        // Todo: check output format

I have changed [XmlElement] to [XmlAttribute] for the id and pos_x properties. This was the output:
<Element id="1" pos_x="10">
  <pos_y>20</pos_y>
  <rot>8</rot>
</Element>


text:
Q: IOS trigger notification action when app is in the background My app does the following when the app is opened from a remote notification. Basically, it saves article_id in UserDefaults so that I can use it when the app is launched:
extension AppDelegate: UNUserNotificationCenterDelegate {

    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        didReceive response: UNNotificationResponse,
        withCompletionHandler completionHandler: @escaping () -> Void
    ) {
        let userInfo = response.notification.request.content.userInfo

        if let aps = userInfo["aps"] as? [String: AnyObject] {

            let article_id = aps["article_id"]
            UserDefaults.standard.set(article_id, forKey: "notification_article_id")
        }

        completionHandler()
    }
}

However, this only works if the app is completely closed. If the app remains in the background and the user clicks the notification (e.g. from the lock screen), the function above will not be triggered. Thus, it will not save the data into my UserDefaults. Does any one know how to trigger a similar action in this situation? Thanks in advance!

A: Your extension delegate function declaration is correct, and should fire in the state that you described (lock screen, home screen, app backgrounded). Please make sure that you have set the delegate:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

  UNUserNotificationCenter.current().delegate = self

}

If this is already set, I would verify that your parsing code is correct, and test on the simulator or another device. I often use xcrun simctl to test push notifications in the simulator. You can do this by creating a dummy test file called 'payload.json', and exectuting the following command in the terminal:
xcrun simctl push booted com.yourapp.bundle.id payload.json

This is an example of a payload.json:
{
    "Simulator Target Bundle": "com.yourapp.bundle.id",
    "aps":{
        "alert":{
            "title":"Egon Spengler",
            "body":"I collect spores, molds, and fungus"
        },
        "sound":"alert.caf",
        "badge":3
    },
    "alert":{
        "alertUuid":"asdfasdfasdfasdfasdf",
        "state":1,
        "lastUpdate":"2020-11-8T21:43:57+0000"
    }
}

If the application has been terminated, you can obtain notification content at launch using the following code within didFinishLaunchingWithOptions:
 let notificationOption = launchOptions?[.remoteNotification]
 if let notification = notificationOption as? [String: AnyObject] {

 }

Finally, make sure that you have enabled 'Remote Notifications' background mode in your project settings:


text:
Q: Smart way to load multiple datasets and plot them in python? I have multiple data set with names dat01, dat02,... so on! . I want to load these datasets using for loop or any other trick. Afterwards, I want to plot these datasets in a single plot. Right now I'm doing something like this
import numpy as np

data1=np.loadtxt("dat01.dat")
xData1, yData1 = np.hsplit(data1, 2)
x1 = xData1[:,0]
y1 = yData1[:,0]

data2=np.loadtxt("dat01.dat")
xData2, yData2 = np.hsplit(data2, 2)
x2 = xData2[:,0]
y2 = yData2[:,0]

# plotting these datasets
plt.plot(x1, y1)
plt.plot(x2,y2)

This method works but not a smart way. Are there other methods that can be employed to reduce the typing?

A: Create a function that does it for some data object, and in a loop just load the data and call that function while incrementing the filename by one. Let's say you have 10 of those files:
def plot_data(data):
    xData, yData = np.hsplit(data, 2)
    x = xData[:,0]
    y = yData[:,0]
    plt.plot(x, y)

for i in range(10):
    data = np.loadtxt(f"dat0{i}.dat")
    plot_data(data)

plt.show()

If your file names start from "dat01.dat", then just replace the range to range(1, 10). And if you have a problem with a leading zero in numbers<10, then use np.loadtxt("dat%02d.dat" % i).

A: def plot_data(data,i):
    xData, yData = np.hsplit(data, 2)
    x = xData[:,0]
    y = yData[:,0]
    plt.plot(x, y)
    plt.legend("Graph number {index}".format(index=i))
# I do think a Graph title in more appropriate than a legend in this case.
# since you asked for a legend, please find it above.
# Here is how I would do a title.
    plt.title("Graph number {index}".format(index=i))

for i in range(10):
    data = np.loadtxt(f"dat0{i}.dat")
    plot_data(data,i)

plt.show()