Alexei | #Computer Vision | DEPRECATED An Image Processing Interface for Android

 by   thiagokimo Java Updated: 12 months ago - 1.4 License: Apache-2.0

Download this library from

Build Applications

kandi X-RAY | Alexei REVIEW AND RATINGS

A type-safe interface of image processing algorithms.

kandi-support
Support

  • Alexei has a low active ecosystem.
  • It has 182 star(s) with 35 fork(s).
  • It had no major release in the last 12 months.
  • On average issues are closed in 110 days.
  • It has a neutral sentiment in the developer community.

quality kandi
Quality

  • Alexei has no issues reported.

security
Security

  • Alexei has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.

license
License

  • Alexei is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.

build
Reuse

  • Alexei releases are available to install and integrate.
  • Deployable package is available in Maven.
  • Build file is available. You can build the component from source.
Top functions reviewed by kandi - BETA

kandi has reviewed Alexei and discovered the below as its top functions. This is intended to give you an instant insight into Alexei implemented functionality, and help decide if they suit your requirements.

  • Blur bitmap .
  • Setup the drawer .
  • Invoked when a navigation drawer item is selected .
  • Calculates the most common color .
  • Performs a sheculus algorithm .
  • Perform the calculation
  • Get the real path from the content uri
  • Shows the user .
  • Fill the palette with the palette color .
  • Start a new instance with the given Context .

Alexei Key Features

DEPRECATED - An Image Processing Interface for Android

Alexei examples and code snippets

  • Setup
  • Usage
  • Example
  • Custom Calculus
  • Custom Executor
  • License
  • Javascript arrays email substring into full name, firstname and lastname
  • process name (comm) as key for BPF map
  • Nuget publishing error: Failed to process request. 'A client version '4.1.0'
  • version name set to Text widget -> Failed assertion: pos 10: 'data != null'
  • Iterating over dataset using GSON parser
  • Simple reverse navigation in datomic
  • Finning columns with 1 or 0 depending upon if the searched string exists
  • How can I write csv.DictReader JSON structure back to TSV file via csv.DictWriter?
  • Handling multithreading computation of big array
  • Drawing line(s) based on X and Y coordinates

Setup

dependencies {
    compile 'com.github.thiagokimo:alexei-library:1.4'
}

Usage

Alexei.with(context)
      .analyze(image)
      .perform(calculus)
      .showMe(answer);

Example

Alexei.with(context)
      .analyze(imageView)
      .perform(ImageProcessingThing.DOMINANT_COLOR)
      .showMe(new Answer<Color>(){
        @Override
        public void beforeExecution() {
          // anything you want to define before the calculation
        }

        @Override
        public void afterExecution(Color answer, long elapsedTime) {
            // your usual things after the calculation
        }

        @Override
        public void ifFails(Exception error) {
          // when shit happens, do your stuff here!
        }
      });

Custom Calculus


Alexei.with(context)
        .analyze(image)
        .perform(new Calculus<YourObject>() {
            @Override
            protected YourObject theCalculation(Bitmap image) {

                // do your bizarre stuff here!

                return new YourObject();
            }
        })
        .showMe(new Answer<YourObject>() {
            @Override
            public void beforeExecution() {}

            @Override
            public void afterExecution(YourObject answer, long elapsedTime) {}

            @Override
            public void ifFails(Exception error) {}
        });

Custom Executor


Alexei
    .with(context)
    .analyze(image)
    .perform(calculus)
    .withExecutor(YOUR_CUSTOM_EXECUTOR_HERE)
    .showMe(answer);

License

Copyright 2011, 2012 Thiago Rocha

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Javascript arrays email substring into full name, firstname and lastname

const Names = (emails) => {
  emails.forEach(i => {
    const indexDot = i.indexOf(".");
    const indexAt = i.lastIndexOf("@");
    console.log("firstname", i.substring(0, indexDot));
    console.log("fullname", i.substring(0, indexAt));
    console.log("lastname", i.substring(indexDot+1, indexAt));
  })
};
-----------------------
const emails = [ "peter.pittman@taitos.com", "ayden.reed@starkindustries.ss", "kiefer.franks@amazonia.hk", "oz.mcguire@tortelloni.zw", "ellisandro.noble@bluthhousing.party", "alyas.briggs@taitos.ninja", "windsor.raymond@hungryhungyhippopottumoses.co.uk", "daniyal.brock@hungryhungyhippopottumoses.ug", "samatar.benson@duffbeer.org", "jaime.freeman@gringottsbank.li", "aaron.pace@starkindustries.org", "guerin.mcgowan@taitos.li", "believe.cote@virtucon.hk", "abdalroof.ray@oscorp.co.uk", "blake.barrett@tortelloni.org", "bradlie.brooks@dundermifflin.ug", "rayyan.garza@tortelloni.ug", "declan.wood@dundermifflin.ug", "tymon.blackburn@oscorp.com", "joash.duffy@wonkaindustries.ug", "aleksander.ford@umbrellacorporation.fi", "jaida.colon@macrosloft.se", "jevan.jensen@lospolloshermanos.zw", "abubakar.palmer@dundermifflin.org", "cator.joyce@lospolloshermanos.org", "valen.henry@gringottsbank.co.uk", "taylor-jay.blackburn@wonkaindustries.ug", "leonardo.mcfadden@goldenstatuettes.co.uk", "noel.schneider@hungryhungyhippopottumoses.co.uk", "will.osborne@tasavallanpresidentti.com","arda.aguilar@oscorp.fi", "omri.walls@virtucon.ug", "lliam.briggs@tortelloni.se", "kris.lester@amazonia.fi", "skye.soto@wonkaindustries.se", "dermot.vang@goldenstatuettes.com", "cruiz.simmons@cookykitchens.co.uk"],
    users = emails.map(mail => {
      const [fullName] =  mail.split('@');
      const [firstName, lastName] = fullName.split('.');
      return { fullName: `${firstName}${lastName}`, firstName, lastName };
    });
console.log(users);
.as-console-wrapper { max-height: 100% !important; top: 0; }
-----------------------
const emails = [ "peter.pittman@taitos.com", "ayden.reed@starkindustries.ss", "kiefer.franks@amazonia.hk", "oz.mcguire@tortelloni.zw", "ellisandro.noble@bluthhousing.party", "alyas.briggs@taitos.ninja", "windsor.raymond@hungryhungyhippopottumoses.co.uk", "daniyal.brock@hungryhungyhippopottumoses.ug", "samatar.benson@duffbeer.org", "jaime.freeman@gringottsbank.li", "aaron.pace@starkindustries.org", "guerin.mcgowan@taitos.li", "believe.cote@virtucon.hk", "abdalroof.ray@oscorp.co.uk", "blake.barrett@tortelloni.org", "bradlie.brooks@dundermifflin.ug", "rayyan.garza@tortelloni.ug", "declan.wood@dundermifflin.ug", "tymon.blackburn@oscorp.com", "joash.duffy@wonkaindustries.ug", "aleksander.ford@umbrellacorporation.fi", "jaida.colon@macrosloft.se", "jevan.jensen@lospolloshermanos.zw", "abubakar.palmer@dundermifflin.org", "cator.joyce@lospolloshermanos.org", "valen.henry@gringottsbank.co.uk", "taylor-jay.blackburn@wonkaindustries.ug", "leonardo.mcfadden@goldenstatuettes.co.uk", "noel.schneider@hungryhungyhippopottumoses.co.uk", "will.osborne@tasavallanpresidentti.com","arda.aguilar@oscorp.fi", "omri.walls@virtucon.ug", "lliam.briggs@tortelloni.se", "kris.lester@amazonia.fi", "skye.soto@wonkaindustries.se", "dermot.vang@goldenstatuettes.com", "cruiz.simmons@cookykitchens.co.uk"],
    users = emails.map(mail => {
      const [fullName] =  mail.split('@');
      const [firstName, lastName] = fullName.split('.');
      return { fullName: `${firstName}${lastName}`, firstName, lastName };
    });
console.log(users);
.as-console-wrapper { max-height: 100% !important; top: 0; }
-----------------------
const emails=["peter.pittman@taitos.com","ayden.reed@starkindustries.ss","kiefer.franks@amazonia.hk","oz.mcguire@tortelloni.zw","ellisandro.noble@bluthhousing.party","alyas.briggs@taitos.ninja","windsor.raymond@hungryhungyhippopottumoses.co.uk","daniyal.brock@hungryhungyhippopottumoses.ug"]

let re = /^(?<first>\w+)\.(?<second>\w+)@/

let result = emails.map(e => {
    let {first,second} = e.match(re).groups
    return {fulll:first+second,first,second}
})

console.log(result)
-----------------------
const emails = [
  "peter.pittman@taitos.com",
  "ayden.reed@starkindustries.ss",
  "kiefer.franks@amazonia.hk",
  "oz.mcguire@tortelloni.zw",
  "ellisandro.noble@bluthhousing.party",
  "alyas.briggs@taitos.ninja",
  "windsor.raymond@hungryhungyhippopottumoses.co.uk",
  "daniyal.brock@hungryhungyhippopottumoses.ug",
  "samatar.benson@duffbeer.org",
  "jaime.freeman@gringottsbank.li",
  "aaron.pace@starkindustries.org",
  "guerin.mcgowan@taitos.li",
  "believe.cote@virtucon.hk",
  "abdalroof.ray@oscorp.co.uk",
  "blake.barrett@tortelloni.org",
  "bradlie.brooks@dundermifflin.ug",
  "rayyan.garza@tortelloni.ug",
  "declan.wood@dundermifflin.ug",
  "tymon.blackburn@oscorp.com",
  "joash.duffy@wonkaindustries.ug",
  "aleksander.ford@umbrellacorporation.fi",
  "jaida.colon@macrosloft.se",
  "jevan.jensen@lospolloshermanos.zw",
  "abubakar.palmer@dundermifflin.org",
  "cator.joyce@lospolloshermanos.org",
  "valen.henry@gringottsbank.co.uk",
  "taylor-jay.blackburn@wonkaindustries.ug",
  "leonardo.mcfadden@goldenstatuettes.co.uk",
  "noel.schneider@hungryhungyhippopottumoses.co.uk",
  "will.osborne@tasavallanpresidentti.com",
  "arda.aguilar@oscorp.fi",
  "omri.walls@virtucon.ug",
  "lliam.briggs@tortelloni.se",
  "kris.lester@amazonia.fi",
  "skye.soto@wonkaindustries.se",
  "dermot.vang@goldenstatuettes.com",
  "cruiz.simmons@cookykitchens.co.uk",
  "tymoteusz.riley@tortelloni.fi",
  "kaidyn.hays@aperaturescience.party",
  "apisai.fletcher@oscorp.co.uk",
  "kedrick.mcfadden@cookykitchens.com",
  "archibald.elliott@gringottsbank.hk",
  "kjae.hurley@umbrellacorporation.com",
  "tymon.nielsen@hungryhungyhippopottumoses.fi",
  "james.dejesus@amazonia.party",
  "reno.silva@gringottsbank.ug",
  "tayyib.brooks@taitos.ss",
  "cormack.alexander@duffbeer.ss",
  "obieluem.guerra@umbrellacorporation.party",
  "hector.moran@dundermifflin.co.uk",
  "logan.parrish@wonkaindustries.com",
  "robin.rivers@starkindustries.zw",
  "albie.spence@tasavallanpresidentti.hk",
  "qasim.schwartz@duffbeer.zw",
  "aodhan.cooper@tasavallanpresidentti.org",
  "eassan.hobbs@lospolloshermanos.org",
  "parkash.juarez@wonkaindustries.party",
  "teos.horton@haxhoont.se",
  "kuba.larsen@duffbeer.ninja",
  "eisa.beard@umbrellacorporation.li",
  "hamza.french@starkindustries.org",
  "sung.randall@taitos.ss",
  "samir.bond@virtucon.org",
  "conlyn.mckee@goldenstatuettes.com",
  "thiago.hooper@starkindustries.com",
  "demetrius.holland@macrosloft.zw",
  "uchenna.oneill@hungryhungyhippopottumoses.zw",
  "windsor.steele@hungryhungyhippopottumoses.fi",
  "keiryn.macias@tasavallanpresidentti.org",
  "kehinde.allen@cookykitchens.hk",
  "yuri.ramirez@macrosloft.zw",
  "ruan.perez@umbrellacorporation.org",
  "dyllon.young@dundermifflin.zw",
  "lockey.mcmahon@goldenstatuettes.fi",
  "lyndsay.haynes@goldenstatuettes.ninja",
  "dareh.grimes@macrosloft.co.uk",
  "veeran.vinson@cookykitchens.fi",
  "jayke.schroeder@lospolloshermanos.org",
  "aronas.berry@bluthhousing.li",
  "jonothan.donaldson@gringottsbank.zw",
  "kenzeigh.weber@umbrellacorporation.se",
  "cesare.huber@tasavallanpresidentti.com",
  "uzair.harris@virtucon.ninja",
  "kelan.yates@taitos.co.uk",
  "thomson.gonzales@bluthhousing.co.uk",
  "keaton.green@umbrellacorporation.hk",
  "jazeb.kinney@duffbeer.co.uk",
  "ronald.flores@starkindustries.hk",
  "alastair.moses@umbrellacorporation.se",
  "ogheneochuko.ratliff@aperaturescience.se",
  "kenton.conley@gringottsbank.ninja",
  "kashif.trujillo@bluthhousing.hk",
  "saghun.ayers@taitos.hk",
  "kamil.eaton@lospolloshermanos.org",
  "bailee.henson@goldenstatuettes.li",
  "alexei.stanton@haxhoont.li",
  "basher.clarke@taitos.li",
]



const Names = (emails) => {
  emails.map(i => {
    console.log("firstname:", i.substring(0, i.indexOf(".")),
                ", fullname:", i.substring(0, i.lastIndexOf("@")).replace(".", ""),
                ", lastname:", i.substring(i.indexOf(".")+1, i.lastIndexOf("@")));
  })
};

Names(emails)
-----------------------
^([^\s@.]+)\.([^\s@.]+)@[^\s@]+$
const emails = ["peter.pittman@taitos.com", "peter@taitos.com"]
let regex = /^([^\s@.]+)\.([^\s@.]+)@[^\s@]+$/

let result = emails.map(s => {
  let m = s.match(regex);
  if (m) {
    return {
      "fullname": m[1] + m[2],
      "firstname": m[1],
      "lastname": m[2]
    }
  }
  return s;
})

console.log(result)
-----------------------
^([^\s@.]+)\.([^\s@.]+)@[^\s@]+$
const emails = ["peter.pittman@taitos.com", "peter@taitos.com"]
let regex = /^([^\s@.]+)\.([^\s@.]+)@[^\s@]+$/

let result = emails.map(s => {
  let m = s.match(regex);
  if (m) {
    return {
      "fullname": m[1] + m[2],
      "firstname": m[1],
      "lastname": m[2]
    }
  }
  return s;
})

console.log(result)

process name (comm) as key for BPF map

class procName(Structure):
    _fields_ = [("name", (c_char_p*16))]
myFirst = procName(('p','y','t','h','o','n','\0'))
class procName(Structure):
    _fields_ = [("name", (c_char*16))]

s = "python"

mySecond = procName()
mySecond.name = s
from bcc import BPF
from bcc.utils import printb
from bcc.syscall import syscall_name, syscalls
import ctypes
from ctypes import *

b = BPF(text = """

#include <linux/string.h>

struct procName {
    char name[16];
};

BPF_HASH(attempt, struct procName, u32);

TRACEPOINT_PROBE(raw_syscalls, sys_exit)
{
    u32 *myVal;
    struct procName key;
    bpf_get_current_comm(&(key.name),16);

    myVal = attempt.lookup(&key);

    if (myVal)
    {
        bpf_trace_printk("values: %d\\n", *myVal);
    }

    return 0;

}
""")

class procName(Structure):
    _fields_ = [("name", (c_char*16))]

trialUpload = b["attempt"]

s = "python"

mySecond = procName()
mySecond.name = s
trialUpload[mySecond] = c_int(5)

while 1:
    try:
        (task, pid, cpu, flags, ts, msg) = b.trace_fields()
    except KeyboardInterrupt:
        print("Detaching")
        exit()
    print("%-18.9f %-16s %-6d %s" % (ts, task, pid, msg))
-----------------------
class procName(Structure):
    _fields_ = [("name", (c_char_p*16))]
myFirst = procName(('p','y','t','h','o','n','\0'))
class procName(Structure):
    _fields_ = [("name", (c_char*16))]

s = "python"

mySecond = procName()
mySecond.name = s
from bcc import BPF
from bcc.utils import printb
from bcc.syscall import syscall_name, syscalls
import ctypes
from ctypes import *

b = BPF(text = """

#include <linux/string.h>

struct procName {
    char name[16];
};

BPF_HASH(attempt, struct procName, u32);

TRACEPOINT_PROBE(raw_syscalls, sys_exit)
{
    u32 *myVal;
    struct procName key;
    bpf_get_current_comm(&(key.name),16);

    myVal = attempt.lookup(&key);

    if (myVal)
    {
        bpf_trace_printk("values: %d\\n", *myVal);
    }

    return 0;

}
""")

class procName(Structure):
    _fields_ = [("name", (c_char*16))]

trialUpload = b["attempt"]

s = "python"

mySecond = procName()
mySecond.name = s
trialUpload[mySecond] = c_int(5)

while 1:
    try:
        (task, pid, cpu, flags, ts, msg) = b.trace_fields()
    except KeyboardInterrupt:
        print("Detaching")
        exit()
    print("%-18.9f %-16s %-6d %s" % (ts, task, pid, msg))
-----------------------
class procName(Structure):
    _fields_ = [("name", (c_char_p*16))]
myFirst = procName(('p','y','t','h','o','n','\0'))
class procName(Structure):
    _fields_ = [("name", (c_char*16))]

s = "python"

mySecond = procName()
mySecond.name = s
from bcc import BPF
from bcc.utils import printb
from bcc.syscall import syscall_name, syscalls
import ctypes
from ctypes import *

b = BPF(text = """

#include <linux/string.h>

struct procName {
    char name[16];
};

BPF_HASH(attempt, struct procName, u32);

TRACEPOINT_PROBE(raw_syscalls, sys_exit)
{
    u32 *myVal;
    struct procName key;
    bpf_get_current_comm(&(key.name),16);

    myVal = attempt.lookup(&key);

    if (myVal)
    {
        bpf_trace_printk("values: %d\\n", *myVal);
    }

    return 0;

}
""")

class procName(Structure):
    _fields_ = [("name", (c_char*16))]

trialUpload = b["attempt"]

s = "python"

mySecond = procName()
mySecond.name = s
trialUpload[mySecond] = c_int(5)

while 1:
    try:
        (task, pid, cpu, flags, ts, msg) = b.trace_fields()
    except KeyboardInterrupt:
        print("Detaching")
        exit()
    print("%-18.9f %-16s %-6d %s" % (ts, task, pid, msg))
-----------------------
class procName(Structure):
    _fields_ = [("name", (c_char_p*16))]
myFirst = procName(('p','y','t','h','o','n','\0'))
class procName(Structure):
    _fields_ = [("name", (c_char*16))]

s = "python"

mySecond = procName()
mySecond.name = s
from bcc import BPF
from bcc.utils import printb
from bcc.syscall import syscall_name, syscalls
import ctypes
from ctypes import *

b = BPF(text = """

#include <linux/string.h>

struct procName {
    char name[16];
};

BPF_HASH(attempt, struct procName, u32);

TRACEPOINT_PROBE(raw_syscalls, sys_exit)
{
    u32 *myVal;
    struct procName key;
    bpf_get_current_comm(&(key.name),16);

    myVal = attempt.lookup(&key);

    if (myVal)
    {
        bpf_trace_printk("values: %d\\n", *myVal);
    }

    return 0;

}
""")

class procName(Structure):
    _fields_ = [("name", (c_char*16))]

trialUpload = b["attempt"]

s = "python"

mySecond = procName()
mySecond.name = s
trialUpload[mySecond] = c_int(5)

while 1:
    try:
        (task, pid, cpu, flags, ts, msg) = b.trace_fields()
    except KeyboardInterrupt:
        print("Detaching")
        exit()
    print("%-18.9f %-16s %-6d %s" % (ts, task, pid, msg))

Nuget publishing error: Failed to process request. 'A client version '4.1.0'

Install-Package NuGet.VisualStudio -Version 4.5.0
-----------------------
# This should get you the current version of PowershellGet
Install-Module -Name PowerShellGet -Force -Scope AllUsers

# But just in case...
Update-Module -Name PowerShellGet -Force
Import-Module PowershellGet -Force

# Make sure you have the expected version of the module
Get-Module PowershellGet

# Run your publish commands again 
<YOUR_PUBLISH_COMMAND>
-----------------------
# This should get you the current version of PowershellGet
Install-Module -Name PowerShellGet -Force -Scope AllUsers

# But just in case...
Update-Module -Name PowerShellGet -Force
Import-Module PowershellGet -Force

# Make sure you have the expected version of the module
Get-Module PowershellGet

# Run your publish commands again 
<YOUR_PUBLISH_COMMAND>

version name set to Text widget -> Failed assertion: pos 10: 'data != null'

_textVersion =
          "ver" + packageInfo.version + "(" + packageInfo.buildNumber + ")";
class SignInForm extends StatefulWidget {
  @override
  _SignInFormState createState() => _SignInFormState();
}

class _SignInFormState extends State<SignInForm> {
  String _textVersion = "";

  @override
  void initState() {
    PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
      setState(() {
        _textVersion =
            "ver" + packageInfo.version + "(" + packageInfo.buildNumber + ")";
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: new AppBar(
            centerTitle: true,
            title: new Text('Sign in',
                style: TextStyle(fontWeight: FontWeight.bold))),
        body: new Container(child: new Text(_textVersion)));
  }
}
 @override
  void initState() {
    getVersion();
    super.initState();
  }

  void getVersion() async{
    final packageInfo= await PackageInfo.fromPlatform();
      setState(() {
        _textVersion =
            "ver" + packageInfo.version + "(" + packageInfo.buildNumber + ")";
      });
  }
-----------------------
_textVersion =
          "ver" + packageInfo.version + "(" + packageInfo.buildNumber + ")";
class SignInForm extends StatefulWidget {
  @override
  _SignInFormState createState() => _SignInFormState();
}

class _SignInFormState extends State<SignInForm> {
  String _textVersion = "";

  @override
  void initState() {
    PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
      setState(() {
        _textVersion =
            "ver" + packageInfo.version + "(" + packageInfo.buildNumber + ")";
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: new AppBar(
            centerTitle: true,
            title: new Text('Sign in',
                style: TextStyle(fontWeight: FontWeight.bold))),
        body: new Container(child: new Text(_textVersion)));
  }
}
 @override
  void initState() {
    getVersion();
    super.initState();
  }

  void getVersion() async{
    final packageInfo= await PackageInfo.fromPlatform();
      setState(() {
        _textVersion =
            "ver" + packageInfo.version + "(" + packageInfo.buildNumber + ")";
      });
  }
-----------------------
_textVersion =
          "ver" + packageInfo.version + "(" + packageInfo.buildNumber + ")";
class SignInForm extends StatefulWidget {
  @override
  _SignInFormState createState() => _SignInFormState();
}

class _SignInFormState extends State<SignInForm> {
  String _textVersion = "";

  @override
  void initState() {
    PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
      setState(() {
        _textVersion =
            "ver" + packageInfo.version + "(" + packageInfo.buildNumber + ")";
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: new AppBar(
            centerTitle: true,
            title: new Text('Sign in',
                style: TextStyle(fontWeight: FontWeight.bold))),
        body: new Container(child: new Text(_textVersion)));
  }
}
 @override
  void initState() {
    getVersion();
    super.initState();
  }

  void getVersion() async{
    final packageInfo= await PackageInfo.fromPlatform();
      setState(() {
        _textVersion =
            "ver" + packageInfo.version + "(" + packageInfo.buildNumber + ")";
      });
  }

Iterating over dataset using GSON parser

for(Map.Entry<String,JsonElement> entry : obj.entrySet()) {
    String key = entry.getKey();     // BIBREF0
    JsonElement value = entry.getValue();   // details, can be cast to JsonObject
    processBibRef((JsonObject)value);       // For example
}

Simple reverse navigation in datomic

(ns club
  (:require [datahike.api :as d]))

(def schema
  [{:db/ident :person/name
    :db/valueType :db.type/string
    :db/cardinality :db.cardinality/one}
   {:db/ident :club/name
    :db/valueType :db.type/string
    :db/cardinality :db.cardinality/one}
   {:db/ident :club/members
    :db/valueType :db.type/ref
    :db/cardinality :db.cardinality/many}])

(def database "datahike:mem://example")

(def data
  [{:club/name "Carpentry" :club/members [{:person/name "liliana"} {:person/name "alexei"}]}
   {:club/name "Taxidermy" :club/members [{:person/name "karenna"} {:person/name "alexei"}]}])

(comment
  (d/create-database database)

  (def conn (d/connect database))

  (d/transact conn schema)

  (d/transact conn data)

  (d/q '[:find (pull ?e [{:club/_members [:club/name]}])
         :where [?e :person/name "alexei"]]
       @conn))
([#:club{:_members [#:club{:name "Carpentry"}]}] [#:club{:_members [#:club{:name "Taxidermy"}]}])
-----------------------
(ns club
  (:require [datahike.api :as d]))

(def schema
  [{:db/ident :person/name
    :db/valueType :db.type/string
    :db/cardinality :db.cardinality/one}
   {:db/ident :club/name
    :db/valueType :db.type/string
    :db/cardinality :db.cardinality/one}
   {:db/ident :club/members
    :db/valueType :db.type/ref
    :db/cardinality :db.cardinality/many}])

(def database "datahike:mem://example")

(def data
  [{:club/name "Carpentry" :club/members [{:person/name "liliana"} {:person/name "alexei"}]}
   {:club/name "Taxidermy" :club/members [{:person/name "karenna"} {:person/name "alexei"}]}])

(comment
  (d/create-database database)

  (def conn (d/connect database))

  (d/transact conn schema)

  (d/transact conn data)

  (d/q '[:find (pull ?e [{:club/_members [:club/name]}])
         :where [?e :person/name "alexei"]]
       @conn))
([#:club{:_members [#:club{:name "Carpentry"}]}] [#:club{:_members [#:club{:name "Taxidermy"}]}])

Finning columns with 1 or 0 depending upon if the searched string exists

xl['values']=np.where(xl['values'].str.contains('ALEXEI',na=False),1,0)

How can I write csv.DictReader JSON structure back to TSV file via csv.DictWriter?

from ast import literal_eval
import csv
import json
import io
from pprint import pprint

# This is the JSON structure that's passed to the python script
infile = '"[{\\"Manuscript preparation\\": \\"Y\\", \\"First_Name\\": \\"Anna\\", \\"Last_Name\\": \\"Karenina\\", \\"Tel\\": \\"8885006000\\", \\"Data generation\\": \\"Y\\", \\"Places\\": \\"BioInform_Harvard\\", \\"Fax\\": \\"8885006001\\", \\"Experimental design\\": \\"Y\\", \\"Joint\\": \\"1\\", \\"Data analysis\\": \\"Y\\", \\"Statistical analysis\\": \\"Y\\", \\"Data processing\\": \\"Y\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"anna.Karenina@ucsf.edu\\", \\"Initials\\": \\"A\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"Konstantin\\", \\"Last_Name\\": \\"Levin\\", \\"Tel\\": \\"8887006000\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"Neuro_Harvard\\", \\"Fax\\": \\"8887006001\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"1\\", \\"Data analysis\\": \\"Y\\", \\"Statistical analysis\\": \\"Y\\", \\"Data processing\\": \\"Y\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"Konstantin.levin@childrens.harvard.edu\\", \\"Initials\\": \\"D\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"Alexei\\", \\"Last_Name\\": \\"Vronsky\\", \\"Tel\\": \\"8889006000\\", \\"Data generation\\": \\"Y\\", \\"Places\\": \\"IGM_Columbia\\", \\"Fax\\": \\"8889006001\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"2\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"alexei.vronsky@cumc.columbia.edu\\", \\"Initials\\": \\"K\\"}, {\\"Manuscript preparation\\": \\"Y\\", \\"First_Name\\": \\"Stepan\\", \\"Last_Name\\": \\"Oblonsky\\", \\"Tel\\": \\"8891006000\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"NIMH\\", \\"Fax\\": \\"8891006001\\", \\"Experimental design\\": \\"Y\\", \\"Joint\\": \\"2\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"steoblon@mail.nih.gov\\", \\"Initials\\": \\"A\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"Ekaterina\\", \\"Last_Name\\": \\"Shcherbatskaya\\", \\"Tel\\": \\"8893006000\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"CHU_Montreal\\", \\"Fax\\": \\"8893006001\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"Y\\", \\"Statistical analysis\\": \\"Y\\", \\"Data processing\\": \\"Y\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"Ekaterina.Shcherbatskaya@umontreal.ca\\", \\"Initials\\": \\"A\\"}, {\\"Manuscript preparation\\": \\"Y\\", \\"First_Name\\": \\"Alexei\\", \\"Last_Name\\": \\"Karenin\\", \\"Tel\\": \\"8895006000\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"BioInform_Harvard, Neuro_Harvard\\", \\"Fax\\": \\"8895006001\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"Y\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"Karenin05@hms.harvard.edu\\", \\"Initials\\": \\"A\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"Fyodor\\", \\"Last_Name\\": \\"Dostoevsky\\", \\"Tel\\": \\"8897006000\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"Penn_Psych\\", \\"Fax\\": \\"8897006001\\", \\"Experimental design\\": \\"Y\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"Y\\", \\"Email\\": \\"Fyodor_Dostoevsky@pennmedicine.upenn.edu\\", \\"Initials\\": \\"M\\"}, {\\"Manuscript preparation\\": \\"Y\\", \\"First_Name\\": \\"Lev\\", \\"Last_Name\\": \\"Tolstoy\\", \\"Tel\\": \\"8899006000\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"UCSF_Weill\\", \\"Fax\\": \\"8899006001\\", \\"Experimental design\\": \\"Y\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"Y\\", \\"Statistical analysis\\": \\"Y\\", \\"Data processing\\": \\"Y\\", \\"Corresponding\\": \\"Y\\", \\"Email\\": \\"ltolstoy@mednet.ucla.edu\\", \\"Initials\\": \\"N\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"Place\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"Address\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"BioInform_Harvard\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"Department of Biomedical Informatics, Harvard Medical School, Boston, MA, USA\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"CHU_Montreal\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"CHU Sainte-Justine Research Centre, University of Montreal, 3175 Chemin de la Co_te-Sainte-Catherine, Montreal, Quebec H3T 1C5, Canada.\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"IGM_Columbia\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"Institute for Genomic Medicine, Columbia University Medical Center, Hammer Health Sciences, 1408, 701 West 168th St., New York, NY 10032, USA.\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"Neuro_Harvard\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"Department of Neurology, Boston Children\'s Hospital and Harvard Medical School, Boston, MA, USA\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"NIMH\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"National Institute of Mental Health, 10 Center Dr, Bethesda, MD 20814\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"Penn_Psych\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"Department of Psychiatry, Neuropsychiatry Section, Perelman School of Medicine at the University of Pennsylvania, 3400 Spruce, Philadelphia, PA 19104\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"UCSF_Weill\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"Department of Psychiatry, UCSF Weill Institute for Neurosciences, University of California, San Francisco, San Francisco, CA 94158\\"}]"'

# Convert json string that's passed to script into literal list of dicts
contents = json.loads(literal_eval(infile))
fieldnames = contents[0].keys()  # Get TSV fieldnames from first dictionary.

# Put list of dicts back into TSV "file" in memory
memory_file = io.StringIO()
writer = csv.DictWriter(memory_file, fieldnames=fieldnames, delimiter='\t')
writer.writerows(contents)

as_string = memory_file.getvalue()
print('\n'.join(as_string.splitlines()))

Handling multithreading computation of big array

#threads = #cpu-cores - 1
val nOfThreads = Runtime.getRuntime().availableProcessors() - 1;
val ctx = ForkJoinPool( if (nOfThreads == 0) then 1 else nOfThreads).asCoroutineDispatcher()
-----------------------
#threads = #cpu-cores - 1
val nOfThreads = Runtime.getRuntime().availableProcessors() - 1;
val ctx = ForkJoinPool( if (nOfThreads == 0) then 1 else nOfThreads).asCoroutineDispatcher()

Drawing line(s) based on X and Y coordinates

double startX = -1;
double startY = -1;

while( true ) {

    // ...Your code...

    if( startX > -1 || startY > -1 ) {
       Stage.setTitle("Constellation Simulator");  // Should be outside the while loop
       gc.setFill(Color.YELLOW);  // Should be outside the while loop
       gc.fillRect(x,y,10,10);
       gc.setStroke(Color.RED);  // Should be outside the while loop
       gc.strokeLine(startX,startY,x,y);
    }
}

// Save the current position
startX = x;
startY = y;

COMMUNITY DISCUSSIONS

Top Trending Discussions on Alexei
  • Javascript arrays email substring into full name, firstname and lastname
  • what happens if we pass threads in executorService execute call in Java multithreading
  • process name (comm) as key for BPF map
  • Nuget publishing error: Failed to process request. 'A client version '4.1.0'
  • version name set to Text widget -> Failed assertion: pos 10: 'data != null'
  • Iterating over dataset using GSON parser
  • Simple reverse navigation in datomic
  • Finning columns with 1 or 0 depending upon if the searched string exists
  • How can I write csv.DictReader JSON structure back to TSV file via csv.DictWriter?
  • Is there something better than preprocessor directives (#if, etc) in C#?
Top Trending Discussions on Alexei

QUESTION

Javascript arrays email substring into full name, firstname and lastname

Asked 2021-Feb-19 at 13:24
      I know my questions are similar to other questions but I could not figure it. 

I am practicing javascript. I have arrays of emails. from that email I want to get three out puts of strings fullname, firstname and lastname inside one map function. I can able to get output first name by reading one stack-overflow questions. I am able get full name by I get output john.doe, I want johndoe. Could not figure it out last name doe.

My example email address is like this: john.doe@co.uk

My expected output is

firstname: 'john'

fullname: johndoe

lastname: doe

This is my code

const Names = (emails) => {
  emails.map(i => {
    console.log("firstname", i.substring(0, i.indexOf(".")));
    console.log("fullname", i.substring(0, i.lastIndexOf("@")));
    console.log("lastname");
  })
};

Names(emails)

const emails = [
  "peter.pittman@taitos.com",
  "ayden.reed@starkindustries.ss",
  "kiefer.franks@amazonia.hk",
  "oz.mcguire@tortelloni.zw",
  "ellisandro.noble@bluthhousing.party",
  "alyas.briggs@taitos.ninja",
  "windsor.raymond@hungryhungyhippopottumoses.co.uk",
  "daniyal.brock@hungryhungyhippopottumoses.ug",
  "samatar.benson@duffbeer.org",
  "jaime.freeman@gringottsbank.li",
  "aaron.pace@starkindustries.org",
  "guerin.mcgowan@taitos.li",
  "believe.cote@virtucon.hk",
  "abdalroof.ray@oscorp.co.uk",
  "blake.barrett@tortelloni.org",
  "bradlie.brooks@dundermifflin.ug",
  "rayyan.garza@tortelloni.ug",
  "declan.wood@dundermifflin.ug",
  "tymon.blackburn@oscorp.com",
  "joash.duffy@wonkaindustries.ug",
  "aleksander.ford@umbrellacorporation.fi",
  "jaida.colon@macrosloft.se",
  "jevan.jensen@lospolloshermanos.zw",
  "abubakar.palmer@dundermifflin.org",
  "cator.joyce@lospolloshermanos.org",
  "valen.henry@gringottsbank.co.uk",
  "taylor-jay.blackburn@wonkaindustries.ug",
  "leonardo.mcfadden@goldenstatuettes.co.uk",
  "noel.schneider@hungryhungyhippopottumoses.co.uk",
  "will.osborne@tasavallanpresidentti.com",
  "arda.aguilar@oscorp.fi",
  "omri.walls@virtucon.ug",
  "lliam.briggs@tortelloni.se",
  "kris.lester@amazonia.fi",
  "skye.soto@wonkaindustries.se",
  "dermot.vang@goldenstatuettes.com",
  "cruiz.simmons@cookykitchens.co.uk",
  "tymoteusz.riley@tortelloni.fi",
  "kaidyn.hays@aperaturescience.party",
  "apisai.fletcher@oscorp.co.uk",
  "kedrick.mcfadden@cookykitchens.com",
  "archibald.elliott@gringottsbank.hk",
  "kjae.hurley@umbrellacorporation.com",
  "tymon.nielsen@hungryhungyhippopottumoses.fi",
  "james.dejesus@amazonia.party",
  "reno.silva@gringottsbank.ug",
  "tayyib.brooks@taitos.ss",
  "cormack.alexander@duffbeer.ss",
  "obieluem.guerra@umbrellacorporation.party",
  "hector.moran@dundermifflin.co.uk",
  "logan.parrish@wonkaindustries.com",
  "robin.rivers@starkindustries.zw",
  "albie.spence@tasavallanpresidentti.hk",
  "qasim.schwartz@duffbeer.zw",
  "aodhan.cooper@tasavallanpresidentti.org",
  "eassan.hobbs@lospolloshermanos.org",
  "parkash.juarez@wonkaindustries.party",
  "teos.horton@haxhoont.se",
  "kuba.larsen@duffbeer.ninja",
  "eisa.beard@umbrellacorporation.li",
  "hamza.french@starkindustries.org",
  "sung.randall@taitos.ss",
  "samir.bond@virtucon.org",
  "conlyn.mckee@goldenstatuettes.com",
  "thiago.hooper@starkindustries.com",
  "demetrius.holland@macrosloft.zw",
  "uchenna.oneill@hungryhungyhippopottumoses.zw",
  "windsor.steele@hungryhungyhippopottumoses.fi",
  "keiryn.macias@tasavallanpresidentti.org",
  "kehinde.allen@cookykitchens.hk",
  "yuri.ramirez@macrosloft.zw",
  "ruan.perez@umbrellacorporation.org",
  "dyllon.young@dundermifflin.zw",
  "lockey.mcmahon@goldenstatuettes.fi",
  "lyndsay.haynes@goldenstatuettes.ninja",
  "dareh.grimes@macrosloft.co.uk",
  "veeran.vinson@cookykitchens.fi",
  "jayke.schroeder@lospolloshermanos.org",
  "aronas.berry@bluthhousing.li",
  "jonothan.donaldson@gringottsbank.zw",
  "kenzeigh.weber@umbrellacorporation.se",
  "cesare.huber@tasavallanpresidentti.com",
  "uzair.harris@virtucon.ninja",
  "kelan.yates@taitos.co.uk",
  "thomson.gonzales@bluthhousing.co.uk",
  "keaton.green@umbrellacorporation.hk",
  "jazeb.kinney@duffbeer.co.uk",
  "ronald.flores@starkindustries.hk",
  "alastair.moses@umbrellacorporation.se",
  "ogheneochuko.ratliff@aperaturescience.se",
  "kenton.conley@gringottsbank.ninja",
  "kashif.trujillo@bluthhousing.hk",
  "saghun.ayers@taitos.hk",
  "kamil.eaton@lospolloshermanos.org",
  "bailee.henson@goldenstatuettes.li",
  "alexei.stanton@haxhoont.li",
  "basher.clarke@taitos.li",
]



const Names = (emails) => {
  emails.map(i => {
    console.log("firstname", i.substring(0, i.indexOf(".")));
    console.log("fullname", i.substring(0, i.lastIndexOf("@")));
    console.log("lastname");
  })
};

Names(emails)

ANSWER

Answered 2021-Feb-19 at 05:44

For fullname, you cane use replace(".", "") to remove the '.' So for fullname it can be: i.substring(0, i.lastIndexOf("@")).replace(".", "")

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Source https://stackoverflow.com/questions/66272298

QUESTION

what happens if we pass threads in executorService execute call in Java multithreading

Asked 2020-Oct-08 at 11:47

See these two examples:

EXAMPLE 1

public static void main(String[] args) throws InterruptedException {

ExecutorService executorService = Executors.newCachedThreadPool();
        
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                //work
                for (int i = 0 ; i < 5 ; i++){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        executorService.execute(thread1);
        executeService.shutdown();
}

EXAMPLE 2

public static void main(String[] args) throws InterruptedException {

        ExecutorService executorService = Executors.newCachedThreadPool();

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                //work
                for (int i = 0 ; i < 5 ; i++){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        executeService.shutdown();
    }

Results are the same in both cases but a friend of mine from StackOverflow alexei-kaigorodov (in this question) said in a comment that

"executorService is an alternative to treads. There is no sense to put threads in executorService. First, create Runnable, and then either put it as a parameter to a thread and start that thread or submit that runnable to an executorService."

I hope I am clear with my question, so please tell me the difference in passing runnable to ExecuteService vs. passing thread to ExecutableService.

ANSWER

Answered 2020-Oct-08 at 11:47

Thread implements Runnable so the excutor service will accept it as a simple Runnable, and thus calls the Thread.run() method.

Which means that the Thread itself will never be started, unless you call its start() method yourself, in which case the result is definetely undefined.

So you could say the snippets behave the same, you're only passing a Runnable to the ExecutorService and that then executes it by calling the Runnable.run() method.

Source https://stackoverflow.com/questions/64261592

QUESTION

process name (comm) as key for BPF map

Asked 2020-Apr-25 at 20:39

I've been trying to design a tool wherein I can do per-process tracing, but this implies that I need a key for each process so that I can store key-value map pairings for each process. I instinctually don't like using structs or strings as keys, and for a while I was considering how to access inode values for their use as keys. However there are numerous examples that use structures or strings as hashmap keys, and Alexei suggested that process names will be commonly used as a key. That said, I am unable to get a basic implementation of such a hashmap to work. Within the BPF program, the tracepoint isn't able to find the associated value with the process_name key. Perhaps I'm comparing memory locations and not the string literals as intended? Is there something going on under the hood with c_types that creates a mismatch between the keys?

from bcc import BPF
from bcc.utils import printb
from bcc.syscall import syscall_name, syscalls
from ctypes import *

b = BPF(text = """

struct procName {
    char name[16];
};

BPF_HASH(attempt, struct procName, u32);

TRACEPOINT_PROBE(raw_syscalls, sys_exit)
{
    u32 *val;
    struct procName hKey;
    bpf_get_current_comm(hKey.name,16);
    val = attempt.lookup(&hKey);

    if (val)
    {
        bpf_trace_printk("Hello world, I have value %d!\\n", *val);
    }

    return 0;
}
""")

class procName(Structure):
    _fields_ = [("name", (c_char_p*16))]

myFirst = procName(('p','y','t','h','o','n','\0'))
trialUpload[myFirst] = c_int(10)

while 1:
    try:
        (task, pid, cpu, flags, ts, msg) = b.trace_fields()
    except KeyboardInterrupt:
        print("Detaching")
        exit()
    print("%-18.9f %-16s %-6d %s" % (ts, task, pid, msg))

ANSWER

Answered 2020-Apr-25 at 20:39

The error in the original code has nothing to do with BCC & BPF and lies within my implemention of ctypes. For starters --

class procName(Structure):
    _fields_ = [("name", (c_char_p*16))]

creates a structure with the field "name". In the above definition, name will be of type *char[16] when I want a char[16]. Second, while this

myFirst = procName(('p','y','t','h','o','n','\0'))

might work, its not the best practice initialization. This is the correct approach --

class procName(Structure):
    _fields_ = [("name", (c_char*16))]

s = "python"

mySecond = procName()
mySecond.name = s

Thus, the full program incorporating a process_name based key and implementation of such to pass data from python is then..

from bcc import BPF
from bcc.utils import printb
from bcc.syscall import syscall_name, syscalls
import ctypes
from ctypes import *

b = BPF(text = """

#include <linux/string.h>

struct procName {
    char name[16];
};

BPF_HASH(attempt, struct procName, u32);

TRACEPOINT_PROBE(raw_syscalls, sys_exit)
{
    u32 *myVal;
    struct procName key;
    bpf_get_current_comm(&(key.name),16);

    myVal = attempt.lookup(&key);

    if (myVal)
    {
        bpf_trace_printk("values: %d\\n", *myVal);
    }

    return 0;

}
""")

class procName(Structure):
    _fields_ = [("name", (c_char*16))]

trialUpload = b["attempt"]

s = "python"

mySecond = procName()
mySecond.name = s
trialUpload[mySecond] = c_int(5)

while 1:
    try:
        (task, pid, cpu, flags, ts, msg) = b.trace_fields()
    except KeyboardInterrupt:
        print("Detaching")
        exit()
    print("%-18.9f %-16s %-6d %s" % (ts, task, pid, msg))

Source https://stackoverflow.com/questions/61415843

QUESTION

Nuget publishing error: Failed to process request. 'A client version '4.1.0'

Asked 2020-Apr-16 at 11:59

I m publishing NuGet package. I ve installed latest version of Visual Studio 2017 Community. I get the following error:

Failed to process request. 'A client version '4.1.0' or higher is required to be able to push packages. Please contact support@nuget.org to get more details.'.

Why latest Visual Studio cannot publish NuGet? How to fix it? The full build log is below:

1>------ Rebuild All started: Project: MyProject.NuGet, Configuration: Release Any CPU ------
1>  MyProject.NuGet -> C:\Users\User\Documents\MyProject\MyProject.NuGet\bin\Release\MyProject.NuGet.dll
1>   
1>  NuGet Packager 2.0.3
1>   
1>  Creating backup...
1>  Renamed MyProject.1.0.6.nupkg to MyProject.1.0.6.nupkg.bak
1>   
1>  Updating NuGet...
1>  The element 'metadata' in namespace 'http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd' has invalid child element 'developmentDependency' in namespace 'http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd'. List of possible elements expected: 'releaseNotes, projectUrl, title, language, iconUrl, dependencies, frameworkAssemblies, tags, references, licenseUrl, summary, copyright, description' in namespace 'http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd'.
1>  Checking for updates from https://nuget.org/api/v2/.
1>  Currently running NuGet.exe 2.2.0.
1>  Updating NuGet.exe to 4.4.1.
1>   
1>  Creating package...
1>  Attempting to build package from 'Package.nuspec'.
1>  Id: MyProject
1>  Version: 1.0.6
1>  Authors: Boris Zinchenko
1>  Description: MyProject
1>  License Url: MyProject
1>  Project Url: MyProject
1>  Tags: MyProject
1>  Dependencies: 
1>  Added file 'lib\net20\MyProject.dll'.
1>  Added file 'tools\init.ps1'.
1>  Added file 'tools\install.ps1'.
1>  Added file 'tools\uninstall.ps1'.
1>  Successfully created package 'MyProject.1.0.6.nupkg'.
1>   
1>  Publishing package...
1>  Repository Url: https://www.nuget.org
1>   
1>  Pushing MyProject 1.0.6 to the NuGet gallery (https://www.nuget.org)...
1>  Failed to process request. 'A client version '4.1.0' or higher is required to be able to push packages. Please contact support@nuget.org to get more details.'. 
1>EXEC : The remote server returned an warning : (400) Bad Request..
1>  Pushing MyProject 1.0.6 to the NuGet gallery (https://www.nuget.org)...
1>  Failed to process request. 'A client version '4.1.0' or higher is required to be able to push packages. Please contact support@nuget.org to get more details.'. 
1>EXEC : The remote server returned an warning : (400) Bad Request..
1>   
1>  Exit Code: 0
1>   
1>  Build Exit Code: -1
========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ==========

Update

After valuable advise by @Alexei Levenkov, I ve updated NuGet version using command: Install-Package NuGet.VisualStudio. Surprisingly, it did not make any effect on my error and the error still remains the same. The log of update from NuGet console is below.

Package Manager Console Host Version 4.5.0.4685
Type 'get-help NuGet' to see all available NuGet commands.

PM> Install-Package NuGet.VisualStudio

Attempting to gather dependency information for package 'NuGet.VisualStudio.4.5.0' with respect to project 'MyProject', targeting '.NETFramework,Version=v2.0'
Gathering dependency information took 20.7 ms
Attempting to resolve dependencies for package 'NuGet.VisualStudio.4.5.0' with DependencyBehavior 'Lowest'
Resolving dependency information took 0 ms
Resolving actions to install package 'NuGet.VisualStudio.4.5.0'
Resolved actions to install package 'NuGet.VisualStudio.4.5.0'
Retrieving package 'NuGet.VisualStudio 4.5.0' from 'nuget.org'.
  GET https://api.nuget.org/v3-flatcontainer/nuget.visualstudio/4.5.0/nuget.visualstudio.4.5.0.nupkg
  OK https://api.nuget.org/v3-flatcontainer/nuget.visualstudio/4.5.0/nuget.visualstudio.4.5.0.nupkg 524ms
Installing NuGet.VisualStudio 4.5.0.
Adding package 'NuGet.VisualStudio.4.5.0' to folder 'C:\Users\User\Documents\MyProject\packages'
Added package 'NuGet.VisualStudio.4.5.0' to folder 'C:\Users\User\Documents\MyProject\packages'
Added package 'NuGet.VisualStudio.4.5.0' to 'packages.config'
Successfully installed 'NuGet.VisualStudio 4.5.0' to MyProject
Executing nuget actions took 5.01 sec
Time Elapsed: 00:00:07.1699206

ANSWER

Answered 2018-Jan-28 at 06:35

Looks like you did not get updated version of NuGet. I assume one that comes with VS is less than 4.1 and it sounds like www.nuget.org now requires higher version.

To update NuGet:

Source https://stackoverflow.com/questions/48483733

QUESTION

version name set to Text widget -> Failed assertion: pos 10: 'data != null'

Asked 2020-Mar-23 at 16:35

android studio 3.6

I want to set version name to Text widget.

here my snippet:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:package_info/package_info.dart';
import 'constants.dart' as Constants;

class SignInForm extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new _SignInFormState();
  }
}

class _SignInFormState extends State {
  final _formKey = GlobalKey<FormState>();
  String _textVersion;

  @override
  Widget build(BuildContext context) {
    PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
      _textVersion =
          "ver" + packageInfo.version + "(" + packageInfo.buildNumber + ")";
    });

    return Scaffold(
        appBar: new AppBar(
            centerTitle: true,
            title: new Text('Sign in',
                style: TextStyle(fontWeight: FontWeight.bold))),
        body: new Container(
            child: new Text(_textVersion)));
  }
}

in logcat I get error:

I/flutter: ════════════════════════════════════════════════════════════════════════════════════════════════════
I/flutter: ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter: The following assertion was thrown building SignInForm(dirty, state: _SignInFormState#61fee):
I/flutter: A non-null String must be provided to a Text widget.
I/flutter: 'package:flutter/src/widgets/text.dart':
I/flutter: Failed assertion: line 302 pos 10: 'data != null'
I/flutter: The relevant error-causing widget was:
I/flutter:   SignInForm file:///home/alexei/dev/Tango-flutter/ios-flutter/lib/main.dart:19:19
I/flutter: When the exception was thrown, this was the stack:
I/flutter: #2      new Text (package:flutter/src/widgets/text.dart:302:10)
I/flutter: #3      _SignInFormState.build (package:flutter_sample/signinform.dart:33:24)
I/flutter: #4      StatefulElement.build (package:flutter/src/widgets/framework.dart:4619:28)
I/flutter: #5      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4502:15)
I/flutter: #6      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4675:11)
I/flutter: #7      Element.rebuild (package:flutter/src/widgets/framework.dart:4218:5)
I/flutter: #8      ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4481:5)
I/flutter: #9      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4666:11)
I/flutter: #10     ComponentElement.mount (package:flutter/src/widgets/framework.dart:4476:5)
I/flutter: ...     Normal element mounting (115 frames)
I/flutter: #125    Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
I/flutter: #126    MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5947:32)
I/flutter: ...     Normal element mounting (238 frames)
I/flutter: #364    Element.inflateWidget (package:flutter/src/widgets/framework.dart:3446:14)
I/flutter: #365    Element.updateChild (package:flutter/src/widgets/framework.dart:3214:18)
I/flutter: #366    RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:1142:16)
I/flutter: #367    RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:1113:5)
I/flutter: #368    RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> (package:flutter/src/widgets/binding.dart:1055:17)
I/flutter: #369    BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2607:19)
I/flutter: #370    RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:1054:13)
I/flutter: #371    WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:935:7)
I/flutter: #372    WidgetsBinding.scheduleAttachRootWidget.<anonymous closure> (package:flutter/src/widgets/binding.dart:917:7)
I/flutter: (elided 13 frames from class _AssertionError, class _RawReceivePortImpl, class _Timer, dart:async, and dart:async-patch)
I/flutter: ════════════════════════════════════════════════════════════════════════════════════════════════════

ANSWER

Answered 2020-Mar-23 at 14:42

First of all, you should not do anything costly in your build method. Second, _textVersion is null at first when you try to initialize it into the Text because the below line of code will run sometime after the Text is initialized in build.

_textVersion =
          "ver" + packageInfo.version + "(" + packageInfo.buildNumber + ")";

Move your code to the initiState method.

class SignInForm extends StatefulWidget {
  @override
  _SignInFormState createState() => _SignInFormState();
}

class _SignInFormState extends State<SignInForm> {
  String _textVersion = "";

  @override
  void initState() {
    PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
      setState(() {
        _textVersion =
            "ver" + packageInfo.version + "(" + packageInfo.buildNumber + ")";
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: new AppBar(
            centerTitle: true,
            title: new Text('Sign in',
                style: TextStyle(fontWeight: FontWeight.bold))),
        body: new Container(child: new Text(_textVersion)));
  }
}

Or you can also create and call another async function from initState, since initState cannot be marked async.

 @override
  void initState() {
    getVersion();
    super.initState();
  }

  void getVersion() async{
    final packageInfo= await PackageInfo.fromPlatform();
      setState(() {
        _textVersion =
            "ver" + packageInfo.version + "(" + packageInfo.buildNumber + ")";
      });
  }

Source https://stackoverflow.com/questions/60815048

QUESTION

Iterating over dataset using GSON parser

Asked 2020-Mar-23 at 10:38

I am writing a GSON (Java) parser for the CORD19 dataset https://pages.semanticscholar.org/coronavirus-research of about 40K scientific papers which have been made open for everyone. I want to iterate over the JSON tree using GSON and convert them to HTML. In particular I want to iterate over the entries of the JsonObject elements.

Q1: If anyone has already written an F/OSS CORD19 parser in GSON or other Java parser I'd be delighted.

My specific problem is to iterate over the fields (entries) of a JsonObject.

Data (heavily snipped, but hopefully parsable if snips removed):

{
    "paper_id": "b801b7f92cff2155d98f0e3404229c67b60e2f9f",
    "metadata": {
        "title": "Realtime 2-5A kinetics suggests interferons \u03b2 and \uf06c evade global arrest of translation by RNase L",
        "authors": [
            {
                "first": "Alisha",
                "middle": [],
                "last": "Chitrakar",
                "suffix": "",
                "affiliation": {},
                "email": ""
            },
            ... SNIPPED
            {
                "first": "Alexei",
                "middle": [],
                "last": "Korennykh",
                "suffix": "",
                "affiliation": {},
                "email": "akorenny@princeton.edu"
            }
        ]
    },
    "abstract": [
        {
            "text": "Cells of all mammals recognize double-stranded RNA (dsRNA) as a foreign material. ...",
            "cite_spans": [],
            "ref_spans": [],
            "section": "Abstract"
        },
... SNIPPED
        {
            "text": "The 2-5A system is also a surveillance pathway for ...",
            "cite_spans": [],
            "ref_spans": [],
            "section": "Abstract"
        }
    ],
    "body_text": [
        {
            "text": "Interferons IFNs of type I (\uf061 and \u03b2) and type III ...",
            "cite_spans": [],
            "ref_spans": [],
            "section": "Introduction"
        },
        {
            "text": "To evaluate how the nuclear envelope ...",
            "cite_spans": [
                {
                    "start": 382,
                    "end": 384,
                    "text": "50",
                    "ref_id": null
                }
            ],
            "ref_spans": [],
            "section": "Diffusion calculations"
        }
    ],
    "bib_entries": {
        "BIBREF0": {
            "ref_id": "b0",
            "title": "Higher-order substrate recognition of eIF2alpha by the RNA-dependent protein kinase PKR",
            "authors": [
                {
                    "first": "A",
                    "middle": [
                        "C"
                    ],
                    "last": "Dar",
                    "suffix": ""
                },
... SNIPPED
                {
                    "first": "F",
                    "middle": [],
                    "last": "Sicheri",
                    "suffix": ""
                }
            ],
            "year": 2005,
            "venue": "Cell",
            "volume": "122",
            "issn": "",
            "pages": "887--900",
            "other_ids": {}
        },
        "BIBREF1": {
            "ref_id": "b1",
            "title": "Increased nuclease activity in cells treated with pppA2'p5'A2'p5' A",
            "authors": [
                {
                    "first": "A",
                    "middle": [
                        "G"
                    ],
                    "last": "Hovanessian",
                    "suffix": ""
                },
                ... SNIPPED
                {
                    "first": "L",
                    "middle": [],
                    "last": "Montagnier",
                    "suffix": ""
                }
            ],
            "year": 1979,
            "venue": "Proc Natl Acad Sci U S A",
            "volume": "76",
            "issn": "",
            "pages": "3261--3266",
            "other_ids": {}
        },
        "BIBREF2": {
            "ref_id": "b2",
            "title": "Interferon action--sequence specificity of the ppp(A2'p)nA-dependent ribonuclease",
            "authors": [
                {
                    "first": "D",
                    "middle": [
                        "H"
                    ],
                    "last": "Wreschner",
                    "suffix": ""
                },
                ... SNIPPED
                {
                    "first": "I",
                    "middle": [
                        "M"
                    ],
                    "last": "Kerr",
                    "suffix": ""
                }
            ],
            "year": 1981,
            "venue": "Nature",
            "volume": "289",
            "issn": "",
            "pages": "414--421",
            "other_ids": {}
        },
        ... SNIPPED
        "BIBREF47": {
            "ref_id": "b47",
            "title": "Size-dependent DNA mobility in cytoplasm and nucleus",
            "authors": [
                {
                    "first": "G",
                    "middle": [
                        "L"
                    ],
                    "last": "Lukacs",
                    "suffix": ""
                }
            ],
            "year": 2000,
            "venue": "J Biol Chem",
            "volume": "275",
            "issn": "",
            "pages": "1625--1634",
            "other_ids": {}
        },
        "BIBREF48": {
            "ref_id": "b48",
            "title": "Modeling transmembrane transport through cell membrane wounds created by acoustic cavitation",
            "authors": [
                {
                    "first": "V",
                    "middle": [],
                    "last": "Zarnitsyn",
                    "suffix": ""
                },
                ... SNIPPED
                {
                    "first": "M",
                    "middle": [
                        "R"
                    ],
                    "last": "Prausnitz",
                    "suffix": ""
                }
            ],
            "year": 2008,
            "venue": "Biophys J",
            "volume": "95",
            "issn": "",
            "pages": "4124--4162",
            "other_ids": {}
        }
    },
    ... SNIPPED
    "back_matter": [
        {
            "text": "We are grateful to Prof. Bonnie Bassler (Princeton University) for All NS All NS NS ** All ****",
            "cite_spans": [],
            "ref_spans": [],
            "section": "Acknowledgments:"
        }
    ]
}

There is a schema on the CORD-19 site, but entries such as BIBREF1 ... BIBREF48 vary in number over each data set. (Q what is the precise name for a BIBREF object - entry? Child?)

My current code is:

    @Test
    public void testReadJSON() {

        File jsonFile = new File(BIORXIV_MEDRXIV, "b801b7f92cff2155d98f0e3404229c67b60e2f9f.json");
        JsonObject oo = null;
        try {
            String resultsJsonString = IOUtils.toString(new FileInputStream(jsonFile), "UTF-8");
            JsonParser parser = new JsonParser();
            oo = (JsonObject) parser.parse(resultsJsonString);

        } catch (Exception e) {
            throw new RuntimeException("Cannot read CORD19 file: "+jsonFile, e);
        }

        String paperId = oo.get("paper_id").getAsString();
        System.out.println("id: "+paperId);

        JsonElement metadata = oo.get("metadata");
        JsonObject metadataObject = metadata.getAsJsonObject();
        String title = metadataObject.get("title").getAsString();
        System.out.println("title: "+title);

        JsonElement authorsObject = metadataObject.get("authors");
        System.out.println("Auth: "+authorsObject);
        JsonArray authors = authorsObject.getAsJsonArray();
        for (int i = 0; i < authors.size(); i++) {
            System.out.println(authors.get(i));
        }

        JsonElement abstrakt = oo.get("abstract");
        System.out.println("abstract: "+abstrakt);
        JsonArray texts = abstrakt.getAsJsonArray();
        for (int i = 0; i < texts.size(); i++) {
            System.out.println(texts.get(i));
        }

        JsonElement bodyText = oo.get("body_text");
        System.out.println("bodyText: "+bodyText);
        texts = bodyText.getAsJsonArray();
        for (int i = 0; i < texts.size(); i++) {
            System.out.println(texts.get(i));
        }

        JsonElement bibEntries = oo.get("bib_entries");
        System.out.println("bibEntries: "+bibEntries.getClass()+bibEntries);
        JsonObject obj = bibEntries.getAsJsonObject();
        // WHAT TO WRITE HERE?

    }

}

(Additional Q. I am learning Java8 so would appreciate answers in Java8 streams as well as Java7)

(Additional Q. [I would not normally "advertise" on Stack Overflow, but these are not normal times, and think this will help save lives, and provide opportunities for Stack Overflow members to contribute skills] I have set up volunteer projects to hack this dataset. I have had many years of extracting knowledge from scientific papers and believe that the existing papers may contain valuable pointers to new scientific knowledge.

Also - does Stack Overflow have a way of collecting expertise that can be re-used specifically for COVID-19?

ANSWER

Answered 2020-Mar-23 at 09:59

GSON's JsonObject offers the entrySet() method for iterating the contents.

for(Map.Entry<String,JsonElement> entry : obj.entrySet()) {
    String key = entry.getKey();     // BIBREF0
    JsonElement value = entry.getValue();   // details, can be cast to JsonObject
    processBibRef((JsonObject)value);       // For example
}

Streams won't help much here, but separate methods for subelements should be used to structure the code better, as in the example.

As can be seen, manually parsing JSON is cumbersome with Java, and when you're transforming JSON to for example HTML, the extra step of converting to objects makes other less typesafe languages such as Javascript more attractive.

Source https://stackoverflow.com/questions/60810617

QUESTION

Simple reverse navigation in datomic

Asked 2020-Jan-11 at 22:48

Learning Datomic, and having trouble with a basic case. Given a simple schema containing:

:club/name
:club/members (ref, cardinality many)

and

:people/name

So it might be populated (basically) like this:

[
{:club/name "Carpentry" :club/members [:person/name "liliana" :person/name "alexei"}]}
{:club/name "Taxidermy" :club/members [:person/name "karenna" :person/name "alexei"}]}
etc.
]

I want to do a reverse navigation to find "all the clubs 'alexei' is in". If I do this, I get only one club:

d/q '[:find (pull ?g [ {:club/_members [:club/name]}]) 
       :in $ 
       :where 
       [?g :person/name "alexei"]
       ]
     (d/db conn))

I would expect to get two hits for this example data. Am I modeling it backwards? Do I have to create a separate entity to express person-in-club?

Thanks much!

ANSWER

Answered 2020-Jan-11 at 22:48

I'm learning Datomic too, currently, I'm using Datahike because the syntax is similar & easier to dev on imo

Anyway I tried your example and came up with this:

(ns club
  (:require [datahike.api :as d]))

(def schema
  [{:db/ident :person/name
    :db/valueType :db.type/string
    :db/cardinality :db.cardinality/one}
   {:db/ident :club/name
    :db/valueType :db.type/string
    :db/cardinality :db.cardinality/one}
   {:db/ident :club/members
    :db/valueType :db.type/ref
    :db/cardinality :db.cardinality/many}])

(def database "datahike:mem://example")

(def data
  [{:club/name "Carpentry" :club/members [{:person/name "liliana"} {:person/name "alexei"}]}
   {:club/name "Taxidermy" :club/members [{:person/name "karenna"} {:person/name "alexei"}]}])

(comment
  (d/create-database database)

  (def conn (d/connect database))

  (d/transact conn schema)

  (d/transact conn data)

  (d/q '[:find (pull ?e [{:club/_members [:club/name]}])
         :where [?e :person/name "alexei"]]
       @conn))

Result:

([#:club{:_members [#:club{:name "Carpentry"}]}] [#:club{:_members [#:club{:name "Taxidermy"}]}])

Which I think is what you were looking for

There are two things that stand out to me in your comment that might have caused issue:

  • Your schema says people/name but your data says person/name
  • The club members vector in your data looks like it's mixing [ { I think you need a vector of two maps in there

But those issues might not be in your source code, could debug further if you'd like to share your source code

Hope this helps

Source https://stackoverflow.com/questions/59640205

QUESTION

Finning columns with 1 or 0 depending upon if the searched string exists

Asked 2019-Sep-11 at 10:57

I am trying to replace the string in a column with value 0 or 1 by searching for a specific word. The column consists of long sentences. How can I achieve that?

I tried searching for the words in the column but all I have been able to do far is check how many times the words exist or print the boolean values only.

xl['values'].fillna(0)
if (xl['values'].str.contains('ALEXEI').any()):
    xl['values'].str.replace(xl['values'],'1')

ANSWER

Answered 2019-Sep-11 at 10:57
xl['values']=np.where(xl['values'].str.contains('ALEXEI',na=False),1,0)

I find np.where() to be much quicker than any pandas method to do this kind of thing. The first argument is your search, the second is the returned value for True and the second for false.

Source https://stackoverflow.com/questions/57887267

QUESTION

How can I write csv.DictReader JSON structure back to TSV file via csv.DictWriter?

Asked 2019-Jul-17 at 17:07

I'm creating a python (Flask) application that will be deployed to a read-only file system in production. Overall, this application intends to:

  1. Parse a .TSV as a list of dictionaries (using the csv.DictReader) in a wrapper python script (main.py)
  2. Turn that list into a JSON structure (still main.py)
  3. Pass this JSON structure to another python script (author-script.py) as an argument in the command-line (since I can't save the .TSV file locally in production)
  4. Parse the JSON structure and write out to a temp TSV file in memory (now in author-script.py)
  5. Process that TSV file to produce an HTML file as a result (author-script.py)

For Step 4) I want the author-script.py script to parse this JSON structure ultimately like a .TSV file via csv.DictWriter. This is because, originally, author-script.py is set up to parse a TSV file and it would take too long to modify it so that it parses a dictionary.

Currently, my approach for doing this is to backtrack from the JSON structure back to dictionaries and then write these out via csv.DictWriter. Below is my attempt (demo-ing as if I'm starting within author-script.py to parse the JSON structure argument):

import csv
import json
from pprint import pprint
from ast import literal_eval

# This is the JSON structure that's passed to the python script
infile = '"[{\\"Manuscript preparation\\": \\"Y\\", \\"First_Name\\": \\"Anna\\", \\"Last_Name\\": \\"Karenina\\", \\"Tel\\": \\"8885006000\\", \\"Data generation\\": \\"Y\\", \\"Places\\": \\"BioInform_Harvard\\", \\"Fax\\": \\"8885006001\\", \\"Experimental design\\": \\"Y\\", \\"Joint\\": \\"1\\", \\"Data analysis\\": \\"Y\\", \\"Statistical analysis\\": \\"Y\\", \\"Data processing\\": \\"Y\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"anna.Karenina@ucsf.edu\\", \\"Initials\\": \\"A\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"Konstantin\\", \\"Last_Name\\": \\"Levin\\", \\"Tel\\": \\"8887006000\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"Neuro_Harvard\\", \\"Fax\\": \\"8887006001\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"1\\", \\"Data analysis\\": \\"Y\\", \\"Statistical analysis\\": \\"Y\\", \\"Data processing\\": \\"Y\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"Konstantin.levin@childrens.harvard.edu\\", \\"Initials\\": \\"D\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"Alexei\\", \\"Last_Name\\": \\"Vronsky\\", \\"Tel\\": \\"8889006000\\", \\"Data generation\\": \\"Y\\", \\"Places\\": \\"IGM_Columbia\\", \\"Fax\\": \\"8889006001\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"2\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"alexei.vronsky@cumc.columbia.edu\\", \\"Initials\\": \\"K\\"}, {\\"Manuscript preparation\\": \\"Y\\", \\"First_Name\\": \\"Stepan\\", \\"Last_Name\\": \\"Oblonsky\\", \\"Tel\\": \\"8891006000\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"NIMH\\", \\"Fax\\": \\"8891006001\\", \\"Experimental design\\": \\"Y\\", \\"Joint\\": \\"2\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"steoblon@mail.nih.gov\\", \\"Initials\\": \\"A\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"Ekaterina\\", \\"Last_Name\\": \\"Shcherbatskaya\\", \\"Tel\\": \\"8893006000\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"CHU_Montreal\\", \\"Fax\\": \\"8893006001\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"Y\\", \\"Statistical analysis\\": \\"Y\\", \\"Data processing\\": \\"Y\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"Ekaterina.Shcherbatskaya@umontreal.ca\\", \\"Initials\\": \\"A\\"}, {\\"Manuscript preparation\\": \\"Y\\", \\"First_Name\\": \\"Alexei\\", \\"Last_Name\\": \\"Karenin\\", \\"Tel\\": \\"8895006000\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"BioInform_Harvard, Neuro_Harvard\\", \\"Fax\\": \\"8895006001\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"Y\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"Karenin05@hms.harvard.edu\\", \\"Initials\\": \\"A\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"Fyodor\\", \\"Last_Name\\": \\"Dostoevsky\\", \\"Tel\\": \\"8897006000\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"Penn_Psych\\", \\"Fax\\": \\"8897006001\\", \\"Experimental design\\": \\"Y\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"Y\\", \\"Email\\": \\"Fyodor_Dostoevsky@pennmedicine.upenn.edu\\", \\"Initials\\": \\"M\\"}, {\\"Manuscript preparation\\": \\"Y\\", \\"First_Name\\": \\"Lev\\", \\"Last_Name\\": \\"Tolstoy\\", \\"Tel\\": \\"8899006000\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"UCSF_Weill\\", \\"Fax\\": \\"8899006001\\", \\"Experimental design\\": \\"Y\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"Y\\", \\"Statistical analysis\\": \\"Y\\", \\"Data processing\\": \\"Y\\", \\"Corresponding\\": \\"Y\\", \\"Email\\": \\"ltolstoy@mednet.ucla.edu\\", \\"Initials\\": \\"N\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"Place\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"Address\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"BioInform_Harvard\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"Department of Biomedical Informatics, Harvard Medical School, Boston, MA, USA\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"CHU_Montreal\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"CHU Sainte-Justine Research Centre, University of Montreal, 3175 Chemin de la Co_te-Sainte-Catherine, Montreal, Quebec H3T 1C5, Canada.\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"IGM_Columbia\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"Institute for Genomic Medicine, Columbia University Medical Center, Hammer Health Sciences, 1408, 701 West 168th St., New York, NY 10032, USA.\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"Neuro_Harvard\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"Department of Neurology, Boston Children\'s Hospital and Harvard Medical School, Boston, MA, USA\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"NIMH\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"National Institute of Mental Health, 10 Center Dr, Bethesda, MD 20814\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"Penn_Psych\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"Department of Psychiatry, Neuropsychiatry Section, Perelman School of Medicine at the University of Pennsylvania, 3400 Spruce, Philadelphia, PA 19104\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"UCSF_Weill\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"Department of Psychiatry, UCSF Weill Institute for Neurosciences, University of California, San Francisco, San Francisco, CA 94158\\"}]"'

# Convert json string that's passed to script into literal list of dicts
contents = literal_eval(json.loads(infile))

# Put list of dicts back into TSV "file" in memory
writer = csv.DictWriter(open("dict_write_test.tsv", 'w'), fieldnames=None, delimiter='\t')
for l in contents:
    writer.writerow(l)

The error I'm getting is TypeError: argument of type 'NoneType' is not iterable. I know how to make this work if I had the csv.DictReader object in the same script, but I wouldn't have that in this case.

My questions are:

  1. How exactly do I convert from JSON --> dictionaries --> DictReader object --> DictWriter --> TSV file?
  2. How do I write out to the .TSV file in memory?

UPDATE

When I test the following method by having the csv.DictReader object in the same code, the csv.DictWriter method obviously works fine and prints out the TSV file in memory as it looked in the original TSV. But when I implement @martineau's solution, the columns are outputted in a jumbled manner.

infile = open("/Users/cdastmalchi/Downloads/Author_Template.tsv")

contents = csv.DictReader(infile, delimiter='\t')
memory_file = io.StringIO()

writer = csv.DictWriter(memory_file, fieldnames=contents.fieldnames, delimiter='\t')
for row in contents:
    writer.writerow(row)

as_string = memory_file.getvalue()
print('\n'.join(as_string.splitlines()))

ANSWER

Answered 2019-Jul-17 at 17:07

You're getting the error because you have fieldnames=None in the csv.DictWriter() call. You can get the fieldnames from the keys of the first dictionary in the contents list.

The TSV file can be written to memory by using the io.StringIO class.

from ast import literal_eval
import csv
import json
import io
from pprint import pprint

# This is the JSON structure that's passed to the python script
infile = '"[{\\"Manuscript preparation\\": \\"Y\\", \\"First_Name\\": \\"Anna\\", \\"Last_Name\\": \\"Karenina\\", \\"Tel\\": \\"8885006000\\", \\"Data generation\\": \\"Y\\", \\"Places\\": \\"BioInform_Harvard\\", \\"Fax\\": \\"8885006001\\", \\"Experimental design\\": \\"Y\\", \\"Joint\\": \\"1\\", \\"Data analysis\\": \\"Y\\", \\"Statistical analysis\\": \\"Y\\", \\"Data processing\\": \\"Y\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"anna.Karenina@ucsf.edu\\", \\"Initials\\": \\"A\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"Konstantin\\", \\"Last_Name\\": \\"Levin\\", \\"Tel\\": \\"8887006000\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"Neuro_Harvard\\", \\"Fax\\": \\"8887006001\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"1\\", \\"Data analysis\\": \\"Y\\", \\"Statistical analysis\\": \\"Y\\", \\"Data processing\\": \\"Y\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"Konstantin.levin@childrens.harvard.edu\\", \\"Initials\\": \\"D\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"Alexei\\", \\"Last_Name\\": \\"Vronsky\\", \\"Tel\\": \\"8889006000\\", \\"Data generation\\": \\"Y\\", \\"Places\\": \\"IGM_Columbia\\", \\"Fax\\": \\"8889006001\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"2\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"alexei.vronsky@cumc.columbia.edu\\", \\"Initials\\": \\"K\\"}, {\\"Manuscript preparation\\": \\"Y\\", \\"First_Name\\": \\"Stepan\\", \\"Last_Name\\": \\"Oblonsky\\", \\"Tel\\": \\"8891006000\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"NIMH\\", \\"Fax\\": \\"8891006001\\", \\"Experimental design\\": \\"Y\\", \\"Joint\\": \\"2\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"steoblon@mail.nih.gov\\", \\"Initials\\": \\"A\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"Ekaterina\\", \\"Last_Name\\": \\"Shcherbatskaya\\", \\"Tel\\": \\"8893006000\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"CHU_Montreal\\", \\"Fax\\": \\"8893006001\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"Y\\", \\"Statistical analysis\\": \\"Y\\", \\"Data processing\\": \\"Y\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"Ekaterina.Shcherbatskaya@umontreal.ca\\", \\"Initials\\": \\"A\\"}, {\\"Manuscript preparation\\": \\"Y\\", \\"First_Name\\": \\"Alexei\\", \\"Last_Name\\": \\"Karenin\\", \\"Tel\\": \\"8895006000\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"BioInform_Harvard, Neuro_Harvard\\", \\"Fax\\": \\"8895006001\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"Y\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"Karenin05@hms.harvard.edu\\", \\"Initials\\": \\"A\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"Fyodor\\", \\"Last_Name\\": \\"Dostoevsky\\", \\"Tel\\": \\"8897006000\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"Penn_Psych\\", \\"Fax\\": \\"8897006001\\", \\"Experimental design\\": \\"Y\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"Y\\", \\"Email\\": \\"Fyodor_Dostoevsky@pennmedicine.upenn.edu\\", \\"Initials\\": \\"M\\"}, {\\"Manuscript preparation\\": \\"Y\\", \\"First_Name\\": \\"Lev\\", \\"Last_Name\\": \\"Tolstoy\\", \\"Tel\\": \\"8899006000\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"UCSF_Weill\\", \\"Fax\\": \\"8899006001\\", \\"Experimental design\\": \\"Y\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"Y\\", \\"Statistical analysis\\": \\"Y\\", \\"Data processing\\": \\"Y\\", \\"Corresponding\\": \\"Y\\", \\"Email\\": \\"ltolstoy@mednet.ucla.edu\\", \\"Initials\\": \\"N\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"Place\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"Address\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"BioInform_Harvard\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"Department of Biomedical Informatics, Harvard Medical School, Boston, MA, USA\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"CHU_Montreal\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"CHU Sainte-Justine Research Centre, University of Montreal, 3175 Chemin de la Co_te-Sainte-Catherine, Montreal, Quebec H3T 1C5, Canada.\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"IGM_Columbia\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"Institute for Genomic Medicine, Columbia University Medical Center, Hammer Health Sciences, 1408, 701 West 168th St., New York, NY 10032, USA.\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"Neuro_Harvard\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"Department of Neurology, Boston Children\'s Hospital and Harvard Medical School, Boston, MA, USA\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"NIMH\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"National Institute of Mental Health, 10 Center Dr, Bethesda, MD 20814\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"Penn_Psych\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"Department of Psychiatry, Neuropsychiatry Section, Perelman School of Medicine at the University of Pennsylvania, 3400 Spruce, Philadelphia, PA 19104\\"}, {\\"Manuscript preparation\\": \\"\\", \\"First_Name\\": \\"UCSF_Weill\\", \\"Last_Name\\": \\"\\", \\"Tel\\": \\"\\", \\"Data generation\\": \\"\\", \\"Places\\": \\"\\", \\"Fax\\": \\"\\", \\"Experimental design\\": \\"\\", \\"Joint\\": \\"\\", \\"Data analysis\\": \\"\\", \\"Statistical analysis\\": \\"\\", \\"Data processing\\": \\"\\", \\"Corresponding\\": \\"\\", \\"Email\\": \\"\\", \\"Initials\\": \\"Department of Psychiatry, UCSF Weill Institute for Neurosciences, University of California, San Francisco, San Francisco, CA 94158\\"}]"'

# Convert json string that's passed to script into literal list of dicts
contents = json.loads(literal_eval(infile))
fieldnames = contents[0].keys()  # Get TSV fieldnames from first dictionary.

# Put list of dicts back into TSV "file" in memory
memory_file = io.StringIO()
writer = csv.DictWriter(memory_file, fieldnames=fieldnames, delimiter='\t')
writer.writerows(contents)

as_string = memory_file.getvalue()
print('\n'.join(as_string.splitlines()))

You may have problems passing the file as a command-line argument if the file is very big.

Source https://stackoverflow.com/questions/57048278

QUESTION

Is there something better than preprocessor directives (#if, etc) in C#?

Asked 2019-Jul-11 at 21:17

Most questions of this type are seeking to alter the program behavior (things that could be decided at run time) or want to deal directly with debug printing. This is a bit different.

I have code that depends on a peripheral (like a card reader). Sometimes I don't use it, which means the library isn't present. (And I'm being nice, because "library" turns out to mean installing a 2GB software suite). When I remove the library, I can't open the device. If I can't open the device, I can't create the class member that uses it. With the class inoperative, I can't call its methods from within the code. Therefore, I can't just choose not to execute it; I need it to go away since it will not compile without the library.

Preprocessor directives like #if and all that are ok, maybe; but these things appear in more than one file, which means independently maintaining a #define at the top of each. I come from a simpler place (meaning, C) where one header file can be used to control this. I note that C# is rather hostile about #define (either the label exists, or not; no constants or calculations allowed), and that makes me think there's another way.

How do you handle this?

---Follow-up(s)---

I did read the "duplicate" Q/A's, and have a fairly good picture of what I'm dealing with. I didn't find those questions in my original search, but sometimes that's just how it is.

@Amy suggests that #define at the top is "not how it's done" but rather "put it on the command line". So, (if I realize we are sticking with this mechanism) the discussion might go to examining ways to have that happen . One does not simply drop to a terminal and do that. It happens as "IDE features" or "IDE hacks".

@Alexei Levenkov asks what I really want. I really want to (a) not get compile errors, and (b) do it by selectively leaving out the code. And, find the C# equivalent to the way I proposed. Some more constraints are addressed by the fact that I haven't been using VS or C# for all that long. So I know a lot less than you all do. Considering I got the code from the last person and have to deal with what I see, I don't want to set up the person after me to have to figure out what "interesting" thing I might have done to make it work. Thus, things like hand-editing a project file may work but will also cause consternation down the line.

@ Eric Lippert suggests "hostile" is really "sensible". I may have had my tongue too far into my cheek on that one. VS seems to be telling me I'm doing it wrong, so I sensed there's a "right way" I simply don't know about. As for the 2GB supporting application, I will go to various computers and pull down the repository and try out something, and so this "overhead" wants to propagate with it. It's worse if I'm linked through my phone to do the download. And if I build the application with everything included, the end user is then required to install that software suite before the program will run. In theory, they could be required to buy the software. If I sent you a tic-tac-toe game, and told you it wouldn't run until you installed Oracle, you'd probably pass on the whole thing.

I considered the "stub out the interface" idea, but there seemed to be more hooks into the class than I wanted to deal with. Plus, I don't know what these things do, so I have to know something about them in order to "fake" them.

In the end I decided that we're still largely using the #if scheme to get this done, and the replacement feature I imagined might exist, doesn't. And I'm using the provision in the project file(s) as cited by @Jim G. as it gets the job done and is only a little imperfect. It's good enough.

ANSWER

Answered 2019-Jul-09 at 19:36

As @BJ Safdie said here:

  • Set them in your Compilation Properties or Build options.
  • You get to the build options by right-clicking the project and selecting properties from the menu.

Project Build Options

Source https://stackoverflow.com/questions/56959419

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

VULNERABILITIES

No vulnerabilities reported

INSTALL Alexei

You can use Alexei like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the Alexei component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

SUPPORT

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

Implement Alexei faster with kandi.

  • Use the support, quality, security, license, reuse scores and reviewed functions to confirm the fit for your project.
  • Use the, Q & A, Installation and Support guides to implement faster.

Discover Millions of Libraries and
Pre-built Use Cases on kandi