text:
Q: Convert EC Public Key from SubjectPublicKeyInfo form into "traditional" form Hope I got the terms correct.
I currently have an EC public key in the form
-----BEGIN PUBLIC KEY-----
xxxxx
-----END PUBLIC KEY-----

which I understand is the SubjectPublicKeyInfo form. I would like to convert this into the form
-----BEGIN EC PUBLIC KEY-----
xxxxx
-----END EC PUBLIC KEY-----

using commands like openssl or similar. I can't seem to find a RSAPublicKey_{in|out} for the openssl ec command. I would like to be able to convert the public key in both DER and PEM forms.
Is there any other way to do this?

A: OpenSSL does not support any "BEGIN EC PUBLIC KEY" format and (AFAIK) no such format exists. There is a "traditional" public key format for RSA ("BEGIN RSA PUBLIC KEY"), which is essentially a PEM encoded PKCS#1 structure. Later standards defined how to encode public keys in an algorithm agnostic way (SubjectPublicKeyInfo) and so there isn't always a "traditional" format version.
You can check the known OpenSSL PEM types by looking in the openssl pem header file (include/openssl/pem.h). You will notice that there is no "EC PUBLIC KEY" entry. There is an "RSA PUBLIC KEY", "DSA PUBLIC KEY" and "ECDSA PUBLIC KEY", but the latter two are not used anywhere in the OpenSSL codebase (i.e. they only exist in the header file).
There are "traditional" formats for private keys. To convert a PKCS8 private key to traditional form use:
openssl ec -in p8file.pem -out tradfile.pem

The ec command also recognises the "-inform DER" and "-outform DER" options. So, for example, to convert a DER PKCS8 private key file into PEM traditional you could use:
openssl ec -inform DER -in p8file.der -out tradfile.pem

Or to convert a PEM PKCS8 private key file into DER traditional use:
openssl ec -in p8file.pem -outform DER -out tradfile.der

You can also go the other way, i.e. traditional form private key to PKCS8:
openssl pkcs8 -topk8 -nocrypt -in tradfile.pem -out p8file.pem

The pkcs8 command above also recognises the -inform and -outform options.


text:
Q: Jenkins plugin can't access file on node Through my own plugin, I need to know about the existence of a file in the workspace of a Jenkins node. But the file can't be found whereas it really exists on the node (D:\workspace\JOB_NAME\test.txt).
public class MyBuilder extends Builder implements Serializable {

    private static final long serialVersionUID = 1L;

    public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
            throws InterruptedException, IOException {

        FilePath fp = new FilePath(build.getWorkspace(), "test.txt");

        String result = fp.act(new FileCallable<String>() {
            private static final long serialVersionUID = 1L;

            @Override
            public String invoke(File file, VirtualChannel channel) throws IOException, InterruptedException {
                if (file.getAbsoluteFile().exists()){
                    return file.getName() + " exists.";
                } else {
                    return file.getName() + " doesn't exist.";
                }
            }
        });

        System.out.println("result: " + result);

Result:
FATAL: remote file operation failed: D:\workspace\JOB_NAME\test.txt at hudson.remoting.Channel@182752b:Node
hudson.util.IOException2: remote file operation failed: D:\workspace\JOB_NAME\test.txt at hudson.remoting.Channel@182752b:Node
    at hudson.FilePath.act(FilePath.java:900)
    at hudson.FilePath.act(FilePath.java:877)
    at com.company.tlb.proj.MyBuilder.perform(Unknown Source)
    at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:19)
    at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:804)
    at hudson.model.Build$BuildExecution.build(Build.java:199)
    at hudson.model.Build$BuildExecution.doRun(Build.java:160)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:586)
    at hudson.model.Run.execute(Run.java:1575)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:46)
    at hudson.model.ResourceController.execute(ResourceController.java:88)
    at hudson.model.Executor.run(Executor.java:237)
Caused by: java.io.IOException: Unable to serialize hudson.FilePath$FileCallableWrapper@18b91cb
    at hudson.remoting.UserRequest.serialize(UserRequest.java:166)
    at hudson.remoting.UserRequest.<init>(UserRequest.java:62)
    at hudson.remoting.Channel.call(Channel.java:671)
    at hudson.FilePath.act(FilePath.java:893)
    ... 11 more
Caused by: java.io.NotSerializableException: java.io.PrintStream
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1164)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1518)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1483)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1400)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1158)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1518)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1483)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1400)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1158)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1518)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1483)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1400)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1158)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:330)
    at hudson.remoting.UserRequest._serialize(UserRequest.java:155)
    at hudson.remoting.UserRequest.serialize(UserRequest.java:164)
    ... 14 more

What am I doing wrong?
Links:

*

*Making your plugin behave in distributed Jenkins

*Jenkins API: FilePath.java

A: You're passing an anonymous inner-class to act(...) which has an implicit reference to its parent class, MyBuilder. My guess is that even though MyBuilder implements Serializable, it can't actually be serialized due to some reference to another object that isn't Serializable (e.g. a java.io.PrintStream as the stack-trace indicates).
Make your instance of FileCallable<String> a static inner class to get rid of the implicit reference to its parent:
private static class MyFileCallable implements FileCallable<String> {
  private static final long serialVersionUID = 1L;
  @Override
  public String invoke(File file, VirtualChannel channel) throws IOException, InterruptedException {
    if (file.getAbsoluteFile().exists()){
      return file.getName() + " exists.";
    } else {
      return file.getName() + " doesn't exist.";
    }
  }
}

And then use that instead:
String result = fp.act(new MyFileCallable());

Update:
Here's a link to Java's Nested Classes tutorial which outlines the relationship between an instance of an inner class an its enclosing outer class instance:

An instance of InnerClass can exist only within an instance of
  OuterClass and has direct access to the methods and fields of its
  enclosing instance.

This is also explained in more technical terms in the JLS (§8.1.3 Inner Classes and Enclosing Instances).
With that in mind, this quote from the Serializable doc explains why you encountered the NotSerializableException:

When traversing a graph, an object may be encountered that does not
  support the Serializable interface. In this case the
  NotSerializableException will be thrown and will identify the class of
  the non-serializable object.

redpajama_set_name: RedPajamaStackExchange


text:
Q: FTP Server setup: VM issues I have an Filezilla FTP server setup on my Windows 7 64-bit machine. I can access this server on the Windows 7 machine itself.
I have Oracle Virtualbox installed, with a RHEL 5 Guest OS using Host-only Adapter. How would i go about configuring access to the FTP server from this guest OS?
I can ping the guest OS from my host, but not vice versa.

A: Try disabling the firewall on the host machine, then attempt to connect to FTP again.
If this fails, it could be a problem relating to what IPs the FTP server is listening on (Although, I haven't seen this on Filezilla). The easiest thing to do in this case is to have the networking on the virtual machine set to Bridged mode, and then try again.


text:
Q: Custom Comparator in Priority queue in Java I am trying to use a priority queue with a custom comparator, However I am not able to achieve my expected functionality.:
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;

public class TestMain {

    public static void main(String[] args) {
        Queue<Node> queue = new PriorityQueue<>(new Comparator<Node>() {
            public int compare(Node a, Node b) {
                if(a.level == b.level) {
                    return a.data - b.data;
                }
                return a.level - b.level;
            }
        });

        queue.add(new Node(0,1));
        queue.add(new Node(1,2));
        queue.add(new Node(1,4));
        queue.add(new Node(2,3));
        queue.add(new Node(2,7));
        queue.add(new Node(2,2));
        queue.add(new Node(2,5));

        System.out.println(queue);
    }

    private static class Node {
        int level;
        int data;

        Node(int level, int data) {
            this.level = level;
            this.data = data;
        }

        public String toString() {
            return level + ":" + data;
        }
    }
}

Expected output = [0:1, 1:2, 1:4, 2:2, 2:3, 2:5, 2:7]
Actual output = [0:1, 1:2, 1:4, 2:3, 2:7, 2:2, 2:5]
I want the elements in the priority queue to be ordered by the level first then by data.

A: Actually the logic is correct, only thing is I am trying to do sysout, then it was showing in the order I have inserted, When I used the remove operation on the priority queue data is coming in expected format.
while(!queue.isEmpty()) {
    System.out.println(queue.remove());
}

Output:
0:1
1:2
1:4
2:2
2:3
2:5
2:7

A: The method toString may not display the elements in retrieval order. So, it  doesn't mean that your comparator is incorrect.
The following is written in the javadoc for PriorityQueu (emphasis is mine):

This class and its iterator implement all of the optional methods of the  Collection  and  Iterator  interfaces.  The Iterator provided in method
iterator()  and the Spliterator provided in method  spliterator()
are not guaranteed to traverse the elements of  the priority queue in any particular order. If you need ordered  traversal, consider using Arrays.sort(pq.toArray()).

It isn't written explicitly here, but toString relies on iterators, therefore elements may not be displayed in the expected orther either.
The toString method is defined in class Collection, and isn't specificly overridden here.
PriorityQueu is probably implemented using a binary heap in an array.
From there, it follows naturally that iteration is made in array order. Displaying elements in the correct order would require removing them from the queue, and is therefore impossible except by sorting a copy somewhere else, what would be too heavy for a simple toString.


text:
Q: Encoding problems in gvim window title I'm running gVim 7.4 on a Windows 10 machine.

*

*The system version is single-language-cyrillic (can not change this).

*The language for non-unicode programs is set to russian.

*_vimrc contains the following commands: set langmenu=en_US.UTF-8 set encoding=utf-8 set guifont=Lucida_Console:h14 (this font has cyrillic glyphs)
However, the window title and the output of several commands contains some gibberish. My guess is that gvim tries to print something in russian but fails.
An example of such behavior (note the window title, the output, and the invitation for the next command in the end):

What is the best course of action here? What should I put into _vimrc (or tweak in my OS) to make this gibberish readable? Any advice would be helpful.
Full listing of my _vimrc:
set langmenu=en_US.UTF-8

filetype plugin on
set shellslash
filetype indent on
set grepprg=grep\ -nH\ $*
set encoding=utf-8
set backspace+=start
syntax enable
if has('gui_running')
set guifont=Lucida_Console:h14
set background=light
set guioptions-=T
else
set background=dark
endif
colorscheme solarized
let g:Tex_DefaultTargetFormat='pdf'
let g:Tex_MultipleCompileFormats='pdf,aux'
set nu
set wrap
set linebreak
set nolist
set formatoptions+=l

A: If it is only about messages in gVim, not about displaying content of your file or a menu, you can try to put this line in your _vimrc
language messages ru_RU.UTF-8

Edit: Unfortunately, this doesn't work because there is no ru_RU.UTF-8 folder presented in gVim (it would need to be created, more about it here). So it is possible to change to English only with
language messages en_US.UTF-8

:h language
:h win32-gettext


text:
Q: Sending data from a database to list view in android I have been trying to print data I have retreived from a database in android to a list view but whilst I get the data back I am not getting anything printed out. I believe I might be missing some code but I am not sure.
Here is the code I have to retrieve and print from the database:
public class DrinksDiaryActivity extends Activity {

    private ListView listView;
    public static ArrayList<String> ArrayOfDrink = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drinks_diary);
        populateLayoutFromDrinkDiaryTitles();
    }

    public void onNewDrinkButtonClicked(View v){
        Intent drinkEntry = new Intent(this, DrinkEntryActivity.class);
        startActivity(drinkEntry);

    }

    private void populateLayoutFromDrinkDiaryTitles(){
        DatabaseHandler db = new DatabaseHandler(this);
        List<Drink> drinkEntry = db.getAllDrinkEntrys();
        for (Drink cn : drinkEntry) {
            String log = "Id: "+cn.getID()+", Drink: " + cn.getDrinkType() + ", Drink Volume: " + cn.getDrinkVolume() + ", Alcohol Percentage: " + cn.getAlcoholPercentage() + ", Time: " + cn.getTimeStamp() +
                ", Units: " + cn.getUnits();
            System.out.println(log);

        }
        //db.getAllDrinkEntrys();

        listView = (ListView) findViewById(R.id.drinkDiaryList);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, ArrayOfDrink);

        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {
               Toast.makeText(getApplicationContext(),
                ((TextView) v).getText(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

My database handler:
public class DatabaseHandler extends SQLiteOpenHelper  {
    // Database Version
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DRINKS_DIARY_DATABASE = "drinksDiaryDatabase";
    // Contacts table name
    private final String DRINKS_DIARY_TABLE = "drinksDiaryDatabase";
    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_DRINK_TYPE = "drinkType";
    private static final String KEY_DRINK_VOLUME = "drinkVolume";
    private static final String KEY_ALCOHOL_PERCENTAGE = "alcoholPercentage";
    private static final String KEY_TIMESTAMP = "timeStamp";
    private static final String KEY_UNITS = "units";

    public DatabaseHandler(Context context) {
        super(context, DRINKS_DIARY_DATABASE, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_DRINK_DIARY_TABLE = "CREATE TABLE " + DRINKS_DIARY_TABLE + "(" + KEY_ID + " INTEGER PRIMARY KEY, " + KEY_DRINK_TYPE
            + " TEXT, " + KEY_DRINK_VOLUME + " TEXT, " + KEY_ALCOHOL_PERCENTAGE + " TEXT, " + KEY_TIMESTAMP + " TEXT, " + KEY_UNITS + " TEXT" +  ")";
         db.execSQL(CREATE_DRINK_DIARY_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

         db.execSQL("DROP TABLE IF EXISTS " + DRINKS_DIARY_TABLE);

        onCreate(db);
    }

    public void addDrinkEntry(Drink drinkEntry) {
    SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_DRINK_TYPE, drinkEntry.getDrinkType());
        values.put(KEY_DRINK_VOLUME, drinkEntry.getDrinkVolume());
        values.put(KEY_ALCOHOL_PERCENTAGE, drinkEntry.getAlcoholPercentage());
        values.put(KEY_TIMESTAMP, drinkEntry.getTimeStamp());
        values.put(KEY_UNITS, drinkEntry.getUnits());
        db.insert(DRINKS_DIARY_TABLE, null, values);
        db.close();
    }

    public Drink getDrinkEntry(int id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(DRINKS_DIARY_TABLE, new String[] {
        KEY_ID, KEY_DRINK_TYPE, KEY_DRINK_VOLUME, KEY_ALCOHOL_PERCENTAGE, KEY_TIMESTAMP, KEY_UNITS,
        }, KEY_ID + "=?", new String[] {
            String.valueOf(id) }, null, null, null, null);
        if (cursor != null){
            cursor.moveToFirst();
        }
        Drink drinkEntry = new Drink(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
        return drinkEntry;
    }

     public List<Drink> getAllDrinkEntrys() {
         List<Drink> drinkEntryList = new ArrayList<Drink>();
         String selectQuery = "SELECT  * FROM " + DRINKS_DIARY_TABLE;
         SQLiteDatabase db = this.getWritableDatabase();
         Cursor cursor = db.rawQuery(selectQuery, null);
         if (cursor.moveToFirst()) {
             do {
                 Drink drinkEntry = new Drink();
                 drinkEntry.setID(Integer.parseInt(cursor.getString(0)));
                 drinkEntry.setDrinkType(cursor.getString(1));
                 drinkEntry.setDrinkVolume(cursor.getString(2));
                 drinkEntry.setAlcoholPercentage(cursor.getString(3));
                 drinkEntry.setTimeStamp(cursor.getString(4));
                 drinkEntry.setUnits(cursor.getString(5));
                 drinkEntryList.add(drinkEntry);
             }
             while (cursor.moveToNext());
             }
          return drinkEntryList;
     }

     public int getDrinkEntryCount() {
         String countQuery = "SELECT  * FROM " + DRINKS_DIARY_TABLE;
         SQLiteDatabase db = this.getReadableDatabase();
         Cursor cursor = db.rawQuery(countQuery, null);
         cursor.close();
         return cursor.getCount();
     }

     public int updateDrinkEntry(Drink drinkEntry) {
         SQLiteDatabase db = this.getWritableDatabase();
         ContentValues values = new ContentValues();
         values.put(KEY_DRINK_TYPE, drinkEntry.getDrinkType());
         values.put(KEY_DRINK_VOLUME, drinkEntry.getDrinkVolume());
         values.put(KEY_ALCOHOL_PERCENTAGE, drinkEntry.getDrinkVolume());
         values.put(KEY_TIMESTAMP, drinkEntry.getTimeStamp());
         values.put(KEY_UNITS, drinkEntry.getUnits());

         return db.update(DRINKS_DIARY_TABLE, values, KEY_ID + " = ?", new String[] { String.valueOf(drinkEntry.getID()) });
     }

      public void deleteDrinkEntry(Drink drinkEntry) {
         SQLiteDatabase db = this.getWritableDatabase();
         db.delete(DRINKS_DIARY_TABLE, KEY_ID + " = ?",
             new String[] { String.valueOf(drinkEntry.getID()) });
         db.close();
    }

}

And my database:
public class Drink {

    int _ID;
    String _drinkType;
    String _drinkVolume;
    String _timeStamp;
    String _alcoholPercentage;
    String _units;

    public Drink(){

    }

    public Drink(int id, String drinkType, String drinkVolume, String timeStamp, String alcoholPercentage, String units){
        this._ID = id;
        this._drinkType = drinkType;
        this._drinkVolume = drinkVolume;
        this._timeStamp = timeStamp;
        this._alcoholPercentage = alcoholPercentage;
        this._units = units;
    }

    public Drink(String drinkType, String drinkVolume, String timeStamp, String alcoholPercentage, String units){
        this._drinkType = drinkType;
        this._drinkVolume = drinkVolume;
        this._timeStamp = timeStamp;
        this._alcoholPercentage = alcoholPercentage;
        this._units = units;
    }

    public int getID(){
        return this._ID;
    }

    public void setID(int id){
        this._ID = id;
    }

    public String getDrinkType(){
        return this._drinkType;
    }

    public void setDrinkType(String drinkType){
        this._drinkType = drinkType;
    }

    public String getDrinkVolume(){
        return this._drinkVolume;
    }

    public void setDrinkVolume(String drinkVolume){
        this._drinkVolume = drinkVolume;
    }

    public String getAlcoholPercentage(){
        return this._alcoholPercentage;
    }

    public void setAlcoholPercentage(String alcoholPercentage){
        this._alcoholPercentage = alcoholPercentage;
    }

    public String getTimeStamp(){
        return this._timeStamp;
    }

    public void setTimeStamp(String timeStamp){
        this._timeStamp = timeStamp;
    }

    public String getUnits(){
        return this._units;
    }

    public void setUnits(String units){
        this._units = units;
    }
}

Can any one show me what I have been doing wrong and how to fix it?
Thanks

A: Your ArrayList<String> ArrayOfDrink is null as you have not added any data into your arraylist and you are directly setting that ArrayList in your ListView.
I have simply added the drink types to show the demo. You can add any detail whichever you want.Add the data in your ArrayList as below:
private void populateLayoutFromDrinkDiaryTitles(){
        DatabaseHandler db = new DatabaseHandler(this);
        List<Drink> drinkEntry = db.getAllDrinkEntrys();
        for (Drink cn : drinkEntry) {
            String log = "Id: "+cn.getID()+", Drink: " + cn.getDrinkType() + ", Drink Volume: " + cn.getDrinkVolume() + ", Alcohol Percentage: " + cn.getAlcoholPercentage() + ", Time: " + cn.getTimeStamp() +
                ", Units: " + cn.getUnits();
            System.out.println(log);
           ArrayOfDrink.add(cn.getDrinkType().toString);

        }


text:
Q: How to extract data from an JsonObject in an android studio project I'm working on a REST API application in android studio. I want to extract the data from a JsonObject which I saved using the model class when retrieving data using retrofit library. But It shows the below error.
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.covid_19updates, PID: 15236
    java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: org.json.JSONException: No value for flag
        at org.json.JSONObject.get(JSONObject.java:400)
        at org.json.JSONObject.getJSONObject(JSONObject.java:620)
        at com.example.covid_19updates.MainActivity$onCreate$1.onResponse(MainActivity.kt:52)
        at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1.lambda$onResponse$0$DefaultCallAdapterFactory$ExecutorCallbackCall$1(DefaultCallAdapterFactory.java:89)
        at retrofit2.-$$Lambda$DefaultCallAdapterFactory$ExecutorCallbackCall$1$hVGjmafRi6VitDIrPNdoFizVAdk.run(Unknown Source:6)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

The single data object I'm extracting is below:
{"updated":1606563124609,"country":"Afghanistan","countryInfo":{"_id":4,"iso2":"AF","iso3":"AFG","lat":33,"long":65,"flag":"https://disease.sh/assets/img/flags/af.png"},"cases":45966,"todayCases":127,"deaths":1752,"todayDeaths":12,"recovered":36709,"todayRecovered":414,"active":7505,"critical":93,"casesPerOneMillion":1170,"deathsPerOneMillion":45,"tests":146413,"testsPerOneMillion":3727,"population":39280785,"continent":"Asia","oneCasePerPeople":855,"oneDeathPerPeople":22421,"oneTestPerPeople":268,"activePerOneMillion":191.06,"recoveredPerOneMillion":934.53,"criticalPerOneMillion":2.37}

I want to retrieve data inside the countryInfo object. Below is my modal class
data class Covid(
    var updated: Long,
    var country:String,
    var countryInfo:JSONObject,
    var cases:Int,
    var todayCases:Int,
    var deaths:Int,
    var todayDeaths:Int,
    var recovered:Int,
    var todayRecovered:Int,
    var active:Int,
    var critical:Int,
    var casesPerOneMillion:Double,
    var deathsPerOneMillion:Double,
    var test:Long,
    var testPerOneMillion:Double,
    var population:Long,
    var continent:String,
    var oneCasePerPeople:Double,
    var oneDeathPerPeople:Double,
    var oneTestPerPeople:Double,
    var activePerOneMillion:Double,
    var recoveredPerOneMilion:Double,
    var criticalPerOneMillion:Double
)

And the code piece I wrote to get the data
override fun onResponse(call: Call<List<Covid>>, response: Response<List<Covid>>) {
                var list = response.body()
                Log.d("Response: ",response.toString())
                var countryList = ArrayList<String>()
                var countList = ArrayList<String>()
                var activeList = ArrayList<String>()
                var deathList = ArrayList<String>()
                var recoveredList = ArrayList<String>()
                var imageList = ArrayList<String>()
                list?.map { item ->
                    countryList.add(item.country.toString())
                    var totalCases = "Total Cases: "+item.cases.toString()
                    var activeCases = "Active Cases: "+item.active.toString()
                    var deaths = "Total Deaths: "+item.deaths.toString()
                    var recovered = "Total Recovered: "+item.recovered.toString()
                    var image = item.countryInfo.getJSONObject("flag").toString()
                    countList.add(totalCases)
                    activeList.add(activeCases)
                    deathList.add(deaths)
                    recoveredList.add(recovered)

                }

A: Try and make a separate data class for CountryInfo.
In covid class
val countryInfo: CountryInfo,

Then
    data class CountryInfo(
val _id: Int,
val iso2: String,
val iso3: String,
val lat: Double, //trust me you should use double on latLng values.
val long: Double,
val flag: String

)

Sidenote, you can use this site to automate making kotlin objects from JSONs.


text:
Q: Как преобразовать дату в ISO формат? Пытаюсь преобразовать дату следующим образом, но выдает ошибку builtins.ValueError: Invalid format string
import datetime
now = datetime.datetime.now()
print(now.strftime('%Y-%m-%d%%TH:%i:%sP'))

A: Помог комментарий andreymal.
import datetime
original_timestamp = datetime.datetime.now(datetime.timezone.utc)
timestamp_string = original_timestamp.strftime("%Y-%m-%dT%H:%M:%S%z")
timestamp_string = "{0}:{1}".format(timestamp_string[:-2], timestamp_string[-2:])


text:
Q: How to Create WSDL for Restful WS I have developed a small RESTful web service example using MyEclipse. I want to create a client for those WS using WSDL. How do I create a WSDL for the above web service using MyEclipse? Please help.

A: Take a look at this resource.  It describes using WSDL 2.0 to describe a REST interface:
http://www.ibm.com/developerworks/webservices/library/ws-restwsdl/#describerestservice

A: WSDL ? for a REST web service ? i'd suggest you read this book for a better understanding of REST http://oreilly.com/catalog/9780596529260
You don't need WSDL (nor WADL AFAIC) documentation in rest could be plain text for developers, schemas (xsd, rdfs...etc depending on the content types you use) sitemaps for example, a lot of links and post/put templates for example ( to mimic forms in html)


text:
Q: Jquery replace not clone I'm using replaceWith() to move a element to another parent element in DOM. But it makes a copy of it, without removing. So the element remains in the place, but a copy is made in the other parent element. How can i just move the element to other place?

A: use $.append() or $.appendTo(). Like $('#element').appendTo('#place-to-move-it');. That will move #element to #place-to-move-it.

A: Let's say you have the following HTML:

You could do the following:
$("#childDiv").detach().appendTo("#container2");

Example: https://jsfiddle.net/459usn9x/1/
EDIT: To first clear the contents of container2 before adding elements, you could do the following:
$("#container2").empty();
$("#childDiv").detach().appendTo("#container2");

A: to do this consistently on various devices, use this:
$('#elementID').detach().appendTo($('#targetID'));

detach keeps the link of the element with others, whereas remove doesn't. And it seems that appendTo used alone creates a copy on certain devices.


text:
Q: How do I best show that Likert-responses for one set of questions differ from another set of questions tested in the same population? Let me preface this by saying I am very new to research / statistics so I don't know much and I apologize for the basic questions.
I have data from a Likert-type survey (Strongly Disagree, Disagree, Neutral, Agree, Strongly Agree) that consists of twelve questions assessing bias. The first six questions assess perceived age bias (bias one thinks exists in the world) and the latter six questions assess personal age bias (bias one personally has). The likert responses can be collapsed to leave essentially three categories: Unbiased, Neutral, Biased.
My hypothesis was that there was no difference between perceived and personal age bias. I'm not sure what the best way to test this hypothesis is with my data...
Since Q1 - 6 measure perceive bias while 7 - 12 measure personal bias, I thought about aggregating results for Q1-6 and comparing that to results for Q7-12. I could then do something like a Chi-square to show a difference in distribution between the two and a post-hoc standardized residual analysis to pinpoint which response category is weighing in the most on that difference.
Also, if I do aggregate the results...what do I do if there is an outlier response that throws things off? Is there a better way to go about this? I pretty much want to say something like "Responses to the perceived bias questions were to show bias compared to the personal bias questions" or whatever I find.
Sorry for the long post, and I am grateful for the help.

A: Please explain what you mean by 'collapse'. I can imagine several
ways to do this, even though I suppose it results in some loss in
information, and thus fear it may be a bad idea.
I cannot imagine how you you could get a genuine 'outlier' from such Likert data. If you have values from one or more subjects that
'throw things off', then maybe you have made a mistake or maybe
there is an unexpected outcome in your data that's trying to tell
you something. Please explain what the 'outlier' is and why you think it is a barrier to analysis.
After collapsing, suppose each subject has a 'Perception' score x1, which
can take values -1, 0, 1. Similarly, each subject has a 'Personal' score
x2, which can take values -1, 0, 1.
Then you wonder whether a subject's two scores have the "same distribution."
Speaking very loosely, as you certainly are, that might mean any one
of several things. For example, two possible interpretations (among several) might be:

*

*Looking across subjects, difference scores d = x1 - x2 would tend to be $0.$ (Mean or median $0.)$

*It is often possible to predict a subject's x2 score from his/her x1. (Dependence between x1 and x2.)
How to do a test might depend on your method of 'collapsing' and would
certainly depend on what interpretations you have in mind. (Paired Wilcoxon test for the first, chi-squared test of independence for the second.)
Please clarify your question. Then maybe one of us can make suggestions how to analyze your data.

A: I would encourage that you consider reframing your research question. Statistically speaking, you cannot prove the absence of a difference unless you plan on using Bayesian methods. I'll explain what I mean using a simple example of how you might use your data.
Say that you decide to take the mean rating of items 1-6 and 7-12. To do this, you might document a rating of "Strongly Disagree" as a 1, "Disagree" as a 2, "Neutral" as a 3, etc. You could then average the two parts of your scale so that each person has an average rating of perceived age bias and an average rating of personal age bias. You might then use a paired sample's t-test to "test" whether the average rating of these constructs differ within individuals. Under standard null hypothesis testing, the following would be your null and alternative hypotheses:
$H_0: \mu_d = 0$
$H_a: \mu_d \ne 0$
Just for clarity, $\mu_d$ is the mean difference (i.e., the average difference in the perceived age bias and personal age bias for each person). This null hypothesis test should illustrate that the null hypothesis (that there is no average difference) is your research hypothesis. At first glance, that should mean that your question is answerable since you could test that hypothesis; however, the issue with frequentist methods is that we are testing whether we can reject the null hypothesis. Frequentist null hypothesis tests can only ever have two results: reject the null hypothesis (result is statistically significant) or fail to reject the null hypothesis (result is not statistically significant).
So, depending on your statistical orientation, framing your question as trying to show the absence of an effect is not possible. From a scientific integrity perspective, your research question and hypothesis shouldn't be trying to prove a negative either.
Not all hope is gone, however. Like I mentioned, you could use Bayesian methods to estimate the evidence for the null relative to the alternative hypotheses. Or, you could reframe your statistical hypothesis. For example, instead of saying that there is no difference between the two subscales, you could test whether results are negligibly different from zero (or effectively zero). This framework is the two one-sided t-test (TOST).
As far as strategies for answering a question of whether people respond to items similarly or differently, I'm going to assume that items are repeated on the scale. In other words, the same items are given on the perceived bias and personal bias scales (e.g., Q1 = Q7, Q2 = Q8, etc.). the Item Response Theory framework gives a few resources for doing this analysis. You could test directly whether there is differential item functioning depending on whether an item is for personal bias or perceived bias, but this would assume that it's safe to say that there is a single latent variable (i.e., bias) as opposed to two separate latent variables (i.e., personal bias and perceived bias). Item Response Theory generally requires a fairly large sample (e.g., 250-500 people). You could do a chi-square for each item where you check whether counts of endorsements for the different Likert ratings versus whether the item is for perceived or personal bias, but you would need to adjust your p-values for multiple observations. The issue is that you would run into the fact that a non-significant result can't be taken as meaning that there is no difference.


text:
Q: Form, input, onMouseOver - onMouseOut and browsers I've a form (POST) with this INPUT (a line), in a JSP file:
<INPUT TYPE="submit" VALUE="Executar" name="1" id="Execute"
style="visibility:hidden" onMouseOver="window.status='URL: http://jlex1x2-uocpfc.rhcloud.com'"
onMouseOut="window.status=''">

It works with:

*

*IE 6 and Mozilla Firefox 36.0.4: See my onMouseOver.

It doesn't work with:

*

*Mozilla Firefox 9.01 and Chrome 41.0: Nothing it appears.

*IE 9: It appears '*.rhcloud.com/directory/filename.jsp#'
EDIT 2 APR:

*

*My form (simplifyed) is this (without my textarea):

:
<FORM action="#" METHOD="POST">
... // Initial code
</FORM>

I would like to improve my INPUT (for all browsers) with only '*.rhcloud.com'.

A: Working fine for me..Just remove the style="visibility".
Here is my code and output screenshot :

<INPUT TYPE="submit" VALUE="Executar" name="1" id="Execute"
onmouseover="window.status='http://jlex1x2-uocpfc.rhcloud.com'"
onmouseout="window.status=''">


text:
Q: How to make calabash-ios tests run within CircleCI? How can you run calabash-ios tests within CircleCI?
This is what I have tried:
machine:
  xcode:
    version: "6.3.1"

dependencies:
    override:
        - sudo gem install calabash-cucumber
        - sudo gem install cocoapods

test:
    overrride:
        - pod setup
        - pod install
        - calabash-ios gen
        - cucumber

And after installing calabash, CircleCI does not end up running the commands written in my .feature file. Any ideas?

A: I fixed it by changing to this:
machine:
  xcode:
    version: "6.3.1"

dependencies:
    override:
        - sudo gem install calabash-cucumber
        - sudo gem install cocoapods

test:
    pre:
        - pod setup
        - pod install
    post:
        - cucumber


text:
Q: Why does jQuery's remove() method accept a selector? I noticed a strange thing when using remove from jQuery. Although jQuery cleary states that:

selector
  Type: String
  A selector expression that filters the set of matched elements to be removed.

If you try this code:
$element.remove('.k-grouping-header,.k-group-cell,.k-group-col,.k-grouping-row');

it won't work as expected and you have to use
$element.find('.k-grouping-header,.k-group-cell,.k-group-col,.k-grouping-row').remove();

Did you guys noticed it as well or it is only me doing something wrong?
JSFiddle: http://jsfiddle.net/YzfRT/

A: remove() will take all elements that are selected out of the DOM, whether you pass an argument or not.
Passing an argument (selection) to remove() will filter those elements to match that selection.
Presumably in the first instance, you have your parent selected. remove() would try to remove this element, but since it (probably) doesn't match .k-grouping-header,.k-group-cell,.k-group-col,.k-grouping-row it will stay where it is.
Your confusion probably comes from not understanding the difference between filtering and finding
Your second attempt is correct.
Why allow a selector at all?
Primarily for chaining. Consider you have many elements selected to call a jQuery method on, maybe you'd like to change the colour:
$('div').css({color:"#F00"})

But then you only wanted to remove the ones with the class .remove? You can still chain, and filter the ones to remove:
$('div').css({color:"#F00"}).remove('.remove')

Which, by the way, does exactly the same as:
$('div').css({color:"#F00"}).filter('.remove').remove()

JSFiddle

A: You see, there written filtering. It means that you should choose for example in this

so you should write
$('div').remove('.orion');

Because it's filtering classes from each chosen elements, but it doesn't work like $('body').remove('orion'), something like $('body').find('.orion').remove();
That's all.

A: The argument inside the .remove() function is used as a filter to the selector,
So,
$('div').remove('.abc')
will remove
s with class abc, not its children with class abc.

In your case,use
$('p',$element).remove('.k-grouping-header,.k-group-cell,.k-group-col,.k-grouping-row');

Demo


text:
Q: Does 'du' command count the size of unaccessible folders? I am trying to get the size of an user's folder named allysek and I am using this command du -hLlxcs allysek. I know I don't have permissions to some of the locations.
In the end, I get an output as follows,
du: cannot access '/export/mite-09/bc/users/allysek/charlet/PS-tools-mjyger/PS-NOVA/IMR90.NOMe-seq.bam'
du: cannot access '/export/mite-09/bc/users/allysek/charlet/PS-tools-mfter/PS-NOVA/IMR90.NOMe-seq.bam.bai'
du: cannot access '/export/mite-09/bc/users/allysek/charlet/PS-tools-iuhgi/PS-NOVA/colon.WGBS.bam'
du: cannot access '/export/mite-09/bc/users/allysek/charlet/PS-tools-kh/PS-NOVA/colon.WGBS.bam.bai'
du: cannot access '/export/mite-09/bc/users/allysek/charlet/PS-tools-h/PS-NOVA/dbNOVA_135.hg19.sort.vcf'
du: cannot access '/export/mite-09/bc/users/allysek/charlet/PS-tools-master/PS-NOVA/hg19_rCRSchrm.fa'
du: cannot access '/export/mite-09/bc/users/allysek/charlet/PS-tools-master/PS-plot/DKO1.NOMe-seq.bam'
du: cannot access '/export/mite-09/bc/users/allysek/charlet/PS-tools-master/PS-plot/DKO1.NOMe-seq.bam.bai'
896M    /export/mite-09/bc/users/allysek
896M    total

So my question is, does the 896M    total include sizes of items which I wasn't able to access as well?

A: du is an ordinary command running with your privileges and access rights. Just like ls. What you can see is what it can see, so it cannot count files that you cannot access.
You can tell it not to complain about files it cannot access by discarding stderr:
du -hLlxcs allysek 2>/dev/null

A: No.  Compare the output of
du -shc /

vs
sudo du -shc /

A: Simply not.
Look this example
du -shc *
4,0K    AUDIO_TS
4,4G    VIDEO_TS
4,4G    total
chmod 000 * #don't use this in wrong dir!
du -shc *
du: cannot read directory 'VIDEO_TS': Permission denied
du: cannot read directory 'AUDIO_TS': Permission denied
4,0K    AUDIO_TS
4,0K    VIDEO_TS
8,0K    total


text:
Q: Can't add GeoJSON layer to ArcGis js 4.4 I am new to ArcGis.  I created a JSON service that creates a GeoJSON file.  I ran the output through GeoJSONLint and it is exactly what I'm expecting and the point features show up on their map.
Here's my GeoJSON:
{
    "metadata": {
        "title": "Hurricane Track"
    },
    "type": "FeatureCollection",
    "features": [{
        "properties": {
            "strength": "#initial",
            "descriptionHtml": " \n\t   \t
 \n

Hurricane Irma (al112017)<\/b><\/font>
<\/td><\/tr> \n
Advisory #36<\/td>
<\/tr> \n

<\/td><\/tr> \n

Advisory Information<\/td><\/tr> \n\t   \t

Valid at:  8:00 PM EDT September 07, 2017 <\/td><\/tr> \n\t
\t
Location: 21.3 N, -72.4 W <\/td><\/tr> \n\t
\t
Maximum Wind: 145 knots (165 mph) <\/td>
<\/tr> \n\t   \t
Wind Gusts: 175 knots (200 mph)
<\/td><\/tr> \n
Motion: WNW
<\/td><\/tr>\n
Minimum Pressure:
920 mb <\/td><\/tr>\n\t       "
        },
        "id": 1,
        "type": "Feature",
        "geometry": {
            "coordinates": [-72.4, 21.3],
            "type": "Point"
        }
    }, {
        "properties": {
            "strength": "#m",
            "descriptionHtml": " \n\t   \t
 \n

Hurricane Irma (al112017)<\/b><\/font>
<\/td><\/tr> \n
Advisory #36<\/td>
<\/tr> \n

<\/td><\/tr> \n

12 hr Forecast<\/td><\/tr> \n\t   \t
Valid at:  8:00 AM EDT September 08, 2017 <\/td><\/tr> \n\t
\t
Location: 21.8 N, -74.4 W <\/td><\/tr> \n\t
\t
Maximum Wind: 145 knots (165 mph) <\/td>
<\/tr> \n\t   \t
Wind Gusts: 175 knots (200 mph)
<\/td><\/tr> \n                        \n
\n\t       "
        },
        "id": 2,
        "type": "Feature",
        "geometry": {
            "coordinates": [-74.4, 21.8],
            "type": "Point"
        }
    }, {
        "properties": {
            "strength": "#m",
            "descriptionHtml": " \n\t   \t
 \n

Hurricane Irma (al112017)<\/b><\/font>
<\/td><\/tr> \n
Advisory #36<\/td>
<\/tr> \n

<\/td><\/tr> \n

24 hr Forecast<\/td><\/tr> \n\t   \t
Valid at:  8:00 PM EDT September 08, 2017 <\/td><\/tr> \n\t
\t
Location: 22.3 N, -76.7 W <\/td><\/tr> \n\t
\t
Maximum Wind: 140 knots (160 mph) <\/td>
<\/tr> \n\t   \t
Wind Gusts: 170 knots (195 mph)
<\/td><\/tr> \n                        \n
\n\t       "
        },
        "id": 3,
        "type": "Feature",
        "geometry": {
            "coordinates": [-76.7, 22.3],
            "type": "Point"
        }
    }, {
        "properties": {
            "strength": "#m",
            "descriptionHtml": " \n\t   \t
 \n

Hurricane Irma (al112017)<\/b><\/font>
<\/td><\/tr> \n
Advisory #36<\/td>
<\/tr> \n

<\/td><\/tr> \n

36 hr Forecast<\/td><\/tr> \n\t   \t
Valid at:  8:00 AM EDT September 09, 2017 <\/td><\/tr> \n\t
\t
Location: 22.9 N, -78.6 W <\/td><\/tr> \n\t
\t
Maximum Wind: 135 knots (155 mph) <\/td>
<\/tr> \n\t   \t
Wind Gusts: 165 knots (190 mph)
<\/td><\/tr> \n                        \n
\n\t       "
        },
        "id": 4,
        "type": "Feature",
        "geometry": {
            "coordinates": [-78.6, 22.9],
            "type": "Point"
        }
    }, {
        "properties": {
            "strength": "#m",
            "descriptionHtml": " \n\t   \t
 \n

Hurricane Irma (al112017)<\/b><\/font>
<\/td><\/tr> \n
Advisory #36<\/td>
<\/tr> \n

<\/td><\/tr> \n

48 hr Forecast<\/td><\/tr> \n\t   \t
Valid at:  8:00 PM EDT September 09, 2017 <\/td><\/tr> \n\t
\t
Location: 23.7 N, -79.9 W <\/td><\/tr> \n\t
\t
Maximum Wind: 135 knots (155 mph) <\/td>
<\/tr> \n\t   \t
Wind Gusts: 165 knots (190 mph)
<\/td><\/tr> \n                        \n
\n\t       "
        },
        "id": 5,
        "type": "Feature",
        "geometry": {
            "coordinates": [-79.9, 23.7],
            "type": "Point"
        }
    }, {
        "properties": {
            "strength": "#m",
            "descriptionHtml": " \n\t   \t
 \n

Hurricane Irma (al112017)<\/b><\/font>
<\/td><\/tr> \n
Advisory #36<\/td>
<\/tr> \n

<\/td><\/tr> \n

72 hr Forecast<\/td><\/tr> \n\t   \t
Valid at:  8:00 PM EDT September 10, 2017 <\/td><\/tr> \n\t
\t
Location: 27.2 N, -81.1 W <\/td><\/tr> \n\t
\t
Maximum Wind: 100 knots (115 mph) <\/td>
<\/tr> \n\t   \t
Wind Gusts: 120 knots (140 mph)
<\/td><\/tr> \n                        \n
\n\t       "
        },
        "id": 6,
        "type": "Feature",
        "geometry": {
            "coordinates": [-81.1, 27.2],
            "type": "Point"
        }
    }, {
        "properties": {
            "strength": "#s",
            "descriptionHtml": " \n\t   \t
 \n

Hurricane Irma (al112017)<\/b><\/font>
<\/td><\/tr> \n
Advisory #36<\/td>
<\/tr> \n

<\/td><\/tr> \n

96 hr Forecast<\/td><\/tr> \n\t   \t
Valid at:  8:00 PM EDT September 11, 2017 <\/td><\/tr> \n\t
\t
Location: 32.0 N, -83.5 W <\/td><\/tr> \n\t
\t
Maximum Wind: 50 knots (60 mph) <\/td><\/tr>
\n\t   \t
Wind Gusts: 60 knots (70 mph) <\/td>
<\/tr> \n                        \n
\n\t       "
        },
        "id": 7,
        "type": "Feature",
        "geometry": {
            "coordinates": [-83.5, 32.0],
            "type": "Point"
        }
    }, {
        "properties": {
            "strength": "#d",
            "descriptionHtml": " \n\t   \t
 \n

Hurricane Irma (al112017)<\/b><\/font>
<\/td><\/tr> \n
Advisory #36<\/td>
<\/tr> \n

<\/td><\/tr> \n

120 hr Forecast<\/td><\/tr> \n\t   \t
Valid at:  8:00 PM EDT September 12, 2017 <\/td><\/tr> \n\t
\t
Location: 35.5 N, -86.5 W <\/td><\/tr> \n\t
\t
Maximum Wind: 30 knots (35 mph) <\/td><\/tr>
\n\t   \t
Wind Gusts: 40 knots (45 mph) <\/td>
<\/tr> \n                        \n
\n\t       "
        },
        "id": 8,
        "type": "Feature",
        "geometry": {
            "coordinates": [-86.5, 35.5],
            "type": "Point"
        }
    }]
}

So next I have my ArcGis code:

I run this and get the topo base map displaying.  I get an error at this point saying:
init.js:321 [] #load() Failed to load layer (title: 'undefined', id: 'undefined')
e {name: "feature-layer:missing-url-or-source", message: "Feature layer must be created with either a url or a source", details: undefined}
(I realize that simply defining the feature layer is not enough to display anything yet but I was running the map at this point to see if there were any problems)
The ESRI docs are not clear about GeoJSON and what is required in the fields definition so I just sort of guessed.

A: I believe that your GeoJSON is not actually valid -  at http://geojsonlint.com/ I'm getting an error message due to the embedded HTML.
You could try removing the descriptionHtml parameter while you're testing this (you can reintroduce the description once the basics are working, using JSON syntax rather than embedded HTML).
As far as I can see, the ArcGIS Server JS API doesn't have direct support for true GeoJSON, but the featureCollection method for defining a feature layer may work. This is slightly different than the source method you've used.
Using this approach, you define the layer's properties in advance, then provide the data via an AJAX call (or use esriRequest).
There is a sample at https://developers.arcgis.com/javascript/3/jssamples/fl_featureCollection.html which demonstrates how to do this with the Flickr API, but the principle is the same with your http://localhost:8888/gis/getHurriCone.cfm service.


text:
Q: d3 tooltip not showing on top of leaflet map I'm using d3 circles on a leaflet map. I want to add tooltips on the circles, the tooltips are created as you can see on the image but they seem to be underneath the map, I want to bring them on top.
I need those tootlips to display information about the dataset used to create the circles so I can't use Leaflet tooltips.
The tooltip is there but it is underneath the map:

var mymap = L.map('map', {
  zoomControl: false
}).setView([36.71367, 3.18031], 15.5);

var width = document.getElementById('map').offsetWidth;
var height = document.getElementById('map').offsetHeight;

L.svg().addTo(mymap);

var svg = d3.select("#map").select("svg"), /* add the svg to leaflet map */
  g = svg.append("g");

function go() {

  var popup = L.popup();
  var dispo;
  //vider le dataset
  dataset = []; /* this is related to the data i'm displaying with circles */

  //Enlever les anciens cercles
  g.selectAll("circle")
    .data(dataset)
    .exit()
    .remove();

    d3.json('data/data.json', function(data) {

      //some code to fill the dataset

            pane: "tilePane"
    }).addTo(mymap); //end L.geoJSON

        dataBind();
    update();

      }); //end json

        function dataBind() {
    circles = g.selectAll("circle")
      .data(dataset)
      .enter()
      .append("circle");

  }

  mymap.on("zoomend", update);

  //Placer les cercles sur chaque salle
  function update() {

    //tooltip code
    var infobulle = d3.select("body")
      .append("div")
        .style("position", "absolute")
        .style("background", "white")
        .style("opacity", "0")
        .style("padding", "0 10px");

    circles.attr("cx",
        function(d) {
          return mymap.latLngToLayerPoint([d[4].lat, d[4].lng]).x;
        }
      ).attr("cy",
        function(d) {
          return mymap.latLngToLayerPoint([d[4].lat, d[4].lng]).y;
        }
      )
      .attr("pointer-events","visible")
      .style("opacity", 0.8)
      .attr("r", 0)
      .style("fill", function(d, i) {
            return colors(d[3].Type);
      })
      .on("mouseover", function(d){
        infobulle.transition()
          .style("opacity", .9)
          infobulle.html(" heures ")
            .style("left", (d3.event.pageX - 35 + "px"))
            .style("top", (d3.event.pageY - 30 + "px"))
      })
      .on("mouseout", function(d){
        infobulle.transition()
          .style("opacity", 0)

        })

  }

A: I think the style property z-index would be useful in this case. You can add the .style("z-index", "999") to var infobulle as:
//tooltip code
var infobulle = d3.select("body")
  .append("div")
    .style("position", "absolute")
    .style("background", "white")
    .style("opacity", "0")
    .style("padding", "0 10px")
    .style("z-index", "999");


text:
Q: Objective-C address book I have two Objective-C classes that inherit from the UIViewController and am trying a different approach at learning how to interact with the iPhone's address book. The example Apple provides assumes that everything is in one class, but this isn't the way I need it done. My objective would be to have the address book view close after a person is selected. Please have a look and let me know how i can accomplish this without having CallerClass implement ABPeoplePickerNavigationControllerDelegate. Thanks!
-- edit --
What it seems to be boiling down to is the [self dismissModalViewControllerAnimated:YES]; does not have any effect in CalleeClass.m. I still can't seem to get a reaction to close the address book from this command.
CallerClass.m
#import "CallerClass.h"

@implementation CallerClass
- (IBAction)openAddressBook {
    CalleeClass *cc = [[CalleeClass alloc] init];
    [self presentModalViewController:[cc doIt] animated:YES];
}

CalleeClass.h
#import <UIKit/UIKit.h>
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>

@interface CalleeClass : UIViewController <ABPeoplePickerNavigationControllerDelegate> {
    NSString *name;
}

-(ABPeoplePickerNavigationController *)doIt;

@property (nontoxic, retain) NSString *name;

@end

CalleeClass.m
#import <UIKit/UIKit.h>
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import "CalleeClass.h"

@implementation CalleeClass
@synthesize name;

… (default ABPeoplePickerNaviationControllerDelegate implementation outside of what's listed)
- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {}
    return self;
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
    self.name = (NSString *)ABRecordCopyValue(person,kABPersonAddressProperty);

    [self dismissModalViewControllerAnimated:YES];
    return NO;
}

-(ABPeoplePickerNavigationController *)doIt {
    ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
    picker.peoplePickerDelegate = self;
    return picker;
}

@end

A: If the problem is, as you say, that [self dismissModalViewControllerAnimated:YES] has no effect if called from CalleeClass, this is because dismissModalViewControllerAnimated: must be called on the presenting view controller (i.e., the one on which you called presentModalViewController:Animated:. Since you don't have a reference to your CallerClass instance in CalleeClass, this doesn't work.
Fortunately, as the documentation for dismissModalViewControllerAnimated: notes:

If you call this method on the modal view controller itself, however, the modal view
  controller automatically forwards the message to its parent view controller.

So this should work:
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
    self.name = (NSString *)ABRecordCopyValue(person,kABPersonAddressProperty);
    [peoplePicker dismissModalViewControllerAnimated:YES];
    return NO;
}

A: Once you have identified the contact you want to act on you can just pass around the int32 recordID, although as mentioned in the API docs you should probably also use the composite name since as you will notice the recordID is a simple value that starts with "1" and you could run into trouble if your database was restored to a phone with new contacts in old recordID values. Every time you need to access something from the Address Book you do need to create the phone book but you can close it right after, so with recordID you can open, get what you want and then close it. My suggestion is just use the picker like a normal view controller up to the point where you get the recordID, dismiss it, then keep that unique identifier. Use picker again when you need to find a new recordID.


text:
Q: Converting MySQL Query to Yii CDbCriteria I have two table which is named

*

*new_tbl_master_siteid -> model : SiteID

*app_tbl_ict_dapot_genset -> model : genset

and i have a mysql query like this
SELECT A.siteid, B.type, B.status_operations, B.status
FROM new_tbl_master_siteid as A
LEFT JOIN app_tbl_ict_dapot_genset as B
ON A.siteid = B.siteid

Where i want to left join the siteid column
I was thinking of modifying the CdbCriteria on the genset model, how can i do this so the dataprovider of the genset gridview can also use the column from the SiteID model?
Criteria from the genset model
$criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        $criteria->compare('siteid',$this->siteid,true);
        $criteria->compare('merk',$this->merk,true);
        $criteria->compare('type',$this->type,true);
        $criteria->compare('capacity',$this->capacity,true);
        $criteria->compare('kapasitas_tangki',$this->kapasitas_tangki,true);
        $criteria->compare('status',$this->status,true);
        $criteria->compare('status_operations',$this->status_operations,true);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,

==================
Here is the relation below
class genset extends CActiveRecord
.....
public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
         return array(
            'siteids'=>array(self::BELONGS_TO,'SiteID','siteid'),
        );
    }
....

public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        $criteria->compare('siteid',$this->siteid,true);
        $criteria->compare('merk',$this->merk,true);
        $criteria->compare('type',$this->type,true);
        $criteria->compare('capacity',$this->capacity,true);
        $criteria->compare('kapasitas_tangki',$this->kapasitas_tangki,true);
        $criteria->compare('status',$this->status,true);
        $criteria->compare('status_operations',$this->status_operations,true);
        $criteria->with = array('siteids.rtp');
        $criteria->compare('siteids.rtp',$this->rtp,true);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }

and the siteid class
class SiteID extends CActiveRecord
.....
public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'gensets'=>array(self::HAS_MANY, 'genset', 'siteid'),
        );
    }

But i got an error
Relation "rtp" is not defined in active record class "SiteID".

rtp is a column from the siteid model

A: Yii way to do this is thru Relations e g you should add relation to the joined table into your model (if it is not already there) and then you can directly access to related model's properties, for example if SiteID object is $model and  relation's name is 'genset', you can get genset's status like this:  $model->genset->status

A: First thing you have to do is create relation between models that can be done like this :
public function relations()
{
        return array(
            'genset'=>array(self::HAS_MANY, 'genset', 'siteid'),
        );
}

in model class. Once relations are defined in both models modify your criteria to pull result with join using ->with
$criteria->with = array('genset');

and you are ready to go. but make sure you define relation in both the models.


text:
Q: Number of significant figures in a chi square fit I'm working on a scientific paper in which goodness-of-fit and a parameter are estimated by a $\chi^2$ minimization, and I'd like to know whether there is a general rule for how many significant figures one should quote for the value of the $\chi^2$ and its resulting P-value.
In particular I'm fitting one parameter from data in 31 bins, each with its contents in the gaussian regime. I'd guess the precision of my minimization algorithm is not the limiting factor (my code spits out $\chi^2$ = 38.8898 / 30, so the P-value is something like 0.1282) for signifcant figures, but what is? Is it the number of degrees of freedom? The degree to which the gaussian assumption is invalid in the least-populated bin(s)? Most papers I see typically quote to tenths in $\chi^2$ (so 38.9 / 30 in my case) and hundredths in P-value (0.13 for me), but I'm not sure if that's always reasonable.
P.S.- I'd like to apologize if any terminology I used is funny: in physics we use annoyingly non-standard terms when discussing statistics.

A: Those things are data summaries, so one way to decide on significant figures is to keep whittling them down until the summary starts to lack adequate precision or seems unreasonable. I know that that response is not very specific, but consider this: no-one would respond differently to P = 0.13 from P=0.1282. For the Chisq value, I would whittle it down as far as you did, or further if the rounded value still yields the P = 0.13.
There is a paper in The American Statistician which talks about the precision of P-values. I don't agree with all that it says, but it is relevant to your question: Boos & Stefanski, The American Statistician, 2011, 65, 213


text:
Q: Where is ssh daemon log file I am facing a strange issue on my Centos 5.5 VMware virutal machine. SSHD service stops  responding after working for few days. At the same time cmd>telnet server 22 give me no response.
It works when I restart manually
service sshd restart

I want to identify what is going wrong with SSH daemon. For this I have changed the log verbosity to DEBUG3 in /etc/ssh/sshd_config file, but I am unable to see any logs in /var/log/messages.
Can anyone help me to find the log file where I can see crash message whenever SSH daemon stops responding?

A: Try to check:
/var/log/auth.log

Try to edit this options at sshd_config
# Logging
#SyslogFacility AUTH    # <- says to log auth.log, check syslog.conf for additional configuration, or even update remove syslog and install rsyslog.
#LogLevel INFO          # <- edit verbosity


text:
Q: How to apply validation for email id text box in window phone 7? I want to apply validation to text box.
How to apply validation for email id text box in window phone 7?

A:  public static bool IsValidEmail(string strIn)
   {
       // Return true if strIn is in valid e-mail format.
       return Regex.IsMatch(strIn,
              @"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))" +
              @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$");
   }

using System;
using System.Text.RegularExpressions;

A: Change your email TextBox's InputScope property to EmailNameAddress
and use this
Match match = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$").Match(txtEmail.Text);

if (match.Success)
{
     MessageBox.Show("Valid Email");
}    else    MessageBox.Show("Invalid Email");

A: You can change the InputScope property of the textbox into EmailNameAddress

A: //Say the text box's name as txtEmail

    using System;
    using System.Text.RegularExpressions;

    private void txtEmail_Validating(object sender,
                    System.ComponentModel.CancelEventArgs e)
    {
       string errorMsg;
       if(!ValidEmailAddress(txtEmail.Text, out errorMsg))
       {
          // Cancel the event and select the text to be corrected by the user.
          e.Cancel = true;
          txtEmail.Select(0, txtEmail.Text.Length);

          // Set the ErrorProvider error with the text to display.
          this.errorProvider1.SetError(txtEmail, errorMsg);
       }
    }

    private void txtEmail_Validated(object sender, System.EventArgs e)
    {
       // If all conditions have been met, clear the ErrorProvider of errors.
       errorProvider1.SetError(txtEmail, "");
    }
    public bool ValidEmailAddress(string emailAddress, out string errorMessage)
    {
       // Confirm that the e-mail address string is not empty.
       if(emailAddress.Length == 0)
       {
          errorMessage = "e-mail address is required.";
             return false;
       }

 // Confirm that the e-mail address in correct regex format
if (Regex.IsMatch(emailAddress,
              @"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))" +
              @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$")==false)

       // Confirm that there is an "@" and a "." in the e-mail address, and in the correct order.
       if(emailAddress.IndexOf("@") > -1)
       {
          if(emailAddress.IndexOf(".", emailAddress.IndexOf("@") ) > emailAddress.IndexOf("@") )
          {
             errorMessage = "";
             return true;
          }
       }

       errorMessage = "e-mail address must be valid e-mail address format.\n" +
          "For example 'someone@example.com' ";
          return false;
    }

A: if (string.IsNullOrEmpty(email))
                return false;
            var regex = new System.Text.RegularExpressions.Regex(@"\w+([-+.']\w+)@\w+([-.]\w+).\w+([-.]\w+)*");
            return regex.IsMatch(email) && !email.EndsWith(".");

A: Write a helper method like below :
private bool IsVaildEmail(string email)
    {
        return Regex.IsMatch(email, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z");
    }

Call this method and pass the email id which returns true if matched and false if unmatched. Simple.


text:
Q: Run Time Error '13': Type mismatch I have created a macro file to run a greedy algorithm, that is a heuristic process of assigning the work with the greatest value with to the idle server. The macro should assign 26 works to two workstations running the greedy algorithm.
At first I must determine if the task was assigned and then I must determine which unassigned task has the greatest task time and move on. This should be a pretty straightforward code but I have trouble reading the task times from the spreadsheet which range from (C2:C27). I have written the following code but I get a Run Time Error '13': Type  mismatch at the line I have marked with two **:
Sub GreedyAlgorithm()

Dim totalA As Integer
Dim totalB As Integer
Dim nbA As Integer
Dim nbB As Integer
Dim maxRN As Integer
Dim maxTT As Integer

totalA = 0
totalB = 0
nbA = 0
nbB = 0

For i = 1 To 26
    maxRN = 0
    maxTT = 0

    For j = 2 To 27
        If IsEmpty(Sheet2.Cells(j, 5)) Then
            If Sheet2.Cells(j, 3).Value > maxTT Then
            maxRN = j
            **maxTT = Sheet2.Cells(j, 3).Value
            End If
        End If
    Next j

    If totalB > totalA Then
        Sheet2.Cells(maxRN, 5).Value = "A"
        nbA = nbA + 1
        Sheet2.Cells(maxRN, 6).Value = nbA
        totalA = totalA + maxTT
    ElseIf totalB <= totalA Then
        Sheet2.Cells(maxRN, 5).Value = "B"
        nbB = nbB + 1
        Sheet2.Cells(maxRN, 6).Value = nbB
        totalB = totalB + maxTT

    End If
Next i
End Sub

What might be the reason for this? I have went back to my spreadsheet and manually set the data types as number for my range. This still has not solved the problem.

A: The reason is most probably with the data you are trying to assign an Integer with. I tried with 3, and got no issues. Max. Integer value in VBA is 32767.
I'd suggest to declare the maxTT variable as Long.
Dim maxTT As Long

There may be other issues, but without the input it is difficult to guess.


text:
Q: CSS positioning differences Safari vs. Chrome I have different positioning results in Safari and Chrome testing.
CSS....
.home #colophon  {
    margin-top: -150px;
    background-color: #000;
    opacity: .6;
    height: 150px;
}
.home #colophon .textwidget {
    color: #FFF;
    margin-top: -150px;
}

HTML...

                    <?php if (bswp_option('footer-banner-title') != '') {
                        echo bswp_option('footer-banner-title');
                        } ?>

                    <?php dynamic_sidebar( 'footer-1' ); ?>

                    <?php dynamic_sidebar( 'footer-2' ); ?>

                    <?php dynamic_sidebar( 'footer-3' ); ?>

Here is my page...
http://dougragerarchitect.com/
I would like to keep my address block over the black transparent area with both browsers.


text:
Q: Java MSAccess DSN Less So the problem is that I want to make a connection to a msaccess database that has password every time you open it.

*

*The password works if I directly open the access file.

*I can make the connection if I remove the password, which means my code works if there is no password involve

*The password was set using Set database Password in the database tools

*MS Access 2007(but i used the .mdb)

Here's the code
String dbFile = "db.mdb";
String connectionString = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
String driverID = ";DriverID=22;READONLY=true;pwd=qwer}";
if (CONNECTION == null || CONNECTION.isClosed()) {
   dbURL = connectionString + dbFile.trim() + driverID;
   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
   CONNECTION = DriverManager.getConnection(dbURL);
}

----------------------------------------------
Error Code : java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Not a valid password.
----------------------------------------------

I already tried adding parameters to the get connection but it did not work.
Please Help :)

A: There are 2 types of passwords for MS Access database files:

*

*user passwords

*database password

With a user password, you supply the user name and password in the connection string.
;User Id=admin;Password=;

For a database password, you need a different identifier in the connection string to distinguish the password as a database password rather than a user password.
;Database Password=MyDbPassword;

Personally I don't use a database password.  That feature doesn't offer much in the way of security, so it seems like it's more trouble than it's worth.
Edit: I don't know if it's possible to supply a database password with an ODBC connection.  All the connection examples I found used OLE DB when including a database password.
Conn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=\\somepath\\mydb.mdb;" & _
                 "Jet OLEDB:Database Password=MyDbPassword;", "admin", ""

Perhaps it could work to switch from the current Access ODBC driver to the Microsoft OLE DB Provider for ODBC.  Or maybe with the current ODBC driver if you switch
Database Password=MyDbPassword;

to
Jet OLEDB:Database Password=MyDbPassword;

I don't know.  But seems to me the database password is just getting in your way here.  You already know you can connect if you remove the password from the database.


text:
Q: Cacti generate old graph I have a cacti system (Version 0.8.8b). The cacti system has been running for a year.
I would like to generate retroactive daily graphs, because cacti can't show the old daily graphs.
How to generate old daily graphs?
thank you very much

A: Essentially, you can't because the data is gone.
Cacti uses rrdtool to store the data and this tool works by storing detailed records for only a short time and then aggregating this data into lower time resolution for longer time periods. As an example, it might store data in

*

*5 minute intervals for a day

*30 min intervals for a week (averaging 6 of the last five minute data points)

*Hourly intervals for a month (again averaging the 30min data points).

*Daily intervals for a year  (see above...)

This has the advantage that each metric you record needs a fixed amount of storage but at the price of data loss from older time points.


text:
Q: Loop through several check boxes and update inputs on results I have several check boxes that I need to post the value of when a form is submitted. There is 4 at the moment and could be more so I was thinking of instead of adding individual functions is it possible to loop through them all and update respected fields in one go. I have seen a similar thing with form population with google maps but not quite the same. So I have a input like so:

function myCheck() {
    var checkBox = document.getElementById("email_alerts");
    if (checkBox.checked == true){
        document.getElementById('form_email_alerts').value = 'YES'
    } else {
        document.getElementById('form_email_alerts').value = 'NO'
    }
}

Please confirm your contact preferences

<input type="checkbox" id="email_alerts" value="YES" onclick="myCheck()"> Receive email alerts

<input type="checkbox" id="sms_alerts" value="NO" onclick="myCheck()"> Receive free SMS alerts

<input type="checkbox" id="offers_alerts" value="NO" onclick="myCheck()"> Receive offers and discounts

<input type="checkbox" id="instant_alerts" value="NO" onclick="myCheck()"> Receive Instant Notifications

<input id="form_email_alerts" type="hidden" value="">
<input id="form_sms_alerts" type="hidden" value="">
<input id="form_offers_alerts" type="hidden" value="">
<input id="form_instant_alerts" type="hidden" value="">

I could add this 4 times or more with different ID but can I just loop through so be quicker and cleaner? I have tried but cant get it to change the hidden values. Thanks

A: You could do that by looping on all your checkboxes and adding an event listener on each, updating the other input fields.
PS: here I removed the hidden type for you to see the value of every input.

document.querySelectorAll('ul.details li input').forEach(input => {
  input.addEventListener('change', function(){
    let finalInput = document.querySelector('#form_'+input.id);
    if(finalInput) finalInput.value = input.checked ? 'YES' : 'NO';
  });
});

Please confirm your contact preferences

<input type="checkbox" id="email_alerts" value="YES"> Receive email alerts

<input type="checkbox" id="sms_alerts" value="NO"> Receive free SMS alerts

<input type="checkbox" id="offers_alerts" value="NO"> Receive offers and discounts

<input type="checkbox" id="instant_alerts" value="NO"> Receive Instant Notifications

<input id="form_email_alerts" value="">
<input id="form_sms_alerts" value="">
<input id="form_offers_alerts" value="">
<input id="form_instant_alerts" value="">

A: As your IDs have a good format, you can just loop all checkboxes:

document.querySelectorAll('input[type=checkbox]').forEach(e => {
  e.onchange = () => document.getElementById('form_' + e.id).value = e.checked ? 'YES' : 'NO';
});

Please confirm your contact preferences

<input type="checkbox" id="email_alerts" value="YES"> Receive email alerts

<input type="checkbox" id="sms_alerts" value="NO"> Receive free SMS alerts

<input type="checkbox" id="offers_alerts" value="NO"> Receive offers and discounts

<input type="checkbox" id="instant_alerts" value="NO"> Receive Instant Notifications

<input id="form_email_alerts" type="text" value="NO">
<input id="form_sms_alerts" type="text" value="NO">
<input id="form_offers_alerts" type="text" value="NO">
<input id="form_instant_alerts" type="text" value="NO">


text:
Q: How do I properly organize this Rx-based reactive state machine? Please note: Despite me using Swift-lang in the examples, I encourage you to try and help me even if you know RxJava and rxjs or any other Rx implementation.
Question: I have a state machine that is written imperatively. I would like to rewrite reactively using Rx but I am struggling with coming up with the ways to do it proper.
Current imperative system looks like this:
var state: State
var metaState: MetaState

func updateMetaStateIfNeeded() {
    if Bool.random() {
        metaState = MetaState()
    }
}

func tick() -> State {
    updateMetaStateIfNeeded()

    let newState = State(currentState: state, metaState: metaState)
    self.state = newState
    return newState
}

What I came up with so far:
let tick = PublishSubject<Void>()
let metaState = BehaviorSubject<MetaState>()
let state = BehaviorSubject<State>()

let tickAfterMetaStateUpdate = PublishSubject<Void>()

tick -> withLatestFrom metaState -> map to new metaState if update needed or the old one -> put result into metaState AND tickWithUpdatedMetaState

tickAfterMetaStateUpdate -> withLatestFrom state AND metaState -> map State(currentState: state, metaState: metaState) -> put result into state

(The users of this API subscribe to state subject, which will be updated every tick)

I am dissatisfied with this result I came up with. I wonder if it's possible to rewrite this using scan or reduce so that there is no usage of Subjects and it's a plain Observable.
UPDATE after @Daniel T.'s answer:
Wow, this was exactly the proper solution! I have prepared the analytics:

*

*There are 2 state machines, one for metaState update, one for state update

*Each of them has it's own start states which we don't need to specify

*The input alphabet for metaState is Void, a mere presence of a tick. For state, it's the metaState output of the first state machine

So with this understanding, I have rewriten the system using 2 scans:
let state = tick
    .scan(MetaState()) { currentMetaState, void in
        if Bool.random() {
            return MetaState()
        }
        return currentMetaState
    }
    .scan(State()) { currentState, currentMetaState in
        State(currentState: state, metaState: metaState)
    }

WINRAR! Mind_blown.jpg! Actually, now with hind-sight it kinda seems obvious... :) Thank you, thank you, thank you!

A: Hmm... Yes, scan is the go to operator for implementing a state machine. To do it, you need a finite set of states (usually implemented as a struct, but it could be an enum,) a start state (usually implemented using a default constructor on the State struct,) an input alphabet (usually implemented as an enum, often called some variant of Event, Command or Action,) and a transition function (the closure passed to the scan.)
So the real question here is what are the commands/actions that change the state? Most of the time, the actions are produced by user actions, but your question doesn't really give an indication of what actions are, what the input alphabet is...
Sadly, there isn't enough information in the question to give more details than that.
-- UPDATE --
Sorry, but your update is not correct. The closure passed to scan should be pure and the first one is most assuredly not. Even if the MetaState.init() is pure, the Bool.random() isn't.
The only time you should pass an impure closure into an Observable is when you are creating a new Observable, consuming the final result, or within a do.
A simple fix to what you have looks like this:
let state = tick
    .flatMap { // this closure is an Observable factory. You can do impure things here.
        Observable.just(Bool.random() ? MetaState() : nil)
    }
    .scan(State()) { currentState, metaState in // this closure should be pure.
        if let metaState = metaState {
            return State(currentState: currentState, metaState: metaState)
        }
        else {
            return currentState
        }
    }

It's a minor change for sure, but it more clearly shows the intent of the code and makes clear what can, and can't be unit tested.


text:
Q: Google Sheets script hangs on getRange POST UPDATE:
Hi, at the end the problem was seemingly not related to the getvalue() itself but to the source, which was a range imported by an IMPORTRANGE formula. This formula was bugging. I do not really know why but I assume it was somehow related to the size of the spreadsheet. I have not been able to check this point. I tried to download the file without success. Finally, I have build a new spreadsheet. Things now seem to be working alright now. But still I'd like to now what happened to understand how to avoid it next time.
Anyway, thank you for your help.
ORIGINAL POST:
I experiencing problems with the getRange function in GAS. It's quite a simple code which was working normally until something (I do not know what) went wrong and then started to fail. I am just trying to gather a date value from a cell to use it afterwards to create an email.
I am trying to debug the code step by step by means of Logger and vars but I am struggling to figure out what happens when I try to getValue from the corresponding monocell range.
This below is the code I am trying currently:
// Retreive email receipts from Form submitted choice

function EmailUpdatefromForm()
{

  var spreadsheet = SpreadsheetApp.openById("1ImOXXXXXxSDz8AqjMWtuSPtg7xMejqPpHQ9vwDnY");

  var form = FormApp.getActiveForm();
  var formResponses = form.getResponses();

  var formlength = formResponses.length;
  Logger.log(formlength);

    var formResponse = formResponses[formResponses.length-1];
    var itemResponses = formResponse.getItemResponses();

    var itemlength = itemResponses.length;
    Logger.log(itemlength);

    for (var j = 0; j < itemResponses.length; j++) {
      var itemResponse = itemResponses[j];
      var emailto = itemResponse.getResponse();
      Logger.log(itemResponse+" - "+emailto);
    }

  var email = (emailto? emailto[0] : "xxxxxxxxxxs@xxxxxxx.com");
  var sheet = spreadsheet.getSheetByName("report");

  var log1 = spreadsheet.getId(); //--> THIS CHECKPOINT WORKS AND GETS THE PROPER SS ID
  var log2 = sheet.getSheetId(); //--> THIS CHECKPOINT WORKS AND GETS THE PROPER SHEET ID
  var log3 = sheet.getRange(2, 1) //--> THIS CHECKPOINT WORKS ALTHOUGH I CANNOT SEE IF IT IS ACTUALLY POINTING TO THE PROPER CELL

  var log4 = sheet.getRange(2, 1).getValues(); //--> THIS CHECKPOINT GETS STUCK\\

  var updatedate = sheet.getRange(2,1).getValue(); //--> THIS IS WHAT I REALLY WANT TO DO
  var PDFdate = Utilities.formatDate(updatedate, "GMT+1", "yyyyMMdd")

}

I have found several posts mentioning issues with getRange but I have not found any response really clarifying what's happening here and how to turn it around.
Thank you in advance for your support!

A: function EmailUpdatefromForm() {
  var spreadsheet = SpreadsheetApp.openById("1ImOXXXXXxSDz8AqjMWtuSPtg7xMejqPpHQ9vwDnY");
  var form = FormApp.getActiveForm();
  var formResponses = form.getResponses();
  var formlength = formResponses.length;
  Logger.log(formlength);
  var formResponse = formResponses[formResponses.length-1];
  var itemResponses = formResponse.getItemResponses();
  var itemlength = itemResponses.length;
  Logger.log(itemlength);
  for (var j = 0; j < itemResponses.length; j++) {
    var itemResponse = itemResponses[j];
    var emailto = itemResponse.getResponse();
    Logger.log(itemResponse+" - "+emailto);
  }
  var email = (emailto? emailto[0] : "xxxxxxxxxxs@xxxxxxx.com");
  var sheet = spreadsheet.getSheetByName("report");
  var log1 = spreadsheet.getId();
  var log2 = sheet.getSheetId();
  var log3 = sheet.getRange(2, 1);
  var log4 = log3.getValue();
  var updatedate = log4;
  var PDFdate = Utilities.formatDate(updatedate, "GMT+1", "yyyyMMdd")
}


text:
Q: jquery selector id,class,rel etc where value greater than a given number I would like to fade all divs that have a numeric attribute greater than or less than a given number.
Something like $( "div[id$=2]" ).fadeTo("slow", 0.6);
but I would like to use the ">" or "<" operator instead of "="
basically I would name all my divs something like

text

text

text

and then use
$( "div[id$>35]" ).fadeTo("slow", 0.6);

to fade out the last cell

A: First of all, your HTML is not valid. ID attribute should not start with a number.
do it like this,

text

text

text

then jQuery
var divs = $('.fade').map(function(){
                if (this.id.replace('div','') > 35) return '#'+this.id;
           }).get().join(',');

$(divs).fadeTo("slow", 0.6);

You may play it here.
this works too,
var divs = $('.fade').map(function(){
            if (this.id.replace('div','') > 22) return this;
       }).get();
$(divs).fadeOut("slow");

as Russ Cam suggested to use filter,
var divs = $('.fade').filter(function(){
            return (this.id.replace('div','') > 22);
       });
$(divs).fadeOut("slow");

A: This isn't valid HTML.  An id may not start with a digit.  Instead, you may find the :gt selector helpful.  You can use, e.g. td:gt(4) to find those tds with 0-index > 4, or #container div:gt(1) to find divs in container with index > 1.


text:
Q: How to use columns with special characters in Altair I'm pretty new to the Altair library. I'm having difficulties producing graphs if the variable to be plotted has an object dtype in the pandas dataframe.
I tried a barchart and a boxplot without much luck. Any help is much appreciated.
Barchart:
I'm trying to create a chart that looks like the following:

I have read the Altair documentation and tried the following code:
alt.Chart(psy).mark_bar().encode(x = alt.X('player.q_mother_language', title = 'Mother language'), y  ='count()', color = 'player.q_mother_language')

The graph that the code delivers is:

Boxplot
Then I decided to try some boxplots.
THe boxplot that I want to produce is:

The code I have used is:
alt.Chart(psy).mark_boxplot().encode(x = 'player.q_gender', y = 'player.q_age', color = 'player.q_gender')

The result I get is:

The dataset looks like the following:
player.q_mother_language,player.q_country,player.q_age,player.q_gender
Czech,Czech,21,Male
Serbian,Serbia,23,Female
German,Austria,26,Male
German,Austria,21,Female
Portuguese,Portugal,21
Russian,Kazakhstan,22,Female
Mongolian,Mongolia,32,Female
Ukrainian,Ukraine,19,Female
German,Austria,22,Male

Thank you for all your help

A: The problem is that special characters in column names (including periods, brackets, and quotations) are used to indicate hierarchical variables. To proceed with your chart, you should either rename the columns so they don't contain special characters, or escape those special characters in the chart encoding.
Here is an example of the latter approach:
import pandas as pd
import io
import altair as alt

data = """player.q_mother_language,player.q_country,player.q_age,player.q_gender
Czech,Czech,21,Male
Serbian,Serbia,23,Female
German,Austria,26,Male
German,Austria,21,Female
Portuguese,Portugal,21
Russian,Kazakhstan,22,Female
Mongolian,Mongolia,32,Female
Ukrainian,Ukraine,19,Female
German,Austria,22,Male
"""

psy = pd.read_csv(io.StringIO(data))

alt.Chart(psy).mark_bar().encode(
    x= alt.X(r'player\.q_mother_language', type='nominal', title = 'Mother language'),
    y='count()',
    color=alt.Color(r'player\.q_mother_language', type='nominal')
)


text:
Q: Failed to enqueue tests.: An unknown exception occurred While running unit Tests in my Sandbox, i got the Following Error and i cannot continue with tests.
Message is:
Failed to enqueue tests.: An unknown exception occurred.
Any ideas ?

A: The reason of the given error message is that maximum amount of unit tests executions per 24 hours is reached.
According to the documentation:

The maximum number of test classes you can run per 24-hour period is
  the greater of 500 or 10 multiplied by the number of test classes in
  the org. For sandbox and Developer Edition organizations, this limit
  is the greater of 500 or 20 multiplied by the number of test classes
  in the org.

One of the approaches could be to clone a sandbox (if there are unused licenses of same type) and run tests there.


text:
Q: Why do activities have their own Icon? Is there a specifici reason why if I have MainActivity, it has it's own Icon, yet if I create SecondActivity it has a separate icon? If I download an app from the Play store it's all from one icon. Am I just being dumb? Or is there a specific reason why this is. Thanks so much!

A: Any activity that declares the following intent filter will have an icon in the system's app listing:
<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

If you only want one icon then only put this intent filter inside your main activity.

A: Each activity can be launched independently - and thereby can have its own icon - in the Launcher. Also, I think in later APIs, the icon can be displayed inside the Activity itself.


text:
Q: How can one match a function in a replacement rule I'm trying to write a delayed replacement rule that is capable of matching both the functions and their parameters, like
h[1, k[2, x]] /. {f[n_, g[m_, x] _] _ :> f[0, g[m + n, x]]}

The idea would be that I get the output h[0,k[3,x]] for the example I give here. However, obviously the point is that I want the rule to also match, for example f[3,g[5,x]] and give the answer f[0,g[8,x]]. Is it possible to write such a rule?
Thanks.

A: Put the underscore after the name of the Head instead of after the final square brackets,
h[1, k[2, x]] /. {f_[n_, g_[m_, x] ] :> f[0, g[m + n, x]]}
(* h[0, k[3, x]] *)

f[3, g[5, x]] /. {f_[n_, g_[m_, x] ] :> f[0, g[m + n, x]]}
(* f[0, g[8, x]] *)


text:
Q: Java: Error with calling the WriteUTF method I'm having problems with writing a 2d, user-inputted array to a text file. My code thus far (in the Saving method, at least) is:
`public static void Save(String[][] EntryList)
{
   try {
        String[][] content = EntryList;
        File file = new File("CBB.dat");

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }
        InputStream instream;
        OutputStream outstream;

        instream = new DataInputStream( new BufferedInputStream(new FileInputStream(file))); // buffers the data stream
        outstream = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(file)));
        FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
        BufferedWriter writer = new BufferedWriter(fw);
        for (int row = 0; row < EntryList.length; ++row)
        {
                outstream.writeUTF(EntryList[row][1]);
                outstream.writeUTF(EntryList[row][2]);
                outstream.writeUTF(EntryList[row][3]);
                outstream.writeUTF(EntryList[row][4]);
                outstream.writeUTF(EntryList[row][5]);
            }
              outstream.close();

            }catch (IOException e) {
        e.printStackTrace();
    }
        }`

However, when I try to compile, I get the error that Java "cannot find symbol - method WriteUTF(String)"

A: Apparently there is no writeUTF defined for java.io.OutputStream.
You should probably declare outstream as DataOutputStream reference:
DataOutputStream outstream;

as the method writeUTF is defined for DataOutputStream.


text:
Q: How to circumvent "attempt to use poisoned malloc/calloc" errors with GCC? I'm building a native musl compiler (GCC 8.3.0) with a cross musl compiler (same version) and I'm getting this error:
In file included from /usr/local/x86_64-cros-linux-musl/include/pthread.h:30,
                 from /usr/local/x86_64-cros-linux-musl/lib/gcc/x86_64-cros-linux-musl/8.3.0/include/c++/x86_64-cros-linux-musl/bits/gthr-default.h:35,
                 from /usr/local/x86_64-cros-linux-musl/lib/gcc/x86_64-cros-linux-musl/8.3.0/include/c++/x86_64-cros-linux-musl/bits/gthr.h:148,
                 from /usr/local/x86_64-cros-linux-musl/lib/gcc/x86_64-cros-linux-musl/8.3.0/include/c++/ext/atomicity.h:35,
                 from /usr/local/x86_64-cros-linux-musl/lib/gcc/x86_64-cros-linux-musl/8.3.0/include/c++/bits/basic_string.h:39,
                 from /usr/local/x86_64-cros-linux-musl/lib/gcc/x86_64-cros-linux-musl/8.3.0/include/c++/string:52,
                 from ../../gcc-8.3.0/gcc/brig/brigfrontend/brig-to-generic.h:25,
                 from ../../gcc-8.3.0/gcc/brig/brig-lang.c:46:
/usr/local/x86_64-cros-linux-musl/include/sched.h:76:7: error: attempt to use poisoned "calloc"
 void *calloc(size_t, size_t);
       ^
/usr/local/x86_64-cros-linux-musl/include/sched.h:116:36: error: attempt to use poisoned "calloc"
 #define CPU_ALLOC(n) ((cpu_set_t *)calloc(1,CPU_ALLOC_SIZE(n)))
                                    ^

Any ideas on how to circumvent this?
Details:
target/host triple: x86_64-linux-musl
musl version: 1.1.21
I've applied the musl patches here: http://port70.net/~nsz/musl/gcc-8.2.0/
And I've run this command while in the source directory:
sed -e '/m64=/s/lib64/lib/' -i gcc/config/i386/t-linux64

A: So I'm going to just go ahead and assume that #pragma poison calloc is in your header files rather than in system header files.
Recommended general solution: include all system headers before using #pragma poison; this can get tricky when multiple program headers but it really needs to be done.
The alternative is to just up and remove #pragma poison from the source code and the safeguard with it.

A: I have had similar problems with malloc when building gcc, I fixed it by changing the malloc calls to 'xmalloc', I did a grep and there is a 'xcalloc' available.


text:
Q: XHR POST to Philips Hue Bridge I'm working on a bridge-like solution to communicate from an HbbTV-application with some Philips Hue lights (correctly with the gateway-hardware).
As the process is moving forward and the system was working, I'm now at the point that I use a plugin for Firefox that simulates a TV with HbbTV. To do so, I start an apache via XAMPP, on this i have my files which are loaded into Firefox.
Since I did that, I can't send any POST-requests to he Philips gateway, what is correct due same origin policy. I have no access to settings on Philips Hue and so my workarround has to be from clientside only.
My actual try looks like this:

  var stringState = "http://" + this.Ip + "/api/" + this.UserId + "/lights/" + this.LightId;
  var httpxml = new XMLHttpRequest();

  var valueRequest;

  console.log("in GetState:" + this.LightId);

  httpxml.onreadystatechange = function() {
   if (httpxml.readyState  == XMLHttpRequest.DONE) {

    valueRequest = JSON.parse(httpxml.responseText);

    console.log(valueRequest);
    console.log(valueRequest.state.on);

    that.switchState(valueRequest.state.on);
   }
  }

  httpxml.open('GET',stringState,true);

  httpxml.withCredentials = true;
  httpxml.setRequestHeader("Content-Type", "application/json");

  httpxml.send();

I'm pretty new to developing in JavaScript and Web. I hope someone could lead me on the right road, with some advice and maybe a clear example.
Best regards
Adrian

A: One of the P-s in XAMPP is for PHP. So a workaround you can do is hosting a PHP page right next to your HTML one (and there will not be any issues with CORS), and let it do the job.
Something like
<?php
  $ip=$_REQUEST['ip'];
  $user=$_REQUEST['user'];
  $light=$_REQUEST['light'];

  $ch=curl_init("http://".$ip."/api/".$user."/lights/".$light);
  curl_exec($ch);
  curl_close($ch);

This is far from anything safe and nice, but may help to get started. Some trivial clues: variables start with $, and . is the operator for string concatenation. $_REQUEST is an array which gets the url parameters, what you should supply in your modified request (where xy.php is the filename of the PHP page):
var stringState = "xy.php?ip=" + this.Ip + "&user=" + this.UserId + "&light=" + this.LightId;

curl is a utility for issuing web requests (you can find it in your XAMPP folders, xampp\apache\curl.exe), and it has bindings for PHP. https://curl.haxx.se/. By default it returns whatever your contoller provides, so the JSON should pass-through. Content-type may or may not be an issue, if it does not work, you can try putting a header("Content-Type: application/json"); right before the curl_exec line.


text:
Q: Why doesn't this Makefile compile correctly? I've got the following Makefile:
CC=g++
CFLAGS=-c -pedantic -std=c++11 -lglfw -lGL -lGLU -lX11 -lXxf86vm -lXrandr -lpthread -lXi

all: Set GLDrawableGraph Edge Graph Play main

Set: Set.cpp Set.h
        $(CC) $(CFLAGS) -o Set Set.cpp

GLDrawableGraph:  GLDrawableGraph.cpp GLDrawableGraph.h Edge.h Graph.h
         $(CC) $(CFLAGS) -o GLDrawableGraph GLDrawableGraph.cpp

Edge:  Edge.cpp Edge.h
         $(CC) $(CFLAGS) -o Edge Edge.cpp

Graph:  Graph.cpp GLDrawableGraph.h Edge.h Graph.h Play.h
         $(CC) $(CFLAGS) -o Graph Graph.cpp

Play:  Play.cpp GLDrawableGraph.h Edge.h Graph.h  Play.h
         $(CC) $(CFLAGS) -o Play Play.cpp

main:  main.cpp GLDrawableGraph.o Edge.o Graph.o Play.o GLDrawableGraph.h Edge.h Graph.h Play.h Set.o Set.h
         $(CC) $(CFLAGS) -o main main.cpp GLDrawableGraph.cpp Edge.cpp Graph.cpp Play.cpp Set.cpp

And I get the following output:
GLDrawableGraph.cpp:95:10: error: 'p' does not name a type
     auto p=nodes.find(nodenumber);
          ^
GLDrawableGraph.cpp:96:8: error: 'p' was not declared in this scope
     if(p==nodes.end()) throw std::string("Tried to color nonexistant vertex");
        ^
GLDrawableGraph.cpp:97:5: error: 'p' was not declared in this scope
     p->second.color=col;
     ^
GLDrawableGraph.cpp: In member function 'void DrawableGraph::DrawGraph(GLFWwindow*) const':
GLDrawableGraph.cpp:140:15: error: ISO C++ forbids declaration of 'e' with no type [-fpermissive]
     for(auto &e : edges) {
               ^
GLDrawableGraph.cpp:140:19: error: range-based 'for' loops are not allowed in C++98 mode
     for(auto &e : edges) {
                   ^
GLDrawableGraph.cpp:141:18: error: request for member 'first' in 'e', which is of non-class type 'int'
         int i1=e.first.first;
                  ^
GLDrawableGraph.cpp:142:18: error: request for member 'first' in 'e', which is of non-class type 'int'
         int i2=e.first.second;
                  ^
GLDrawableGraph.cpp:151:28: error: request for member 'second' in 'e', which is of non-class type 'int'
         RGB rgb=RGBColor(e.second.color);
                            ^
GLDrawableGraph.cpp:158:15: error: ISO C++ forbids declaration of 'p' with no type [-fpermissive]
     for(auto &p : nodes) {
               ^
GLDrawableGraph.cpp:158:19: error: range-based 'for' loops are not allowed in C++98 mode
     for(auto &p : nodes) {
                   ^
GLDrawableGraph.cpp:159:26: error: request for member 'second' in 'p', which is of non-class type 'int'
         float xx=float(p.second.x-R.l)/(R.r-R.l)*1.8-0.9;
                          ^
GLDrawableGraph.cpp:160:26: error: request for member 'second' in 'p', which is of non-class type 'int'
         float yy=float(p.second.y-R.b)/(R.t-R.b)*1.8-0.9;

I tought these errors were from the C++11 differences from the regular C++, but I've already given the -std=c++11 option and it still does not work.

A: Your makefile dependencies are not correct. What happens is that it compiles your project using the built-in rules, hence your flags don't apply and the compiler does not recognize C++11 auto keyword. Try compiling with make -r to disable the built-in rules and see what happens.
You probably want something like this:
CXX := g++
CPPLAGS := -Wall -Wextra
CXXFLAGS := -std=c++11
LDLIBS := -lglfw -lGL -lGLU -lX11 -lXxf86vm -lXrandr -lpthread -lXi

all : main

main : main.o GLDrawableGraph.o Edge.o Graph.o Play.o Set.o
    ${CXX} -o $@ $^ ${LDLIBS}

%.o : %.cpp # also auto-generates dependencies
    ${CXX} -c -o $@ ${CPPLAGS} ${CXXFLAGS} -MD -MP -MF ${@:.o=.d} $<

-include $(wildcard *.d) # include auto-generated dependencies