text:
Q: Looking for a script or something to generate the numbers 1.1.1.1 to 255.255.255.255 Yes thats right, I am looking for a script or anything that can generate an ip address
list from 1.1.1.1 to 255.255.255.255. Even if its something like cat or grep that generates
the numbers 1.1.1.1 to 255.255.255.255. Thanks!
I found 1 python script but it seems to not work very well.

A: A simple C program:
#include <stdio.h>
#include <limits.h>

#if UINT_MAX != 4294967295
#error Assumes 32-bit ints for stopping condition.
#endif

int main() {
  unsigned n = 0x01010101;
  for ( ; n != 0; ++n)
    printf("%d.%d.%d.%d\n", n>>24, (n>>16)&0xff, (n>>8)&0xff, n&0xff);
  return 0;
}

Just redirect standard output to a file and leave it running for ... I don't know how long.

A: I'm assuming you're looking for a string format?
int a,b,c,d;
char address[16];
char e[4],f[4],g[4],h[4];
for(a=1;a<=255;a++)
{
    for(b=1;b<=255;b++)
    {
        for(c=1;c<=255;c++)
        {
            for(d=1;d<=255;d++)
            {
                //You'll want to clear e,f,g, and h here, as well as null-terminating
                //them once they've been cast and copied.
                strcpy(e,((char)(a)));//Cast your rolling 'int's to 'char's
                strcpy(f,((char)(b)));
                strcpy(g,((char)(c)));
                strcpy(h,((char)(d)));
                strcpy(address,"\0");//Clear your string before constructing
                strcat(address,e);
                strcat(address,'.');//Might need double-quotes(".")
                strcat(address,f);
                strcat(address,'.');
                strcat(address,g);
                strcat(address,'.');
                strcat(address,h);
                strcat(address,'\0');
                //Do whatever you need to do here. (Copy to array or whatever)
            }
        }
    }
}


text:
Q: Many to many association preload error in Ecto I am learning Ecto and was trying out many to many relationship.
I am using MySQL DB,

schemas are like this

User Schema

  @primary_key {:id, :binary_id, autogenerate: true}
  schema "users" do
    field(:name, :string, required: true)
    field(:hashed_password, :string, required: true)
    field(:password, :string, virtual: true)
    timestamps()

    many_to_many(:methods, Bookie.Method.Model, join_through: "users_methods", on_replace: :delete)
  end

Methods Schema

  @primary_key {:id, :binary_id, autogenerate: true}
  schema "methods" do
    field(:function, :string, required: true)
    field(:method, :string, required: true)
    timestamps()

    many_to_many(:users, Bookie.User.Model, join_through: "users_methods", on_replace: :delete)
  end

the association of these 2 schema - users_methods

  schema "users_methods" do
    belongs_to(:users, Bookie.User.Model, type: :binary_id)
    belongs_to(:methods, Bookie.Method.Model, type: :binary_id)
  end

These are my migrations
  create table(:users, primary_key: false) do
      add(:id, :uuid, primary_key: true)
      add(:name, :string, null: false)
      add(:hashed_password, :string, null: false)
      timestamps()
    end

   create(unique_index(:users, [:name]))

    create table(:methods, primary_key: false) do
      add(:id, :uuid, primary_key: true)
      add(:function, :string, null: false)
      add(:method, :string, null: false)
      timestamps()
    end

 create table(:users_methods, primary_key: false) do
      add(:user_id, references("users", type: :uuid, on_delete: :delete_all))
      add(:method_id, references("methods", type: :uuid, on_delete: :delete_all))
    end

    create(index(:users_methods, [:method_id]))
    create(index(:users_methods, [:user_id]))

    create(
      unique_index(:users_methods, [:user_id, :method_id], name: :user_id_method_id_unique_index)
    )

This is my basic setup. Now as soon as i try to preload methods after querying/inserting user it gives me error.
  user_map = %{name: "User 1", password: "password"}

  changeset =
    User.changeset(%User{}, user_map)
    |> Ecto.Changeset.put_change(
      :hashed_password,
      User.hashed_password(changeset.changes[:password])
    )

  user =
    Repo.insert!(changeset)
    |> Repo.preload(:methods)

Error

  [debug] QUERY OK db=2.6ms queue=0.1ms
begin []
[debug] QUERY OK db=3.5ms
INSERT INTO `users` (`hashed_password`,`name`,`inserted_at`,`updated_at`,`id`) VALUES (?,?,?,?,?) ["$2b$12$6W3zoeCnfLRV3N0fzv5t..LFnZly93G4IvfM5DfQSaEWPLtK0jV8q", "User 1", {{2019, 6, 8}, {14, 29, 25, 458464}}, {{2019, 6, 8}, {14, 29, 25, 458477}}, <<208, 210, 137, 42, 54, 3, 75, 211, 148, 173, 9, 174, 171, 125, 44, 225>>]
[debug] QUERY OK db=0.7ms
commit []
[debug] QUERY ERROR source="methods" db=29.5ms
SELECT m0.`id`, m0.`function`, m0.`method`, m0.`inserted_at`, m0.`updated_at`, u1.`id` FROM `methods` AS m0 INNER JOIN `users` AS u1 ON u1.`id` IN (?) INNER JOIN `users_methods` AS u2 ON u2.`model_id` = u1.`id` WHERE (u2.`model_id` = m0.`id`) ORDER BY u1.`id` [<<208, 210, 137, 42, 54, 3, 75, 211, 148, 173, 9, 174, 171, 125, 44, 225>>]
** (Mariaex.Error) (1054): Unknown column 'u2.model_id' in 'where clause'
    (ecto) lib/ecto/adapters/sql.ex:450: Ecto.Adapters.SQL.sql_call!/6
    (ecto) lib/ecto/adapters/sql.ex:420: Ecto.Adapters.SQL.do_execute/6
    (ecto) lib/ecto/repo/queryable.ex:133: Ecto.Repo.Queryable.execute/5
    (ecto) lib/ecto/repo/queryable.ex:37: Ecto.Repo.Queryable.all/4
    (elixir) lib/enum.ex:1327: Enum."-map/2-lists^map/1-0-"/2

(Mariaex.Error) (1054): Unknown column 'u2.model_id' in 'where clause'

I am not getting above part :(
please someone help.

A: The association foreign key is inflected from the last part of the schema name. Since all of your schemas are named Foo.Bar.Model, they all default to model_id. You can pass the join_keys option, to specify the relationships.
For example:
many_to_many(:methods, Bookie.Method.Model, join_through: "users_methods", on_replace: :delete)

should be:
many_to_many(:methods, Bookie.Method.Model, join_through: "users_methods", join_keys: [user_id: :id, method_id: :id], on_replace: :delete)

And:
many_to_many(:users, Bookie.User.Model, join_through: "users_methods", on_replace: :delete)

Should be:
many_to_many(:users, Bookie.User.Model, join_through: "users_methods", join_keys: [method_id: :id, user_id: :id], on_replace: :delete)

Although I would recommend following Ecto's naming convention, then everything will become much simpler.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to ignore `java.nio.charset.MalformedInputException` and replace wrong characters to anything else temporarily? The majority of my users don't know how to solve the charset error, they always ask this question in user groups. So I want to find a solution choosing proper charset automatically.
The first solution is fixed charset property in configuration file. For example, program will load the yaml file in any charset, and read the property metadata.charset, then reload it in this charset.
This is my code choosing property charset:
if (Objects.isNull(charset)) {
  if (getInputFile().exists()) {

    final InputStream inputStream = getInputStream();
    final Object object = yaml.load(inputStream);  // line 85

    if (object instanceof Map) {
      try {
        @SuppressWarnings("unchecked")
        final String charsetName = Structure.of((Map<String, Object>) object).getStringOrFail(charsetPath);
        charset = Charset.forName(charsetName);
      } catch (Throwable throwable) {
        throw new IOException("can not find the charset in auto charset yaml file: " + getInputFile(), throwable);
      }
    } else {
      throw new IOException("yaml value is an instance of type '" + object.getClass().getName() + "', not required 'Map<String, Object>'!");
    }
  } else {
    charset = defaultCharset;
  }
}

The charset of my users' device are inconsistent, and they maybe share configuration file to each other. Consider following situation: If the shared configuration, includes characters can not load in UTF-8, is saved in GBK, and is loading in a device which charset defaults UTF-8, we will get a exception:
java.nio.charset.MalformedInputException: Input length = 1
org.yaml.snakeyaml.error.YAMLException: java.nio.charset.MalformedInputException: Input length = 1
    at org.yaml.snakeyaml.reader.StreamReader.update(StreamReader.java:218)
    at org.yaml.snakeyaml.reader.StreamReader.ensureEnoughData(StreamReader.java:176)
    at org.yaml.snakeyaml.reader.StreamReader.ensureEnoughData(StreamReader.java:171)
    at org.yaml.snakeyaml.reader.StreamReader.peek(StreamReader.java:126)
    at org.yaml.snakeyaml.scanner.ScannerImpl.scanToNextToken(ScannerImpl.java:1218)
    at org.yaml.snakeyaml.scanner.ScannerImpl.fetchMoreTokens(ScannerImpl.java:329)
    at org.yaml.snakeyaml.scanner.ScannerImpl.checkToken(ScannerImpl.java:251)
    at org.yaml.snakeyaml.parser.ParserImpl$ParseImplicitDocumentStart.produce(ParserImpl.java:214)
    at org.yaml.snakeyaml.parser.ParserImpl.peekEvent(ParserImpl.java:166)
    at org.yaml.snakeyaml.parser.ParserImpl.checkEvent(ParserImpl.java:156)
    at org.yaml.snakeyaml.composer.Composer.getSingleNode(Composer.java:141)
    at org.yaml.snakeyaml.constructor.BaseConstructor.getSingleData(BaseConstructor.java:151)
    at org.yaml.snakeyaml.Yaml.loadFromReader(Yaml.java:491)
    at org.yaml.snakeyaml.Yaml.load(Yaml.java:429)
    at cn.codethink.xiaoming.platform.configuration.io.AutoCharsetYamlFileInputOutputImpl.getCharset(AutoCharsetYamlFileInputOutputImpl.java:85)
    at cn.codethink.xiaoming.platform.configuration.io.AutoCharsetYamlFileInputOutputImpl.getReader(AutoCharsetYamlFileInputOutputImpl.java:70)
    at cn.codethink.xiaoming.platform.configuration.AbstractTextConfiguration.load(AbstractTextConfiguration.java:37)
    at cn.codethink.xiaoming.platform.configuration.AbstractTextConfiguration.load(AbstractTextConfiguration.java:87)
    at cn.codethink.xiaoming.platform.configuration.ConfigurationTest.testAutoCharsetYamlFile(ConfigurationTest.java:54)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:727)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:156)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:147)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:86)
    at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(InterceptingExecutableInvoker.java:103)
    at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.lambda$invoke$0(InterceptingExecutableInvoker.java:93)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:92)
    at org.junit.jupiter.engine.execution.InterceptingExecutableInvoker.invoke(InterceptingExecutableInvoker.java:86)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:217)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:213)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:138)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:68)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at com.sun.proxy.$Proxy2.stop(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:135)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.nio.charset.MalformedInputException: Input length = 1
    at java.nio.charset.CoderResult.throwException(CoderResult.java:281)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:339)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
    at java.io.InputStreamReader.read(InputStreamReader.java:184)
    at org.yaml.snakeyaml.reader.UnicodeReader.read(UnicodeReader.java:125)
    at org.yaml.snakeyaml.reader.StreamReader.update(StreamReader.java:183)
    ... 108 more

How to ignore it and replace wrong characters to anything else temporarily (only in this context, the exception will be thrown at other codes in same program)?
I found solutions choosing property charset: use head charset comments like Python, and just read a few characters by InputStream (but I don't think it's graceful enough), or use BOM. But I still want to know how to solve the problem.


text:
Q: How to asterisks the text like a password but show a couple letters? I want to make the username covered like a password is, but to be revealed 1 or 2 letters. I attached what i mean in images
what i mean when i want it to be revealed
example of what i mean by covered like password
Here is my code for the 2 boxes from .css and .html, they are in body ofcourse

input[type="text"] {
  color: #000;
}

input[type="password"] {
  color: #000;
}

input {
  width: 40%;
  height: 30px;
  position: relative;
  top: -4px;
  font-size: 20px;
  padding: 0 .3em;
  color: #555555;
}
<p2>
  Username
  <input type="text" name="username" />
</p2>

<p2>
  Password
  <input type="password" name="pwd" />
</p2>

edit: p2 in css

p2{
    position: relative;
    left: -65px;
    display: block;
    margin-block-start: 1em;
    margin-block-end: 1em;
    margin-inline-start: 0px;
    margin-inline-end: 0px;
    text-align: center;
    }

A: You can try it with "pseudo" css classes, like `:after`` and span for the replaced content.
You need a monospace font, to keep the width on the same level.

Hello World

.replace_by_char span{
  color: red;
  visibility: hidden;
  position: relative;
  font-family: monospace;
}

.replace_by_char span:after {
  visibility: visible;
  position: absolute;
  top: 0;
  left: 0;
  content: "***";
}


text:
Q: Problems coming in a canvas object following the mouse pointer in tkinter canvas I am trying to make a simple rectangle which will follow my mouse pointer on canvas. But when I move the pointer over the canvas , the rectangle disappears . I implemented a time.sleep() function in between to cause a delay and see actually where does it go , and it happened to move out of the canvas.
My code :
pointer = canvas.create_rectangle(10,10,20,20, fill = "red")

def pointer_mouse(event):
     x,y = event.x, event.y
     canvas.move(pointer, x, y)


text:
Q: java.lang.RuntimeException: Unable to instantiate application. Crash on launch When I try to run the react native app on android in debug mode, it crashes as soon as it launches without any error. Opening the app a few times throws an exception with the error mentioned below  Everything was working fine yesterday, but today it won't work anymore. Any help would be very appreciated.
java.lang.RuntimeException: Unable to instantiate application com.sensights.MainApplication package com.sensights: java.lang.ClassNotFoundException: Didn't find class "com.sensights.MainApplication" on path: DexPathList[[zip file "/data/app/~~XrS92eK0FL1rdOtvadinMg==/com.sensights-7FJVzYCKNOkXrB-fDIbxyQ==/base.apk"],nativeLibraryDirectories=[/data/app/~~XrS92eK0FL1rdOtvadinMg==/com.sensights-7FJVzYCKNOkXrB-fDIbxyQ==/lib/arm64, /data/app/~~XrS92eK0FL1rdOtvadinMg==/com.sensights-7FJVzYCKNOkXrB-fDIbxyQ==/base.apk!/lib/arm64-v8a, /system/lib64, /system/system_ext/lib64]]
    at android.app.LoadedApk.makeApplication(LoadedApk.java:1385)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:7054)
    at android.app.ActivityThread.access$1700(ActivityThread.java:275)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2168)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loopOnce(Looper.java:210)
    at android.os.Looper.loop(Looper.java:299)
    at android.app.ActivityThread.main(ActivityThread.java:8280)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:576)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1073)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.sensights.MainApplication" on path: DexPathList[[zip file "/data/app/~~XrS92eK0FL1rdOtvadinMg==/com.sensights-7FJVzYCKNOkXrB-fDIbxyQ==/base.apk"],nativeLibraryDirectories=[/data/app/~~XrS92eK0FL1rdOtvadinMg==/com.sensights-7FJVzYCKNOkXrB-fDIbxyQ==/lib/arm64, /data/app/~~XrS92eK0FL1rdOtvadinMg==/com.sensights-7FJVzYCKNOkXrB-fDIbxyQ==/base.apk!/lib/arm64-v8a, /system/lib64, /system/system_ext/lib64]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:259)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at android.app.AppComponentFactory.instantiateApplication(AppComponentFactory.java:76)
    at androidx.core.app.CoreComponentFactory.instantiateApplication(CoreComponentFactory.java:52)
    at android.app.Instrumentation.newApplication(Instrumentation.java:1177)
    at android.app.LoadedApk.makeApplication(LoadedApk.java:1377)
    ... 10 more

I tried cleaning the project and building again but it didn't work.
This is my android/app/build.gradle :
apply plugin: "com.android.application"
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'

import com.android.build.OutputFile

/**
 * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
 * and bundleReleaseJsAndAssets).
 * These basically call `react-native bundle` with the correct arguments during the Android build
 * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
 * bundle directly from the development server. Below you can see all the possible configurations
 * and their defaults. If you decide to add a configuration block, make sure to add it before the
 * `apply from: "../../node_modules/react-native/react.gradle"` line.
 *
 * project.ext.react = [
 *   // the name of the generated asset file containing your JS bundle
 *   bundleAssetName: "index.android.bundle",
 *
 *   // the entry file for bundle generation. If none specified and
 *   // "index.android.js" exists, it will be used. Otherwise "index.js" is
 *   // default. Can be overridden with ENTRY_FILE environment variable.
 *   entryFile: "index.android.js",
 *
 *   // https://facebook.github.io/react-native/docs/performance#enable-the-ram-format
 *   bundleCommand: "ram-bundle",
 *
 *   // whether to bundle JS and assets in debug mode
 *   bundleInDebug: false,
 *
 *   // whether to bundle JS and assets in release mode
 *   bundleInRelease: true,
 *
 *   // whether to bundle JS and assets in another build variant (if configured).
 *   // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
 *   // The configuration property can be in the following formats
 *   //         'bundleIn${productFlavor}${buildType}'
 *   //         'bundleIn${buildType}'
 *   // bundleInFreeDebug: true,
 *   // bundleInPaidRelease: true,
 *   // bundleInBeta: true,
 *
 *   // whether to disable dev mode in custom build variants (by default only disabled in release)
 *   // for example: to disable dev mode in the staging build type (if configured)
 *   devDisabledInStaging: true,
 *   // The configuration property can be in the following formats
 *   //         'devDisabledIn${productFlavor}${buildType}'
 *   //         'devDisabledIn${buildType}'
 *
 *   // the root of your project, i.e. where "package.json" lives
 *   root: "../../",
 *
 *   // where to put the JS bundle asset in debug mode
 *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
 *
 *   // where to put the JS bundle asset in release mode
 *   jsBundleDirRelease: "$buildDir/intermediates/assets/release",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in debug mode
 *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in release mode
 *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
 *
 *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means
 *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
 *   // date; if you have any other folders that you want to ignore for performance reasons (gradle
 *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
 *   // for example, you might want to remove it from here.
 *   inputExcludes: ["android/**", "ios/**"],
 *
 *   // override which node gets called and with what additional arguments
 *   nodeExecutableAndArgs: ["node"],
 *
 *   // supply additional arguments to the packager
 *   extraPackagerArgs: []
 * ]
 */

project.ext.react = [
    enableHermes: false,  // clean and rebuild if changing
    bundleInDebug: false,
    bundleInRelease: true,
    entryFile: "index.js"
]

apply from: "../../node_modules/react-native/react.gradle"

apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

Project background_geolocation = project(':react-native-background-geolocation')
apply from: "${background_geolocation.projectDir}/app.gradle"

/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = false

/**
 * The preferred build flavor of JavaScriptCore.
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US.  Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'org.webkit:android-jsc:+'

/**
 * Whether to enable the Hermes VM.
 *
 * This should be set on project.ext.react and mirrored here.  If it is not set
 * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
 * and the benefits of using Hermes will therefore be sharply reduced.
 */
def enableHermes = project.ext.react.get("enableHermes", false)

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    dexOptions {
        javaMaxHeapSize "4g"
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    buildFeatures {
        dataBinding true
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    defaultConfig {
        applicationId "com.sensights"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 35
        versionName "1.5.1"
        multiDexEnabled true
    }
    splits {
        abi {
            reset()
            enable true
            // enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'sensights'
            keyPassword 'android'
        }
//release will be here
 release {
            storeFile file('keystore.jks')
            storePassword 'sensights'
            keyAlias 'upload'
            keyPassword 'sensights'
        }
    // release {
    //         if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) {
    //             storeFile file(MYAPP_UPLOAD_STORE_FILE)
    //             storePassword MYAPP_UPLOAD_STORE_PASSWORD
    //             keyAlias MYAPP_UPLOAD_KEY_ALIAS
    //             keyPassword MYAPP_UPLOAD_KEY_PASSWORD
    //         }
        }

    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://facebook.github.io/react-native/docs/signed-apk-android.
            //needs to be signingConfigs.release
            signingConfig signingConfigs.release
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }

    packagingOptions {
        pickFirst "lib/armeabi-v7a/libc++_shared.so"
        pickFirst "lib/arm64-v8a/libc++_shared.so"
        pickFirst "lib/x86/libc++_shared.so"
        pickFirst "lib/x86_64/libc++_shared.so"
    }

    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // https://developer.android.com/studio/build/configure-apk-splits.html
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }

        }
    }

    project.afterEvaluate {
        def isAndroidLibrary = plugins.hasPlugin("com.android.library")
        def variants = isAndroidLibrary ? android.libraryVariants : android.applicationVariants
           variants.all { def variant ->
        def targetName = variant.name.capitalize()
        def mergeResourcesTask = tasks.findByName("merge${targetName}Resources")
        def assetsCopyTask = tasks.findByName("copy${targetName}BundledJs")
        mergeResourcesTask.dependsOn(assetsCopyTask)
        logger.warn("Making task ${mergeResourcesTask} depend on ${assetsCopyTask}")
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    //noinspection GradleDynamicVersion
    implementation "com.facebook.react:react-native:+"  // From node_modules

    implementation "androidx.multidex:multidex:2.0.1"

//     implementation "org.jetbrains:kotlin:kotlin-stdlib:$kotlin_version"

    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"

    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
      exclude group:'com.facebook.fbjni'
    }

    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }

    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }
    implementation group: 'com.zendesk', name: 'chat', version: '3.1.0'
    implementation group: 'com.zendesk', name: 'messaging', version: '5.1.0'
    // implementation project(':react-native-contacts')

    // implementation project(':react-native-geocoder')

    // implementation project(':react-native-immediate-phone-call')

    // implementation project(':react-native-location')

    // Pushy SDK for Android
    implementation 'me.pushy:sdk:1.0.67'

    // Pushy SDK for React Native Android
    implementation 'me.pushy:sdk-react-native:1.0.15'

    implementation project(':WebRTCModule')

    if (enableHermes) {
        def hermesPath = "../../node_modules/hermes-engine/android/"
        debugImplementation files(hermesPath + "hermes-debug.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor
    }

    //lifecycle
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.2.0'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'

    //Coroutines
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.7'
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'

    //CameraX
//     implementation "androidx.camera:camera-core:1.0.2"
//     implementation "androidx.camera:camera-camera2:1.0.2"
//     implementation "androidx.camera:camera-lifecycle:1.0.2"
//     implementation "androidx.camera:camera-view:1.0.0-alpha28"

    implementation "androidx.camera:camera-core:1.0.2"
    implementation "androidx.camera:camera-camera2:1.0.2"
    implementation "androidx.camera:camera-lifecycle:1.0.2"
    implementation "androidx.camera:camera-view:1.0.0-alpha28"

    //ML
    implementation 'com.google.mlkit:face-detection:16.1.2'
    implementation "org.tensorflow:tensorflow-lite:2.2.0"
    implementation "org.tensorflow:tensorflow-lite-gpu:2.2.0"
    implementation 'org.tensorflow:tensorflow-lite-support:0.0.0-nightly'

    //OpenCV
    //implementation "com.quickbirdstudios:opencv:3.4.5"

    //Retrofit
    implementation "com.squareup.okhttp3:okhttp:4.7.2"
    implementation "com.squareup.retrofit2:retrofit:2.9.0"
    implementation "com.squareup.retrofit2:converter-gson:2.9.0"

    //Constrain, Material , Androidx
    implementation "com.google.android.material:material:1.1.0"
    implementation "androidx.appcompat:appcompat:1.0.2"
    implementation "com.android.support.constraint:constraint-layout:1.1.3"
    implementation 'com.android.support:multidex:1.0.3'

}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)

Here is my android/build.gradle file:
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        googlePlayServicesLocationVersion = "17.0.0"  // Or higher.
        // buildToolsVersion = "28.0.3"
        buildToolsVersion = "30.0.3"
        minSdkVersion = 24
        compileSdkVersion = 31
        targetSdkVersion = 30
        appCompatVersion = "1.1.0"      // Or higher.  Required for new AndroidX compatibility.
        supportLibVersion = "28.0.0"
        playServicesVersion = "17.0.0"
//        androidMapsUtilsVersion = "+0.5"
        // # Only using Android Support libraries
        androidXCore = "1.3.1"
        androidXAnnotation = "1.3.0"
        androidXBrowser = "1.3.0"
        kotlin_version = "1.6.21"

        // buildToolsVersion = "28.0.3"
        // minSdkVersion = 16
        // compileSdkVersion = 28
        // targetSdkVersion = 28
    }
    repositories {
        google()
        jcenter()
        mavenCentral()
        maven { url "https://jitpack.io" }
    }
    dependencies {
    classpath("com.android.tools.build:gradle:4.1.3")
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenCentral()
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }
        maven {
            // Required for react-native-background-geolocation
            url("${project(':react-native-background-geolocation').projectDir}/libs")
        }
        maven {
            // Required for react-native-background-fetch
            url("${project(':react-native-background-fetch').projectDir}/libs")
        }
        maven { url 'https://zendesk.jfrog.io/zendesk/repo' }
        google()
        jcenter()
        maven { url 'https://www.jitpack.io' }

    }
}
subprojects {
    afterEvaluate {project ->
        if (project.hasProperty("android")) {
            android {
                compileSdkVersion rootProject.ext.compileSdkVersion
                buildToolsVersion rootProject.ext.buildToolsVersion
            }
        }
    }
}

Here is my AndroidManifest.xml file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.sensights">

    <uses-feature android:name="android.hardware.camera"/>
    <uses-feature android:name="android.hardware.camera.autofocus"/>

    <uses-permission android:name="android.permission.INTERNET" />
    <!-- Pushy Permissions -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <!-- End Pushy Permissions -->
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <uses-permission-sdk-23 android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <uses-permission android:name="android.permission.READ_CONTACTS"/>
    <uses-permission android:name="android.permission.WRITE_CONTACTS" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    <uses-permission android:name="android.permission.FLASHLIGHT"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS "/>

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false" android:requestLegacyExternalStorage="true"
      android:theme="@style/AppTheme">

        <!-- react-native-background-geolocation licence -->
        <meta-data android:name="com.transistorsoft.locationmanager.license" android:value="6e0b13cf6c80c6a541fb5b8797215cf82080fb58e658d32c72ec2f1a523ee9a0" />

      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
        android:launchMode="singleTask"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

                  <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <!-- <data android:scheme="http" /> -->
        <data android:scheme="https" android:host="login.sensights.ai" />
         <!-- <data android:scheme="app" android:host="open.my.app" /> -->
    </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />

      <!-- GOOGLE API -->
      <meta-data android:name="com.google.android.geo.API_KEY" android:value="AIzaSyCM3R8cZQht5FIFqWEoEGiJNiquht_CVUU"/>

      <!-- <activity android:name=".bluetooth.DeviceScanActivity" android:label="@string/app_name" android:theme="@style/Theme.Transparent" />
      <activity android:name=".bluetooth.DeviceControlActivity" android:theme="@style/Theme.Transparent" />
      <service android:name=".bluetooth.BluetoothLeService" android:enabled="true"/> -->

        <!-- Pushy Declarations -->
        <!-- Pushy Notification Receiver -->
        <!-- Do not modify - internal BroadcastReceiver that forwards notifications to the internal notification service-->
        <receiver android:name="me.pushy.sdk.react.receivers.PushReceiver" android:exported="false">
            <intent-filter>
                <!-- Do not modify this -->
                <action android:name="pushy.me" />
            </intent-filter>
        </receiver>

        <!-- Pushy Update Receiver -->
        <!-- Do not modify - internal BroadcastReceiver that restarts the listener service -->
        <receiver android:name="me.pushy.sdk.receivers.PushyUpdateReceiver" android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
            </intent-filter>
        </receiver>

        <!-- Pushy Boot Receiver -->
        <!-- Do not modify - internal BroadcastReceiver that restarts the listener service -->
        <receiver android:name="me.pushy.sdk.receivers.PushyBootReceiver" android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

        <!-- Pushy Socket Service -->
        <!-- Do not modify - internal service -->
        <service android:name="me.pushy.sdk.services.PushySocketService" android:stopWithTask="false" />

        <!-- Pushy Job Service (added in Pushy SDK 1.0.35) -->
        <!-- Do not modify - internal service -->
        <service android:name="me.pushy.sdk.services.PushyJobService"
            android:permission="android.permission.BIND_JOB_SERVICE"
            android:stopWithTask="false" />

        <!-- End Pushy Declarations -->

    </application>

</manifest>


text:
Q: How to use read data from computer using a pi pico running micropython I have looked everywhere on the internet, sadly i couldn't find anything. Is there anyway i could read data from my computer to the raspberry pi pico running micropython? Any help would be appreciated. I use pyserial to send and receive data on my computer.

A: I also had this issue and from this link I was able to figure it out. To read data from the usb port use "sys.stdin.buffer.read(8)".
Here is a short code that you can upload to the pico to do this.
import time
import sys

while True:
      print("hello")
      data = sys.stdin.buffer.read(8)
      # to convert to string use data = sys.stdin.buffer.read(8).decode("utf-8")
      print(data)

      time.sleep(1)

With this code it will wait until 8 bytes come in, until then it will idle. I'm sure there is a way around it, just haven't tried yet.
I used the Arduino IDE serial monitor to send data. Upload this code in Thonny (save it as main.py so it starts on power up), then disconnect the pico, plug it back in, and open the Arduino serial monitor. Send something like '12345678' and it should spit it back out.
EDIT:
The above code will idle until you send it data. To have the pico continue running if no data is sent, use the following (source):
import time
import sys
import select

while True:
   print("hello")
   res = select.select([sys.stdin], [], [], 0)
   data = ""
   while res[0]:
      data = data + sys.stdin.read(1)
      res = select.select([sys.stdin], [], [], 0)
   print(data, end = "")
   time.sleep(1)

And you can just use Thonny to send the data, you don't need the Arduino IDE.


text:
Q: Root class is not read by SASS, only those with ampersand are I have a sass/css class with an ampersand, this is used in conjunction with VueJS. What I was wondering is that the CSS attribute assigned on the ampersand is working but the root element itself isn't detected by the browser.
<style lang="scss" scoped>
.curved-input {
  border-radius: 5px;
  height: 50px;
  margin-right: 1rem;

  &__lg {
    width: 300px;
  }

  &__sm {
    width: 150px;
  }
}
</style>

Here's the explanation, the browser seem to detect the width: 300px or width: 150px but not the border-radius, height, margin-right.
<input name="city" class="curved-input__lg" type="text" placeholder="Palau Ujong, Singapore"/>

The textbox width changed but other attributes are not read by the browser when you look at them on the browser tools. Am I missing something here?
My goal is not to code it as class="curved-input curved-input__lg but rather only use curved-input__lg or curved-input__sm while inheriting the parent attributes (curved-input).

A: This is because you have to declare the curved-input class as well. So your class attribute will look like class="curved-input curved-input__lg".
If you'd write out your CSS in full you'll get something like this:
.curved-input {
   border-radius: 5px;
   height: 50px;
   margin-right: 1rem;
}

.curved-input__lg {
   width: 300px;
}

.curved-input__sm {
   width: 150px;
}

With this in mind you'll see that you have to add the class curved-input as well.

A: You could use @extend to avoid adding additional classes to your markup or (some) duplicate code, if that is your goal.
.curved-input {
  border-radius: 5px;
  height: 50px;
  margin-right: 1rem;
}

.curved-input {
  &__lg {
    @extend .curved-input;
    width: 300px;
  }

  &__sm {
    @extend .curved-input;
    width: 150px;
  }
}

Which would generate the following CSS
.curved-input,
.curved-input__sm,
.curved-input__lg {
  border-radius: 5px;
  height: 50px;
  margin-right: 1rem;
}

.curved-input__lg {
  width: 300px;
}
.curved-input__sm {
  width: 150px;
}

A: Well if you want to write it like that, try to change the first line to:
[class*="curved-input"]


text:
Q: access forbidden while accessing php application from other machine I am using easyphp5.3.6.0 to run the php application.
I have saved the php application folder in www directory.
now when I try to access it by giving 127.0.0.1 IP, it is working fine but when I try to run it with my actual IP address I get an error
"Access forbidden!
You don't have permission to access the requested object. It is either read-protected or not readable by the server. "
please assist me with the problem.

A: You are probably behind a router. You need to forward the port in your router's config page(which I guess is 80 that is the default port).
You can enter here they have information about port forwarding.
I also don't think you meant phpMyAdmin, as far as I know it's a mySQL manager


text:
Q: What file allows you to set the default language in Endless Space 2? I know I can change the language by going through steam properties but is there a way to do this in game or by editing a configuration file? If so please let me know how.
Thanks

A: It seems as though the only way to do this is via right clicking on the game in your steam library-> Properties-> languages.  You might need to restart stem from what some of the posts on the following link say.
https://steamcommunity.com/app/392110/discussions/0/1291816569119420375/

A: just change it in config.ini in game folder. Default should be Language=english, change it to any other supported by game

A:
Blockquote just change it in config.ini in game folder. Default should be Language=english, change it to any other supported by game
  Blockquote

File responsible for language is called "Steam_emu"


text:
Q: nacasha CIgniter-Datatables column styling $t->datatable('employees_table') // table's id
->column('First Name', 'first_name')
->column('Last Name', 'last_name')
->column('Age', 'age')
->column('Salary', 'title');

$t->datatable('employees_table')
->style(array(
    'class' => 'table table-bordered table-striped',
))
$t->init();

All I want to give a width and background etc to Age Column


text:
Q: Manually stop processes launched by mod_wsgi, and monitor how many processes are running I know it's not recommended to run a Bottle or Flask app on production with python myapp.py --port=80 because it's a development server only.
I think it's not recommended as well to run it with python myapp.py --port=5000 and link it to Apache with: RewriteEngine On, RewriteRule /(.*) http://localhost:5000/$1 [P,L] (or am I wrong?), because WSGI is preferred.
So I'm currently setting up Python app <-> mod_wsgi <-> Apache (without gunicorn or other tool to keep things simple).
Question: when using WSGI, I know it's Apache and mod_wsgi that will automatically start/stop enough processes running myapp.py when requests will come, but:

*

*how can I manually stop these processes?

*more generally, is there a way to monitor them / know how many processes started by mod_wsgi are currently still running? (one reason, among others, is to check if the processes terminate after a request or if they stay running)

Example:

*

*I made some changes in myapp.py, and I want to restart all processes running it, that have been launched by mod_wsgi  (Note: I know that mod_wsgi can watch changes on the source code, and relaunch, but this only works on changes made on the .wsgi file, not on the .py file. I already read that touch myapp.wsgi can be a solution for that, but more generally I'd like to be able to stop and restart manually)

*I want to temporarily stop the whole application myapp.py (all instances of it)
I don't want to use service apache2 stop for that because I also run other websites with Apache, not just this one (I have a few VirtualHosts). For the same reason (I run other websites with Apache, and some client might be downloading a 1 GB file at the same time), I don't want to do service apache2 restart that would have an effect on all websites using Apache.
I'm looking for a cleaner way than kill pid or SIGTERM, etc. (because I read it's not recommended to use signals in this case).
Note: I already read How to do graceful application shutdown from mod_wsgi, it helped, but here it's complementary questions, not a duplicate.

My current Python Bottle + Apache + mod_wsgi setup:

*

*Installation:
apt-get install libapache2-mod-wsgi
a2enmod wsgi      # might be done automatically by previous line, but just to be sure

*Apache config (source: Bottle doc; a more simple config can be found here):
<VirtualHost *:80>
  ServerName example.com
  WSGIDaemonProcess yourapp user=www-data group=www-data processes=5 threads=5
  WSGIScriptAlias / /home/www/wsgi_test/app.wsgi
  <Directory />
    Require all granted
  </Directory>
</VirtualHost>

There should be up to 5 processes, is that right? As stated before in the question, how to know how many are running, how to stop them?

*/home/www/wsgi_test/app.wsgi (source: Bottle doc)
import os
from bottle import route, template, default_app

os.chdir(os.path.dirname(__file__))

@route('/hello/<name>')
def index(name):
    return template('Hello {{name}}!', name=name)

application = default_app()

A: Taken partially from this question, add display-name to WSGIDaemonProcess so you can grab them using a command like:
ps aux | grep modwsgi

Add this to your configuration:
Define GROUPNAME modwsgi
WSGIDaemonProcess yourapp user=www-data group=www-data processes=5 threads=5 display-name=%{GROUPNAME}

Update
There are a couple of reasons why ps would not give you the DaemonProcess display-name.
As shown in the docs:

display-name=value Defines a different name to show for the daemon
  process when using the ps command to list processes. If the value is
  %{GROUP} then the name will be (wsgi:group) where group is replaced
  with the name of the daemon process group.
Note that only as many characters of the supplied value can be
  displayed as were originally taken up by argv0 of the executing
  process. Anything in excess of this will be truncated.
This feature may not work as described on all platforms. Typically it
  also requires a ps program with BSD heritage. Thus on some versions of
  Solaris UNIX the /usr/bin/ps program doesn't work, but /usr/ucb/ps
  does. Other programs which can display this value include htop.

You could:
Set a display-name of smaller length:
WSGIDaemonProcess yourapp user=www-data group=www-data processes=5 threads=5 display-name=wsws

And try to find them by:
ps aux | grep wsws

Or set it to %{GROUP} and filter using the name of the daemon process group (wsgi:group).

A: The way which processes are managed with mod_wsgi for each mode is described in:

*

*http://modwsgi.readthedocs.io/en/develop/user-guides/processes-and-threading.html
For embedded mode, where your WSGI application is run inside of the Apache child worker processes, Apache manages when processes are created and destroyed based on the Apache MPM settings. Because of how Apache manages the processes, they can be shutdown at any time if there is insufficient request throughput, or more processes could be created if request throughput increases. When running, the same process will handle many requests over time until it gets shutdown. In other words, Apache dynamically manages the number of processes.
Because of this dynamic process management, it is a bad idea to use embedded mode of mod_wsgi unless you know how to tune Apache properly and many other things as well. In short, never use embedded mode unless you have a good amount of experience with Apache and running Python applications with it. You can watch a video about why you wouldn't want to run in embedded mode at:

*

*https://www.youtube.com/watch?v=k6Erh7oHvns
There is also the blog post:

*

*http://blog.dscpl.com.au/2012/10/why-are-you-using-embedded-mode-of.html
So use daemon mode and verify that your configuration is correct and you are in fact using daemon mode by using the check in:

*

*http://modwsgi.readthedocs.io/en/develop/user-guides/checking-your-installation.html#embedded-or-daemon-mode
For daemon mode, the WSGI application runs in a separate set of managed processed. These are created at the start and will run until Apache is restarted, or reloading of the process is triggered for various reasons, including:

*

*The daemon process is sent a direct signal to shutdown by a user.

*The code of the application sends itself a signal.

*The WSGI script file is modified, which will trigger a shutdown so the WSGI application can be reloaded.

*A defined request timeout occurs due to stuck or long running request.

*A defined maximum number of requests has occurred.

*A defined inactivity timeout expires.

*A defined timer for periodic process restart expires.

*A startup timeout is defined and the WSGI application failed to load in that time.

In these cases, when the process is shutdown, it is replaced.
More details about the various timeout options and how the processes respond to signals can be found in:

*

*http://modwsgi.readthedocs.io/en/develop/configuration-directives/WSGIDaemonProcess.html
More details about source code reloading and touching of the WSGI script file can be found in:

*

*http://modwsgi.readthedocs.io/en/develop/user-guides/reloading-source-code.html
One item which is documented is how you can incorporate code which will look for any changes to Python code files used by your application. When a change occurs to any of the files, the process will be restarted by sending itself a signal. This should only be used for development and never in production.
If you are using mod_wsgi-express in development, which is preferable to hand configuring Apache yourself, you can use the --reload-on-changes option.
If sending a SIGTERM signal to the daemon process, there is a set shutdown sequence where it will wait a few seconds to wait for current requests to finish. If the requests don't finish, the process will be shutdown anyway. That period of time is dictated by the shutdown timeout. You shouldn't play with that value.
If sending a SIGUSR1 signal to the daemon process, by default it acts just like sending a SIGTERM signal. If however you specify the graceful timeout for shutdown, you can extend how long it will wait for current requests to finish. New requests will be accepting during that period. That graceful timeout also applies in other cases as well, such as maxmimum number of requests received, or timer for periodic restart triggered. If you need the timeout when using SIGUSR1 to be different to those cases, define the eviction timeout instead.
As to how to identify the daemon processes to be sent the signal, use the display-name of option WSGIDaemonProcess. Then use ps to identify the processes, or possibly use killall if it uses the modified process name on your platform. Send the daemon processes the SIGUSR1 signal if want more graceful shutdown and SIGTERM if want them to restart straight away.
If you want to track how long a daemon process has been running, you can use:
import mod_wsgi
metrics = mod_wsgi.process_metrics()

The metrics value will include output like the following for the process the call is made in:
{'active_requests': 1,
 'cpu_system_time': 0.009999999776482582,
 'cpu_user_time': 0.05000000074505806,
 'current_time': 1525047105.710778,
 'memory_max_rss': 11767808,
 'memory_rss': 11767808,
 'pid': 4774,
 'request_busy_time': 0.001851,
 'request_count': 2,
 'request_threads': 2,
 'restart_time': 1525047096.31548,
 'running_time': 9,
 'threads': [{'request_count': 2, 'thread_id': 1},
             {'request_count': 1, 'thread_id': 2}]}

If you just want to know how many processes/threads are used for the current daemon process group you can use:
mod_wsgi.process_group
mod_wsgi.application_group
mod_wsgi.maximum_processes
mod_wsgi.threads_per_process

to get details about the process group. The number of process is fixed at this time for daemon mode and the name maximum_processes is just to be consistent with what the name is in embedded mode.
If you need to run code on process shutdown, you should NOT try and define your own signal handlers. Do that and mod_wsgi will actually ignore them as they will interfere with normal operation of Apache and mod_wsgi. Instead, if you need to run code on process shutdown, use atexit.register(). Alternatively, you can subscribe to special events generated by mod_wsgi and trigger something off the process shutdown event.

A: Edit: a more simple WSGI config is given in my question of Python WSGI handler directly in Apache .htaccess, not in VirtualHost

Based on Evhz's answer, I made a simple test to check that the processes are still running:
Apache config:
<VirtualHost *:80>
  ServerName example.com
  <Directory />
    AllowOverride All
    Require all granted
  </Directory>
  WSGIScriptAlias / /home/www/wsgi_test/app.wsgi
  WSGIDaemonProcess yourapp user=www-data group=www-data processes=5 threads=5 display-name=testwsgi
</VirtualHost>

app.wsgi file:
import os, time
from bottle import route, template, default_app

os.chdir(os.path.dirname(__file__))

@route('/hello/<name>')
def index(name):
    global i
    i += 1
    return template('Hello {{name}}! request={{i}}, pid={{pid}}',
        name=name, i=i, pid=os.getpid())

i = 0
time.sleep(3)     # wait 3 seconds to make the client notice we launch a new process!

application = default_app()

Now access http://www.example.com/hello/you many times:

The initial time.sleep(3) will help, from the client browser, to see exactly when a new process is started, and the request counter i will allow to see how many requests have been served by each process.
The PIDs will correspond to those present in ps aux | grep testwsgi:

Also the time.sleep(3) will happen maximum 5 times (at the startup of each of the 5 processes), then the processes should run forever, until we restart/stop the server or modify the app.wsgi file (modifying it triggers a restart of the 5 processes, you can see new PIDs).

[I'll check that by letting my test run now, and access http://www.example.com/hello/you in 2 days to see if it's still a previously-launched process or a new one!]
Edit: the next day, the same processes were still up and running. Now, two days after, when reloading the same URL, I noticed new processes were created... (Is there a time after which a process with no request dies?)


text:
Q: Using list comprehension to get the words with multiple (3) vowels in python Here is my question
fruits = ['mango', 'kiwi', 'strawberry', 'guava', 'pineapple', 'mandarin orange']

# Use a list comprehension to make a variable named fruits_with_more_than_two_vowels. Hint: You'll need a way to check if something is a vowel.

Can I do it in list comprehension alone?

A: You can use a Regular Expression pattern to filter out the consonants.
import re

fruits = ["mango", "kiwi", "strawberry", "guava", "pineapple", "mandarin orange"]
results = [i for i in fruits if len(re.sub(r"[^aeiouAEIOU]", "", i)) > 2]

The above code yields the following output.
>>> results
["guava", "pineapple", "mandarin orange"]

A: def vowels_check(word):
    vowels = 'aeiouAEIOU'
    count = 0
    for vowel in vowels:
        count += word.count(vowel)
    if count > 2: return True
    return False

fruits = ['mango', 'kiwi', 'strawberry', 'guava', 'pineapple', 'mandarin orange']
fruits_with_more_than_two_vowels = [fruit for fruit in fruits if vowels_check(fruit)]


text:
Q: Css Conflict when using npm run build in NextJs I am trying to turn a html/css template to NExtJS App , the problem is that the app is multi-lang So i have two Css file one for Rtl and other for ltr So i do the folowing:
if(router.locale==='ar'){

    require('../styles/Style.rtl.css')
  }else{

    require('../styles/Style.css')
  }

the above Code work fine when I use npm run dev .... but When i use npm run build i got some Conflicts because the two Css file are using same classNames and Webpack combine the two file in one generated css file.
So is there any solution for this or other way to import Css file depending on the Current Lang


text:
Q: Is SplFixedArray implemented in C/C++ under the hood? I'm not very familiar with the source code behind the entity we know as PHP, so I don't know whether the SPL library in general and SplFixedArray in particular are implemented in C/C++. Would anyone have the information?

A: Here you´ll find a link to a "spl_fixedarray.c" file:
http://git.php.net/?p=php-src.git;a=tree;f=ext/spl
=> It is C


text:
Q: How to calculate $\frac{d}{dt}|_{t=0}\langle dR_{x_t(e)} U, dR_{x_t(e)} V \rangle$? I meet this question when I read the 41th page of do Carmo's Riemannian Geometry (as pictures below). I don't know how to deal the red line. What I try :
assume $u_\delta$ is flow of $U$, then
$$
\frac{d}{dt}|_{t=0}  \left[(dR_{x_t(e)})_p U_p \right]
=\frac{d}{dt}|_{t=0} \left[\frac{d}{d\delta}|_{\delta=0}  ~u_\delta(p) x_t(e)
\right ]
=U_pX_e
$$
obviously, $U_p X_e$ is unmeaning. And even I can get $UX$, I still can't get the red line.  I am not familiar with Lie group. I really hope a detailed answer.  Thanks very much.

A: In my old answer, I misinterpreted the text by quite a bit. The following is a somewhat late attempt to fix that, so that any future readers are not confused.

The significance of bilinearity of $\langle \,, \, \rangle$ is that the following "product rule" holds:
$$
\left.\frac{d}{dt}\right|_{t=0}\langle dR_{x_t(e)}U, dR_{x_t(e)}V\rangle = \left\langle \left.\frac{d}{dt}\right|_{t=0}dR_{x_t(e)}U, dR_{x_0(e)}V \right\rangle + \left\langle dR_{x_0(e)}U, \left.\frac{d}{dt}\right|_{t=0}dR_{x_t(e)}V \right\rangle,
$$
where $dR_{x_t(e)}$ on vector fields is defined on page 27. You prove this identity just like you would the first-year calculus product rule, but with the product replaced by the bilinear form $\langle\,,\,\rangle$. (A similar identity holds more generally for bilinear forms on arbitrary vector spaces.)
Since $x_0(e) = e$, the map $R_{x_0(e)}$ is simply the identity, which implies that $dR_{x_0(e)}U=U$ and $dR_{x_0(e)}V=V$. do Carmo proves that
$$
\left.\frac{d}{dt}\right|_{t=0}dR_{x_t(e)}U = [U, X],
$$
and similarly for $[V, X]$, so the first displayed expression in this answer simplifies to
$$
\left.\frac{d}{dt}\right|_{t=0}\langle dR_{x_t(e)}U, dR_{x_t(e)}V\rangle = \langle [U, X], V \rangle + \langle U, [V, X]\rangle.
$$
Since $\langle dR_{x_t(e)}U, dR_{x_t(e)}V\rangle$ equals $\langle U, V\rangle$, which is independent of $t$, it vanishes when you take the derivative with respect to $t$. The above expression thus implies
$$
0 = \langle [U, X], V \rangle + \langle U, [V, X] \rangle,
$$
which is what you wanted to prove.


text:
Q: How to clear data of ViewModel in MVVM Light xamrin?
I am working on Xamrin Form right now. I have problem with clear data of ViewModel.

When I logout and login with different user, it shows me data of previous user because the value of UserProfileViewModel doesn't get clear.
When user logout, I want to clear user data from UserProfileViewModel class file. Currently I do this manually when user click on logout. I want any default method like dispose to clear all class member.
I have tried to inherit IDisposable interface with this.Dispose(); but that also didn't work.
I have also tried with default constructor as following but it throws error of
`System.TypeInitializationException`

on this line in app.xaml.cs: public static ViewModelLocator Locator => _locator ?? (_locator = new ViewModelLocator());
public UserProfileViewModel()
{
    //initialize all class member
}

In given code, you can see that on Logout call, I call method
`ClearProfileData` of `UserProfileViewModel`
which set default(clear)

data. It is manually. I want to clear data when user logout.

View Model Logout Page

 [ImplementPropertyChanged]
    public class LogoutViewModel : ViewModelBase
    {
        public LogoutViewModel(INavigationService nService, CurrentUserContext uContext, INotificationService inService)
        {
            //initialize all class member
            private void Logout()
            {
                //call method of UserProfileViewModel
                App.Locator.UserProfile.ClearProfileData();
                //code for logout
            }
        }
    }

User Profile View Model

    [ImplementPropertyChanged]
    public class UserProfileViewModel : ViewModelBase
    {
        public UserProfileViewModel(INavigationService nService, CurrentUserContext uContext, INotificationService inService)
        {
            //initialize all class member
        }

        //Is there any other way to clear the data rather manually?
        public void ClearProfileData()
        {
            FirstName = LastName = UserName = string.Empty;
        }
    }

ViewModel Locator

    public class ViewModelLocator
    {
        static ViewModelLocator()
        {
            MySol.Default.Register<UserProfileViewModel>();
        }

        public UserProfileViewModel UserProfile => ServiceLocator.Current.GetInstance<UserProfileViewModel>();
    }

A: Firstly there is no need to cleanup these kinds of primitive data types, the gc will do that for you.
However if you use Messages or any other Strong Reference for that matter you  WILL have to Unsubscribe from them otherwise your viewmodal will hang around in memory and will never go out of scope

The garbage collector cannot collect an object in use by an
  application while the application's code can reach that object. The
  application is said to have a strong reference to the object.

With Xamarin it really depends how you are coupling your View to Viewmodals to determine which approach you might take to cleanup your viewmodals.
As it turns out MVVM Light ViewModelBase implements an ICleanup interface which has an overridable Cleanup method for you.
ViewModelBase.Cleanup Method

To cleanup additional resources, override this method, clean up and
  then call base.Cleanup().

public virtual void Cleanup()
{
    // clean up your subs and stuff here
    MessengerInstance.Unregister(this);
}

Now your just left with where to call ViewModelBase.Cleanup
You can just call it when your View Closes, if you get a reference to the DataContext (I.e ViewModalBase) on the DataContextChanged Event
Or you can wire up a BaseView that plumbs this for you, or you can implement your own NagigationService which calls Cleanup on Pop. It really does depend on who is creating your views and viewmodels and how you are coupling them


text:
Q: How to return NAs for missing combinations while using group by in data.table I have a data.table like this
library(data.table)
tt1 <- structure(list(start = c(3, 4, 4, 4, 22, 4, 16),
                      end = c(5, 40,40, 40, 25, 40, 18),
                      u = c(1L, 2L, 2L, 2L, 3L, 2L, 4L),
                      duration = c(2, 36, 36, 36, 3, 36, 2),
                      i.start = c(3, 3, 29, 20, 20, 14, 14),
                      i.end = c(5, 5, 31, 22, 22, 16, 16),
                      q = c(7L, 7L, 8L, 9L, 1L, 10L, 10L),
                      i.duration = c(2, 2, 2, 2, 2, 2, 2)), row.names = c(NA,-7L),
                 class = c("data.table", "data.frame"),
                 .Names = c("start", "end", "u", "duration", "i.start", "i.end", "q", "i.duration"))

setDT(tt1)
> tt1
   start end u duration i.start i.end  q i.duration
1:     3   5 1        2       3     5  7          2
2:     4  40 2       36       3     5  7          2
3:     4  40 2       36      29    31  8          2
4:     4  40 2       36      20    22  9          2
5:    22  25 3        3      20    22  1          2
6:     4  40 2       36      14    16 10          2
7:    16  18 4        2      14    16 10          2

I would like to filter records whose "duration" <=2 and group elements by each combination of (i.start,i.end). I was able to do this by,
> tt1[duration<=2, mean(duration), by =c("i.start","i.end"),nomatch=NA]
   i.start i.end V1
1:       3     5  2
2:      14    16  2

However, I would also like NA's to be returned for the (i.start,i.end) groups whose duration>2 along with the previous result.
   i.start i.end V1
1:       3     5  2
2:      14    16  2
3:      29    31  NA
4:      20    22  NA

How can this be done?

A: If you want to keep all the groups then you probably will have to subset within each group rather like you are doing right now (in the ith expression).
Could do either
tt1[, mean(duration[duration <= 2]), by = .(i.start, i.end)]
#    i.start i.end  V1
# 1:       3     5   2
# 2:      29    31 NaN
# 3:      20    22 NaN
# 4:      14    16   2

Or combine it with an if/else statement
tt1[, if(any(duration <= 2)) mean(duration[duration <= 2]) else NA_real_, by = .(i.start, i.end)]
#    i.start i.end V1
# 1:       3     5  2
# 2:      29    31 NA
# 3:      20    22 NA
# 4:      14    16  2

Another (strange) way to achieve this, is to first calculate only the means that you need and then join back with all the possible groups
res <- tt1[duration <= 2, mean(duration), keyby = .(i.start, i.end)]
res[unique(tt1[, .(i.start, i.end)]), on = .(i.start, i.end)]
#    i.start i.end V1
# 1:       3     5  2
# 2:      29    31 NA
# 3:      20    22 NA
# 4:      14    16  2

Or similarly
tt1[duration <= 2][unique(tt1[, .(i.start, i.end)]), on=.(i.start, i.end),
  mean(duration), by=.EACHI]
#    i.start i.end V1
# 1:       3     5  2
# 2:      29    31 NA
# 3:      20    22 NA
# 4:      14    16  2


text:
Q: Formatting text in Description field? Is there a way to format any of the text in the 'Description' field of the DESCRIPTION file in an R package?  I'd like to add emphasize (e.g. italicize) a few of the words; but, it's not critical, so I don't want to change the encoding.
Perhaps this is impossible, but I can't find any mention of it besides briefly in the Extensions manual.  Anyway, here's what has been unsuccessful for me...
bold:

*

*Surrounding text with **

*Text inside \textbf{} (which shows up as \{}textbf{})

italics:

*

*Surrounding text with __ (double underscore)

*Text inside \textit{} (which also shows up as \{}textit{})


text:
Q: "password authentication failed for user" after push to Heroku I followed the heroku documentation to install a django app and at first it worked fine. After a day I pushed some changes to the server. After that, I was not able to access the app at all: FATAL:  password authentication failed for user "drjstoymyqyarj"
I can not even sync the db anymore:
$ heroku run python manage.py syncdb
Running `python manage.py syncdb` attached to terminal... up, run.1
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
    utility.execute()
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/base.py", line 196, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/base.py", line 232, in execute
    output = self.handle(*args, **options)
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/base.py", line 371, in handle
    return self.handle_noargs(**options)
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 57, in handle_noargs
    cursor = connection.cursor()
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/db/backends/__init__.py", line 306, in cursor
    cursor = self.make_debug_cursor(self._cursor())
  File "/app/.heroku/venv/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 177, in _cursor
    self.connection = Database.connect(**conn_params)
  File "/app/.heroku/venv/lib/python2.7/site-packages/psycopg2/__init__.py", line 179, in connect
    connection_factory=connection_factory, async=async)
psycopg2.OperationalError: FATAL:  password authentication failed for user "drjstoymyqyarj"
FATAL:  password authentication failed for user "drjstoymyqyarj"

I have used the database settings recommended in the heroku doc:
import dj_database_url
DATABASES = {'default': dj_database_url.config(default='postgres://localhost')}

When I check the logs after pushing code to the server, there is a suspicious Process exited with status 143 that I did not notice before. Maybe that has something to do with it?
$ heroku logs
heroku[web.1]: State changed from up to starting
heroku[web.1]: Stopping all processes with SIGTERM
heroku[web.1]: Starting process with command `python ./manage.py runserver 0.0.0.0:41048 --noreload`
app[web.1]: Validating models...
app[web.1]:
app[web.1]: 0 errors found
app[web.1]: Django version 1.4, using settings 'ClosetList.settings'
app[web.1]: Development server is running at http://0.0.0.0:41048/
app[web.1]: Quit the server with CONTROL-C.
heroku[web.1]: Process exited with status 143
heroku[web.1]: State changed from starting to up

[Edit]
Same error msg with heroku pg:psql. I am however able to open a Django shell with heroku run python manage.py shell, but I can not access any data from within it (same error of course).
[/Edit]
any help with this is appreciated.

A: Run
heroku config

and see if there are more than 2 heroku dbs configured and also see if DATABASE_URL point to your configured DB. If not, then you can promote your db to default DATABASE_URL by running:
heroku pg:promote HEROKU_POSTGRESQL_GREEN

Where HEROKU_POSTGRESQL_GREEN is your database name, you will see HEROKU_POSTGRESQL_GREEN_URL in your config.
Once your configured database is promoted to default database, you are ready to go.


text:
Q: There is a hole in my ground in Terraria that keeps reappearing! Okay so I made a new world and I started building a house and making the land flat. I then decided to leave my new world to go back to my old world to collect stuff to bring over and I did not have enough inventory room so I dropped/threw a whole bunch of my stuff on the ground (I did not place it like you are supposed to). Anyways when I left my new world and got my stuff from my old world I returned and where I dropped/threw all my stuff was now an empty shallow hole in the ground in the middle of my house.
Now every time I patch it up and exit the game and go to play again later the hole is back and my patchwork has disappeared. What went wrong? I really don't want to tear down my house that I have already built so much of.

A: The problem was that, if you accidentally build over your spawn point, it will destroy any blocks in the way when you respawn. To solve this, either bind your spawn point to a bed somewhere, or just leave that hole there for the time being.

A: Another solution is to use 3rd party software to move the spawn point.  I did this for a map I turned into a server so new players/characters wouldn't wreck my house.
One program you can use is TEdit. In the default view the tool you need is the button 3rd from the bottom on the left side (vertical) tool bar.


text:
Q: google sheet overwrite existing database I am new to this custom script and I have found it difficult to find a script.
When I hit the "edit" button it will automatically save to the "ID Database", but it just creates a new line, not overwriting the existing database file.
Really need a script to replace the existing data with the newest data, when I click the "update" button.
To overwrite the  existing data, I have attached the link to the sheet >> https://docs.google.com/spreadsheets/d/1Q1orpHAJJvTUu3b0JoehR-9iOzDtvsPu457QzPDJ58A/edit#gid=0
Thanks in advance ^^
Kat

A: On your Edit save Id.gs file you are indeed setting the values to the last row:
datasheet.getRange(datasheet.getLastRow()+1, 1, 1, 5).setValues(values);

To update the values from the row you chose you have to search if the ID of the ID entry sheet is = to the ID of the database and then modify that row.
You have to change this:
var values = [[formSS.getRange("D2").getValue(),
                 formSS.getRange("D4").getValue(),
                 formSS.getRange("D5").getValue(),
                 formSS.getRange("D6").getValue(),
                 formSS.getRange("D7").getValue(),]];

  datasheet.getRange(datasheet.getLastRow()+1, 1, 1, 5).setValues(values);

to this:
var databaseValues = datasheet.getDataRange().getValues();

  for (var i = 0; i < databaseValues.length; i++) {
    if (databaseValues[i][0] == formSS.getRange("D2").getValue()) {
      datasheet.getRange(i+1, 2).setValue(formSS.getRange("D4").getValue());
      datasheet.getRange(i+1, 3).setValue(formSS.getRange("D5").getValue());
      datasheet.getRange(i+1, 4).setValue(formSS.getRange("D6").getValue());
      datasheet.getRange(i+1, 5).setValue(formSS.getRange("D7").getValue());
      break;
    }
  }

Hope it helps!


text:
Q: GraphQL GET response time is slow when comparing to RESTful I wanted to test the response times of a GraphQL endpoint, and a RESTful endpoint as I haven't ever used GraphQL before, and I am about to use it in my next Laravel project.
So I am using Lighthouse PHP package to serve a GraphQL endpoint from my Laravel app, and also I have created a RESTful endpoint.
Both endpoints(GraphQL and RESTful) are intended to get all Users(250 users) from my local Database.
So based on the test what I have noticed here is that, when I tested this both endpoints on Postman, the RESTful endpoint response is faster than GraphQL endpoint.
Can I know why GraphQL endpoint's response takes more time than RESTful while both endpoints are getting same data?
GraphQL endpoint result for GET request (response time: 88ms)

GraphQL endpoint result for POST request (response time: 88ms)

RESTful endpoint result (response time: 44ms)

A: There's no such thing as a free lunch.
GraphQL offers a lot of useful features, but those same features invariably incur some overhead. While a REST endpoint can effectively pull data from some source and regurgitate it back to the client, even for a relatively small dataset, GraphQL will have to do some additional processing to resolve and validate each individual field in the response. Not to mention the processing required to parse and validate the request itself. And this overhead only gets bigger with the size of the data returned.
If you were to introduce additional features to your REST endpoint (request and response validation, support for partial responses, ability to alias individual response fields, etc.) that mirrored GraphQL, you would see the performance gap between the two shrink. Even then, though, it's still somewhat of an apples and oranges comparison, since a GraphQL service will go through certain motions simply because that's what the spec says to do.

A: TLDR: Your REST example is simple and less complicated
In Lighthouse it is creating a AST for parsing the graphql request and your schema. It then afterwards passes all the directives and so on to figure out what you are trying to do. It also has to validate your query, to see if you can actually run it on the schema.
Depending on how you defined it in your application, there is a lot of steps it is passing through. However this can be reduced by multiple different ways, the parsing of your graphql schema can be cached, you could cache the result, use deferred fields (prob. wont speed up this example). You can read more about this in the performance section of the docs.
You are not specifying how your REST is setup, if you are using some kind of REST standard where it has to parse the data also. If you add more features, there is more code to run through, hence higher load speed.

A: As of Lighthouse v4, we have made significant performance increases by lazy-loading the minimally required fields and types from the schema. That turns out to bring about a 3x to 10x performance increase, depending on the size of your schema.
You probably still won't beat a single REST endpoint for such a simple query. Lighthouse will begin to shine on more heavily nested queries that join across multiple relationships.

A: Try enabling opcache on the server. This decreased my gql response time from 200ms to 20ms


text:
Q: Draw D3.js graph inside dynamically added div I have this (probably weird) setup where I'm ajax'ing a template of sorts into a section of my page, and then trying to draw a chart with D3.js inside one of the elements of that template.
Weirdly, sometimes it renders, others it doesn't, complaining about what I figure out must be the element which holds the chart not being rendered at that moment, as it's coming from an ajax call.
How can I overcome this? I've been reading about jQuery's when() and then() but I can't seem to grasp how it might (if at all) help me in my case.
This is a (simpler) version of my code:
$.get("/url/to/my/template", function(templateData){
    // this element is already in the page
    $("#elementInThePage").html(templateData);
    // this function draws the D3 chart
    buildChart();
});

function buildChart(){
    // this element comes in the template
    // sometimes it's already available, other times it isn't
    // and obviously d3 complains about it not being there
    var element = d3.select("#elementInTemplate");
    // do more stuff (...)
}

To sum it up, how to be sure I only call buildChart() when #elementInTemplate has rendered?
EDIT: I already tried chaining .done() to my $.get, but exactly the same thing happens.
EDIT2: I think I mis-explained my problem. D3.js doesn't complain about it not being there. What actually happens is that it is drawing the chart conditionally in regard to the size (WxH) of the element in the template, and because that element still hasn't rendered, it borks up the chart.
EDIT3: Another (relevant, I think), note: in buildChart(), D3.js depends of the dimensions of the template's element. So, if I
console.log($("#elementInTemplate").width()+" x "+$("#elementInTemplate").height());

If it fails, I get 234 x 0. If it works I get 234 x 456.


text:
Q: Boolean column in Microsoft Access and filtering data using linq [Apologies for long question but I thought it would be clearer for others to answer]
I have a Microsoft Access database and it contains a table "Customers" with following columns:

*

*ID (auto number)

*Name (Text)

*Active (yes/no)

I created the database table class in C# as below:
[Table (Name = "Products")]
public class Product
{
    [Column (IsPrimaryKey = true, Name = "ProductID")]
    public int ID;

    [Column (Name = "ProductName")]
    public string Name;

    [Column (Name = "Active")]
    public bool Active;
}

And I am using following code snippet to get the products which are active:
using (var con = new OleDbConnection
      (@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\LearnLinq.accdb")) {
    var db = new DataContext (con);
    var productTable = db.GetTable<Product> ();
    var allProducts = from p in productTable
                      where p.Active
                      select p;

    foreach (var p in allProducts) {
        AddLine ("ID: " + p.ID.ToString () +
            ", Name: " + p.Name +
            ", Active: " + p.Active.ToString ());
    }
}

The problem is that above query results in "NO RECORDS". I tried to analysed the SQL generated and it says something like below:
SELECT [t0].[ProductID] AS [ID], [t0].[ProductName] AS [Name], [t0].[Active]
FROM [Products] AS [t0]
WHERE [t0].[Active] = 1

Any clues why it should be happening?

A: Try just using the OleDbCommand object with the generated SQL and iterating through what is returned using OleDbDataReader.
Then try with this SQL string
SELECT [t0].[ProductID] AS [ID], [t0].[ProductName] AS [Name], [t0].[Active]
FROM
[Products] AS [t0]
WHERE [t0].[Active] = YES

I believe it may have something to do with the underlying values used for the Yes/No datatype in Jet database.

Yes/No
A Logical field can be
  displayed as Yes/No, True/False, or
  On/Off. In code, use the constants
  True and False, equivalent to -1 and 0
  respectively.

Have a look at BLS site under Developer Community- There is source code for Linq to Access solution

A: As Russ noted it looks like a problem with different representation of booleans.
Try changing the "Where p.active" into "Where p.active <> 0"

A: Look and see what the productTable.active field contain the Access database,
I bet it's probably not 0 or 1. It might be -1.
What you might want is something like this:
var allProducts = from p in productTable
                  where p.Active = -1
                  select p;

Update:
(
O.P. tells me this won't work in linq/C#; but there must be a way to do the equivalent of the following SQL in linq
Select *
from Customers
where active = -1

)
Failing that (e.g., it shows up as yes/no | true/false) try reading the value of Active in and output it through a msgbox just to see what it really contains.


text:
Q: Foreach array return last value I'm learning OOP and I whould create a list of objects in an array, but my code return the last array
I have search here, but haven't found a solution or idea how to do this.
Excepct
        "MerchantDefinedFields":[
        {
           "Id":2,
           "Value":"email@test.com"
        },
        {
           "Id":4,
           "Value":"Web"
        },
        {
           "Id":9,
           "Value":"NAO"
        },
        {
           "Id":83,
           "Value":"Field"
        },
        {
           "Id":84,
           "Value":"Only"
        }
     ]

My code
            $MDDs = array(
                array("Id" => 2, "Value" => "email@test.com"),
                array("Id" => 4, "Value" => "Web"),
                array("Id" => 9, "Value" => "NO"),
                array("Id" => 83, "Value" => "Field"),
                array("Id" => 84, "Value" => "Only")
            );

            foreach($MDDs as $MDD){
                $abac = array("Id" => $MDD['Id'], "Value" => $MDD['Value']);
            }

Result
    Array
(
    [Id] => 84
    [Value] => PROPRIO
)

A: Your foreach() is re-setting $abac every time it goes through the loop. So on the last time it runs, it will set the variable to the last item in your array.
Instead of setting the variable each time, try adding the key->value to an array (or something like that, depending on what you want):
$abac = [];
foreach($MDDs as $MDD){
    $abac[] = array("Id" => $MDD['Id'], "Value" => $MDD['Value']);
}

It's hard to create the exact right answer for you, since it's unclear what you're trying to accomplish, but this should at least point you in the right direction.

A: For simple answer :- You don't need foreach loop to get the desired result
you can simply use built-in php function to convert your array to JSON
$abac = json_encode ( $MDDs);
Now coming to your problem :-
you are re-assigning the $abac variable in loop instead of adding values to it like .
$abac = [];
foreach($MDDs as $MDD){
    $abac[] = array("Id" => $MDD['Id'], "Value" => $MDD['Value']);
}

A: The best way to do it is to declare the $abac outside of the foreach and then use the array_push method like this:
$abac = array();

foreach($MDDs as $MDD)
{
    array_push($abac, array("Id" => $MDD['Id'], "Value" => $MDD['Value']));
}
print_r($abac);


text:
Q: Is there way to get users public details in google-plus using nodejs I'm trying to get users public details in google-plus. I have only users public URL. Is there way to get users public details?

A: You should use scopes in your request, you can find info here https://developers.google.com/+/web/api/rest/oauth#authorization-scopes
Or if you use passport.js you can try somethink like this:
passport.authenticate('google',  {
   scope:[ 'email', 'profile'],
   failureRedirect: '/'
 })


text:
Q: how to read pdf file and load it into sql server ( with pdf is image) I have found this for how to read normal pdf
Extract Data from .PDF files
but my pdfs are scanned images.
how cna I read them in c# asp.net?


text:
Q: javascript syntax error setting property of jquery datatable I am using the jquery data table like this:
$.fn.tkDataTable = function(){
        "order": [[ 7, 'asc' ]]

        if (! this.length) return;

        if (typeof $.fn.dataTable != 'undefined') {

            this.dataTable();

        }

    };

I get the error:

Uncaught SyntaxError: Unexpected token :

I get this on the line with "order".  How can I correctly set this attribute without the syntax error?

A: You rarely call datatable without an options object
I suspect what you want is something like
$.fn.tkDataTable = function(){
    var opts = {
       "order": [[ 7, 'asc' ]],
       //...  other initialization properties
    };

    if (! this.length) return;

    if (typeof $.fn.dataTable != 'undefined') {
        // pass options to plugin
        this.dataTable(opts);

    }
}