text:
Q: How to make CSS grid container keep responsive square size? I want grid container to maintain square shape. So when screen is resized, it will get bigger or smaller, but it's height will be always same as it's width. I want to place 3 images inside, with top one taking up two columns, and bottom ones are square taking one column each.

HTML:

SASS:
.container: {
  background: #fff;
  max-width: 600px;
  padding: 10px;
}

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  gap: 10px;

  & > img:first-child {
    grid-column: 1 / span 2;
    grid-row: 1;
  }

  img {
    width: 100%;
    background-color: #000;
    object-fit: cover;
  }
}

I tried adding pseudo element to grid to maintain square ratio, only to find out that it won't work for grid. I tried giving img height: 100% but it made the too long.
I found some questions about how to keep images inside square, but non of them was about how to keep grid container square and prevent from being stretched out by children.

A: I'd do the following:

*

*Make the grid width and height responsively sized - for this use this method (.container and &::after pseudo element)

*Make the grid itself follow the square width and height of the container (.grid-wrapper)

*Use a container for the images, so that the containers resize inside the grid (1st row = 2 col wide, 2nd row = 2x1 col) (.grid-box)

*Use absolute positioned images in the divs, so they actually cover the divs

HTML code:

SASS code:
$-gutter: 10px;
$-max-width: 600px;

* {
  box-sizing: border-box;
}

.container {
  position: relative;
  max-width: $-max-width;
  width: 100%;
  background: #ffff00;

  &::after {
    content: "";
    display: block;
    padding-bottom: 100%;
  }
}

.grid-wrapper {
  position: absolute;
  width: 100%;
  height: 100%;
  padding: $-gutter;
}

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  gap: $-gutter;
  width: 100%;
  height: 100%;

  &-box {
    position: relative;
    width: 100%;
    height: 100%;

    &:first-child {
      grid-column: 1 / span 2;
    }
  }

  img {
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: #000000;
    object-fit: cover;
  }
}

Here is a Fiddle demo: https://jsfiddle.net/robertp/uLfj1swm/
And a screenshot of how this solution renders:


text:
Q: Xcode 9.2 doesn't allow to select/change team I have a few teams available for selection in Xcode 'Signing' section.
'Automatic signing' is on and I have one team selected by default when I open project.
Once I try to select another team from a list, my choice is reverted back to initial team. I can neither change team nor set it to 'None'.

I tried deleting all accounts and it results for 'Unknown Team' being selected, which is logical, however I still can not change it to None or to another account if I add one.

Additional details:

*

*I am using Xcode 9.2 and it's React Native project.

*This happens after I pull changes from repo where team has been set
by another developer.

*Another developer (commit owner) can not change his team to 'None' also.
So what are the reasons for that and how to change team?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to show ProgressDialog over only the Activity and not the containing TabHost? Currently when I show a ProgressDialog, it takes up the whole screen including the tabs, like this:

Is it possible for this to only cover the activity and leave the tabs functional? Ideally it would appear like this so that I could click the buttons to leave load a different activity instead of waiting for the current one to finish loading:

Is this possible? Is there another approach I should take to achieve this result?

A: Extend the progress dialog class where you do customisation
public class CustomProgressDialogClass extends ProgressDialog{
public CustomProgressDialogClass(Context context) {
    super(context, R.style.CustomDialogThemeForPorgressbar);
    // TODO Auto-generated constructor stub

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.progress_layout);
}

}
In layout progress_layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/progressbar_layout">

<RelativeLayout
   android:id="@+id/relativeLayout1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:gravity="center"
   android:background="@drawable/loader_bg"  >

   <ProgressBar
        android:id="@+id/progressbarlayout_progressbar"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"/>

In values folder create styles folder and paste this
<style name="CustomDialogThemeForPorgressbar" parent="@android:style/Theme.Dialog">
    <item name="android:windowBackground">@color/transparent</item>
    <item name="android:windowIsFloating">false</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:gravity">center</item>
</style>

Do the changes to windowIsFloating,gravity and windowNoTitle to show in tab host

A: I feel that using the ProgressDialog is not the most suitable choice in a scenario like this. It is the logic of the dialog to block the entire window to indicate the user that no action can be performed at this moment.
If you want to show progress for certain parts of the activity, you should be using a ProgressBar instead. If you want the look and feel to be like a progress dialog, then use can customize the ProgressBar (that looks like the progress dialog), and dynamically attach/remove or change visibility to show or hide it.
I guess you can also take a look at this: https://stackoverflow.com/a/18553879/827110
(I am assuming you are looking for a conceptual answer i.e to find the most suitable way to achieve such a behaviour)


text:
Q: How do you install a new debug-apk without manually uninstalling the old debug-apk with a mismatching signature? I have a hardware product with an application that the user is not able to exit. When there is a new update, the user is able to update to the newest version within the app. We release debug-apk's, not the signed ones.
I read that Android studio automatically signs debug-apk's. I have a new version of the app that I want to release, but the old apk's signature doesn't match the new apk signature. The users are not able to uninstall the app and reinstall the new one since they can not leave the app. I am not able to go around the world manually updating everyones product.
Question: What would be the best way to uninstall the old apk and install the new one without the user having to manually uninstall and install the new apk.
Suggestions: Is there a way to find out the old apk's automatically generated signature and change the new one to match it? Or is there a way to create a service that can uninstall the old apk and install the new one?

A: I could just copy the debug.keystore file from the original computer where the older versions of the app were made and replace my debug.keystore file in the users\yourname.android location on my computer. Then I had to restart android studio and everything worked normally again.

A: You can use that debug-key for signing your new APK and release it.
And your user can update to new one.
Actually, you don't sign the new app and just build an APK with debug-key and release it.
with below code in your gradle:
signingConfigs {
     debug {
         storeFile file("debug.keystore")
     }
 }


text:
Q: How to use Google Text to Speech (python) in Ubuntu 20.04? Here is the screenshot of the errors which I am getting. Please help me! I have also installed mpg321 in my Ubuntu 20.04. It is working fine if I play music from terminal. Here, I am playing a song from terminal. I've tried to play hello.mp3 also(from gtts output) from terminal. It's saying hello world when I run from terminal but when I try run in Pycharm it shows errors. Please help me!!

A: Try this,
#pip install playsound
from playsound import playsound
playsound("fileName.mp3")

Hope this resolved your issue.


text:
Q: Flutter -- java.lang.RuntimeException: at com.google.firebase.firestore.util.AsyncQueue.lambda$panic$3 (AsyncQueue.java) Problem:
This is my output:
java.lang.RuntimeException:
  at com.google.firebase.firestore.util.AsyncQueue.lambda$panic$3 (AsyncQueue.java)
  at com.google.firebase.firestore.util.-$$Lambda$AsyncQueue$jx84dqgUsF4ojecSMurRqFLFD1Y.run (-.java)
  at android.os.Handler.handleCallback (Handler.java:873)
  at android.os.Handler.dispatchMessage (Handler.java:99)
  at android.os.Looper.loop (Looper.java:214)
  at android.app.ActivityThread.main (ActivityThread.java:7050)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:494)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:965)
Caused by: com.google.android.gms.tasks.RuntimeExecutionException:
  at com.google.android.gms.tasks.zzw.getResult (zzw.java)
  at com.google.firebase.firestore.remote.FirestoreChannel.lambda$runBidiStreamingRpc$0 (FirestoreChannel.java)
  at com.google.firebase.firestore.remote.FirestoreChannel.lambda$runBidiStreamingRpc$0$FirestoreChannel (FirestoreChannel.java)
  at com.google.firebase.firestore.remote.-$$Lambda$FirestoreChannel$ThFui-hvcsrVGYxlBtcTH5vVbvE.onComplete (-.java:6)
  at com.google.android.gms.tasks.zzi.run (zzi.java:21)
  at java.util.concurrent.Executors$RunnableAdapter.call (Executors.java:459)
  at java.util.concurrent.FutureTask.run (FutureTask.java:266)
  at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run (ScheduledThreadPoolExecutor.java:301)
  at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1167)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:641)
  at com.google.firebase.firestore.util.AsyncQueue$SynchronizedShutdownAwareExecutor$DelayedStartFactory.run (AsyncQueue.java:15)
  at java.lang.Thread.run (Thread.java:764)
Caused by: java.lang.RuntimeException:
  at com.google.android.gms.tasks.zzz.run (zzz.java:17)
  at com.google.firebase.firestore.util.ThrottledForwardingExecutor.lambda$execute$0 (ThrottledForwardingExecutor.java)
  at com.google.firebase.firestore.util.ThrottledForwardingExecutor.lambda$execute$0$ThrottledForwardingExecutor (ThrottledForwardingExecutor.java)
  at com.google.firebase.firestore.util.-$$Lambda$ThrottledForwardingExecutor$MfIJbVuxZtLwosAgPzPA-cU66Ko.run (-.java:4)
  at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1167)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:641)
  at java.lang.Thread.run (Thread.java:764)
Caused by: java.lang.AssertionError:
  at java.lang.Enum$1.create (Enum.java:272)
  at java.lang.Enum$1.create (Enum.java:262)
  at libcore.util.BasicLruCache.get (BasicLruCache.java:58)
  at java.lang.Enum.getSharedConstants (Enum.java:289)
  at java.lang.Class.getEnumConstantsShared (Class.java:2424)
  at java.util.EnumSet.getUniverse (EnumSet.java:407)
  at java.util.EnumSet.noneOf (EnumSet.java:109)
  at java.util.EnumSet.of (EnumSet.java:235)
  at io.grpc.okhttp.OkHttpChannelBuilder.<clinit> (OkHttpChannelBuilder.java:91)
  at io.grpc.okhttp.OkHttpChannelBuilder.forTarget (OkHttpChannelBuilder.java)
  at io.grpc.okhttp.OkHttpChannelProvider.builderForTarget (OkHttpChannelProvider.java)
  at io.grpc.okhttp.OkHttpChannelProvider.builderForTarget (OkHttpChannelProvider.java)
  at io.grpc.ManagedChannelBuilder.forTarget (ManagedChannelBuilder.java)
  at com.google.firebase.firestore.remote.GrpcCallProvider.initChannel (GrpcCallProvider.java)
  at com.google.firebase.firestore.remote.GrpcCallProvider.lambda$initChannelTask$6 (GrpcCallProvider.java)
  at com.google.firebase.firestore.remote.GrpcCallProvider.lambda$initChannelTask$6$GrpcCallProvider (GrpcCallProvider.java)
  at com.google.firebase.firestore.remote.-$$Lambda$GrpcCallProvider$SCD5iiibQ8l4haiO8ofSfE0wIJg.call (-.java:2)
  at com.google.android.gms.tasks.zzz.run (zzz.java:4)
  at com.google.firebase.firestore.util.ThrottledForwardingExecutor.lambda$execute$0 (ThrottledForwardingExecutor.java)
  at com.google.firebase.firestore.util.ThrottledForwardingExecutor.lambda$execute$0$ThrottledForwardingExecutor (ThrottledForwardingExecutor.java)
  at com.google.firebase.firestore.util.-$$Lambda$ThrottledForwardingExecutor$MfIJbVuxZtLwosAgPzPA-cU66Ko.run (-.java:4)
  at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1167)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:641)
  at java.lang.Thread.run (Thread.java:764)
Caused by: java.lang.NoSuchMethodException:
  at java.lang.Class.getMethod (Class.java:2069)
  at java.lang.Class.getDeclaredMethod (Class.java:2047)
  at java.lang.Enum$1.create (Enum.java:268)
  at java.lang.Enum$1.create (Enum.java:262)
  at libcore.util.BasicLruCache.get (BasicLruCache.java:58)
  at java.lang.Enum.getSharedConstants (Enum.java:289)
  at java.lang.Class.getEnumConstantsShared (Class.java:2424)
  at java.util.EnumSet.getUniverse (EnumSet.java:407)
  at java.util.EnumSet.noneOf (EnumSet.java:109)
  at java.util.EnumSet.of (EnumSet.java:235)
  at io.grpc.okhttp.OkHttpChannelBuilder.<clinit> (OkHttpChannelBuilder.java:91)
  at io.grpc.okhttp.OkHttpChannelBuilder.forTarget (OkHttpChannelBuilder.java)
  at io.grpc.okhttp.OkHttpChannelProvider.builderForTarget (OkHttpChannelProvider.java)
  at io.grpc.okhttp.OkHttpChannelProvider.builderForTarget (OkHttpChannelProvider.java)
  at io.grpc.ManagedChannelBuilder.forTarget (ManagedChannelBuilder.java)
  at com.google.firebase.firestore.remote.GrpcCallProvider.initChannel (GrpcCallProvider.java)
  at com.google.firebase.firestore.remote.GrpcCallProvider.lambda$initChannelTask$6 (GrpcCallProvider.java)
  at com.google.firebase.firestore.remote.GrpcCallProvider.lambda$initChannelTask$6$GrpcCallProvider (GrpcCallProvider.java)
  at com.google.firebase.firestore.remote.-$$Lambda$GrpcCallProvider$SCD5iiibQ8l4haiO8ofSfE0wIJg.call (-.java:2)
  at com.google.android.gms.tasks.zzz.run (zzz.java:4)
  at com.google.firebase.firestore.util.ThrottledForwardingExecutor.lambda$execute$0 (ThrottledForwardingExecutor.java)
  at com.google.firebase.firestore.util.ThrottledForwardingExecutor.lambda$execute$0$ThrottledForwardingExecutor (ThrottledForwardingExecutor.java)
  at com.google.firebase.firestore.util.-$$Lambda$ThrottledForwardingExecutor$MfIJbVuxZtLwosAgPzPA-cU66Ko.run (-.java:4)
  at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1167)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:641)
  at java.lang.Thread.run (Thread.java:764)

If I want to open the APK:

*

*the app opens perfectly

*the screen is black

*the app goes in the background

Notes:
If I run flutter run --release the app opens perfectly but it also shows an error:
Error: ADB exited with exit code 1
Performing Streamed Install

adb: failed to install C:\Users\Flutter\StudioProjects\nomadnet2\build\app\outputs\flutter-apk\app.apk: Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE: Package com.apps.social_circle signatures do not match previously installed version; ignoring!]

If I run: flutter run it works perfectly

I already tried:

*

*upgrade the packages

*install flutter SDK again

*update flutter

I also tried more things but I don't know them anymore

Please help me!

A: Try to delete your previus APK in

C:\Users\Flutter\StudioProjects\nomadnet2\build\app\outputs\flutter-apk\app.apk

Then use the command

flutter clean

And pub get your pubspect.yaml
and try to run the release version again

A: Delete your previously installed app in your phone or emulator, and run release again, probably is because a different sign key.

A: I have faced similar issue.
What I did was:-
Go to phone settings -> under apps section -> search for application name -> remove for all users.
This worked for my case, just try it out :)

A: the solution that worked for me is to register all packages from scratch

Hope it helps!


text:
Q: Flask-Firebase app on Heroku not getting env vars I'm having trouble making a Flask app that uses Firebase to run.
It seems like the Firebase Credentials api does not take the env vars even after they have been printed!
Heres de app code:
#!/usr/bin/env python3
""" PixelCode PDF generation application"""

from io import BytesIO
from os import environ
from flask import Flask, render_template_string, send_file, abort, jsonify
from flask_cors import CORS
from dotenv import load_dotenv
from weasyprint import HTML, CSS
import firebase_admin
from firebase_admin import firestore, credentials

load_dotenv()

APP = Flask(__name__)
CORS(APP)

ENV_KEYS = {
    "type": "service_account",
    "private_key_id": environ["FIREBASE_PRIVATE_KEY_ID"],
    "private_key": environ["FIREBASE_PRIVATE_KEY"],
    "client_email": environ["FIREBASE_CLIENT_EMAIL"],
    "client_id": environ["FIREBASE_CLIENT_ID"],
    "token_uri": environ["FIREBASE_TOKEN_URI"],
    "project_id": environ["FIREBASE_PROJECT_ID"],
}

print("ENV KEYS:", ENV_KEYS)

CREDENTIALS = credentials.Certificate(ENV_KEYS)

firebase_admin.initialize_app(
    CREDENTIALS, {'databaseURL': environ["FIREBASE_DATABASE_URL"]}
)

DB = firestore.client()

# Trimmed for brevity...

@APP.route('/', methods=["GET"])
def get_home():
    return render_template_string("
PixelCode GoDocu Services
")

if __name__ == '__main__':
    # This is used when running locally only. When deploying to Google App
    # Engine, a webserver process such as Gunicorn will serve the app. This
    # can be configured by adding an `entrypoint` to app.yaml.
    # Flask's development server will automatically serve static files in
    # the "static" directory. See:
    # http://flask.pocoo.org/docs/1.0/quickstart/#static-files. Once deployed,
    # App Engine itself will serve those files as configured in app.yaml.
    APP.run(host='0.0.0.0', port=environ.get('PORT', 8080), debug=True)

On dev/local environment (my pc) the app works fine using a .env file.
I have set up the env vars on heroku too.
When the app gets deployed, the print statement prints all the env vars fine.
After that, the app crashes with this error:

2019-12-04T14:11:33.349817+00:00 app[web.1]: [2019-12-04 14:11:33 +0000] [11] [ERROR] Exception in worker process
2019-12-04T14:11:33.349821+00:00 app[web.1]: Traceback (most recent call last):
2019-12-04T14:11:33.349824+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/firebase_admin/credentials.py", line 97, in init
2019-12-04T14:11:33.349826+00:00 app[web.1]:     json_data, scopes=_scopes)
2019-12-04T14:11:33.349829+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/google/oauth2/service_account.py", line 193, in from_service_account_info
2019-12-04T14:11:33.349832+00:00 app[web.1]:     info, require=['client_email', 'token_uri'])
2019-12-04T14:11:33.349834+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/google/auth/_service_account_info.py", line 54, in from_dict
2019-12-04T14:11:33.349836+00:00 app[web.1]:     signer = crypt.RSASigner.from_service_account_info(data)
2019-12-04T14:11:33.349838+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/google/auth/crypt/base.py", line 115, in from_service_account_info
2019-12-04T14:11:33.349840+00:00 app[web.1]:     info.get(_JSON_FILE_PRIVATE_KEY_ID))
2019-12-04T14:11:33.349842+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/google/auth/crypt/_python_rsa.py", line 174, in from_string
2019-12-04T14:11:33.349844+00:00 app[web.1]:     raise ValueError('No key could be detected.')
2019-12-04T14:11:33.349847+00:00 app[web.1]: ValueError: No key could be detected.
2019-12-04T14:11:33.349849+00:00 app[web.1]:
2019-12-04T14:11:33.349851+00:00 app[web.1]: During handling of the above exception, another exception occurred:
2019-12-04T14:11:33.349858+00:00 app[web.1]:
2019-12-04T14:11:33.349860+00:00 app[web.1]: Traceback (most recent call last):
2019-12-04T14:11:33.349862+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker
2019-12-04T14:11:33.349864+00:00 app[web.1]:     worker.init_process()
2019-12-04T14:11:33.349866+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process
2019-12-04T14:11:33.349868+00:00 app[web.1]:     self.load_wsgi()
2019-12-04T14:11:33.349871+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi
2019-12-04T14:11:33.349873+00:00 app[web.1]:     self.wsgi = self.app.wsgi()
2019-12-04T14:11:33.349875+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi
2019-12-04T14:11:33.349877+00:00 app[web.1]:     self.callable = self.load()
2019-12-04T14:11:33.349879+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load
2019-12-04T14:11:33.349881+00:00 app[web.1]:     return self.load_wsgiapp()
2019-12-04T14:11:33.349883+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp
2019-12-04T14:11:33.349885+00:00 app[web.1]:     return util.import_app(self.app_uri)
2019-12-04T14:11:33.349887+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app
2019-12-04T14:11:33.349889+00:00 app[web.1]:     import(module)
2019-12-04T14:11:33.349891+00:00 app[web.1]:   File "/app/app.py", line 30, in
2019-12-04T14:11:33.349893+00:00 app[web.1]:     CREDENTIALS = credentials.Certificate(ENV_KEYS)
2019-12-04T14:11:33.349895+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.7/site-packages/firebase_admin/credentials.py", line 100, in init
2019-12-04T14:11:33.349897+00:00 app[web.1]:     'Caused by: "{0}"'.format(error))
2019-12-04T14:11:33.349900+00:00 app[web.1]: ValueError: Failed to initialize a certificate credential. Caused by: "No key could be detected."
2019-12-04T14:11:33.350466+00:00 app[web.1]: [2019-12-04 14:11:33 +0000] [11] [INFO] Worker exiting (pid: 11)
2019-12-04T14:11:33.625273+00:00 app[web.1]: [2019-12-04 14:11:33 +0000] [4] [INFO] Shutting down: Master

Thanks in advance!!!

A: For anyone who stumbles on a similar issue (not limited to heroku & firebase),
when shells (some) parse environmental variables, they escape special characters hence passing them as literal.
for the case above, When you execute the command heroku config -s, you will notice that for the FIREBASE_PRIVATE_KEY characters, \n is replaced with \\n.
To fix, just replace \\n with \n in your code. See below
ENV_KEYS = {
"type": "service_account",
"private_key_id": environ["FIREBASE_PRIVATE_KEY_ID"],
"private_key": environ["FIREBASE_PRIVATE_KEY"].replace("\\n", "\n"),
"client_email": environ["FIREBASE_CLIENT_EMAIL"],
"client_id": environ["FIREBASE_CLIENT_ID"],
"token_uri": environ["FIREBASE_TOKEN_URI"],
"project_id": environ["FIREBASE_PROJECT_ID"],
}


text:
Q: Can you use matrices to solve for gravitational potential energies I was wondering whether its possible to use matrices to calculate the gravitational potential energy of a system. I know it's possible to calculate the acceleration due to gravity on a system by matrices but was wondering if it was possible to implement it with the potential. For gravity, the implementation is as follows, if the position is split into x, y, and z. Then the transpose of those respective elements subtracted by the original matrix finds the distances between all the points. Then if dx, dy and dz are squared
$$
x = \begin{pmatrix}
x_1\\
x_2\\
x_3
\end{pmatrix}
$$
where x in this case holds all the positions of the respective objects. The numbers indicating different objects. Then
$$
dx = x.T - x =
\begin{pmatrix}
x_1 & x_2 & x_3\\
\end{pmatrix}
- \begin{pmatrix}
x_1\\
x_2\\
x_3
\end{pmatrix}
= \begin{pmatrix}
0 & x_1-x_2 & x_1-x_3\\
x_2-x_1 & 0 & x_2-x_3 \\
x_3-x_1 & x_3-x_2 & 0
\end{pmatrix}
$$
The same is true for the y and z axis like the x. The following matrix stores 1/r^3 for all particle pairwise particle separations and raises it to the correct power.
$$ inverse = (dx^2 + dx^2 + dz^2)^{-\frac{3}{2}}
$$
therefore leading to
ax = G * (dx * inv_r3)(objects_mass) - sorry didn't know how to nicely display this.
The main question is now is this type of matrix manipulation relevant for Gravitational potential. The equation for which is
$$
U(r) = \frac{Gm_1m_2}{r}
$$
This varies from the one of gravity but with the main difference of multiplying by the other mass. So I was wondering if something like the following would be possible.
$$
m = \begin{pmatrix}
m_1\\
m_2\\
m_3
\end{pmatrix}
$$
where m contains all the masses
$$
m_m = (m)  (m.T)
$$
Thereby getting a multiplication of all the masses to each other and then the following
$$
(G\cdot m_m)*(dx^2 + dx^2 + dz^2)^{-1}
$$
Is something like this mathematically correct and if not can something similar be done? Thanks in advance


text:
Q: Proof with Möbius function, divisor function and little omega function For all natural numbers n, show
$\sum_{k|n}$$\mu$(k)d(k) = (-1)$^{\omega(n)}$
where
$\omega$(n) := $\sum_{p|n}$1
$\omega$(1) = 0
$\mu$(n) is the Möbius function and d(n) is the divisor function
So I know the $\omega$(.) function is the sum of all distinct primes of n, but this problem doesn't make sense to me. The RHS will always be $\pm$1 but the LHS seems like it could be other values since d(n) can be greater than 1.
Any pointers or solutions would be much appreciated!

A: In response to query by OP we observe that with $g(n)$ multiplicative
we have
$$\sum_{d|n} g(d)
= \prod_{p^v||n} (g(1)+g(p)+g(p^2)+\cdots+g(p^v)).$$
Here we have $g(n) = \mu(n) d(n)$ and with $\mu(n)$ zero when $n$
is not squarefree this becomes
$$\sum_{d|n} g(d)
= \prod_{p^v||n} (g(1)+g(p)).$$
Observe  that $g(1)  =  \mu(1)d(1) =  1$  and $g(p)  =  \mu(p) d(p)  =
(-1)\times 2$ so we get
$$\sum_{d|n} g(d)
= \prod_{p^v||n} (1+(-1)\times 2)
= \prod_{p^v||n} (-1)  = (-1)^{\omega(n)}$$
as claimed.


text:
Q: Building an App Shell For My Service Worker to cache using Handlebars I am building a PWA using express-handlebars. I'm trying to follow the Google design practices and build an app shell in order to cache with a service worker. However, I'm a little stumped since Handlebars is a template engine which generates html. Is there a better way to build an app shell with express for service worker caching? Examples would be appreciated.

A: "Is there a better way" depends on many variables in your project and there's really no answer to that.
More important here is to understand the basic idea of an app shell, in my opinion at least. When you grok that you'll be able to tune your variables and pick the right tech freely. Generating HTML with Handlebars is completely fine if it suits your app. HTML is fast for the browser to render (vs JS heavy stuff) so it fits the shell idea perfectly.
With app shell your app is structured in the not constantly changing, static(ish) layout (menu, header, footer etc.) and dynamic part. With this separation the app shell idea can use Service Workers this way:

*

*Server ships the app shell (usually only HTML/CSS)

*Browser renders that very fast and caches it for offline use via Service Worker

*After showing the shell, JS takes over and starts to fetch dynamic content (what is shown "inside" the shell)

*Browser renders the dynamic part utilising some JS framework (usually)

These separate parts could be very loosely-coupled. You could use whatever means you want to create the app shell and something completely different for the dynamic part. Or, you could implement them with the same front-end framework. It doesn't really matter from the point of view of the app shell architecture. The point is, the shell should be available super-fast which you'll achieve more easily when you ship just HTML/CSS.


text:
Q: Exportación de un datagridview a excel C# Visual Studio 2017/2019 Estuve leyendo diferentes formas de hacerlo y encontré esta manera: Probé de diferentes formas pero en todas me marca error al momento de crear el documento de excel. Ya activé las referencias de microsoft excel 16.0 y no me funciona e incluso he probado usar el using microsoft.Office etc... pero igualmente no funciona. Alguien podría explicarme o enseñarme como se hace? :(
        SaveFileDialog fichero = new SaveFileDialog();

        fichero.Filter = "Excel (*.xls)|*.xls";
        if (fichero.ShowDialog() == DialogResult.OK)
        {
            Microsoft.Office.Interop.Excel.Application aplicacion;
           PRIMER ERROR EN DONDE DICE WORBOOK Microsoft.Office.Interop.Excel.Workbook libros_trabajo;
            Microsoft.Office.Interop.Excel.Worksheet hoja_trabajo;
            aplicacion = new Microsoft.Office.Interop.Excel.Application();
           SEGUNDO ERROR EN WORBOOKS libros_trabajo = aplicacion.Workbooks.Add();
             hoja_trabajo  =              (Microsoft.Office.Interop.Excel.Worksheet)libros_trabajo.Worksheets.get_Item(1);

            for (int i = 0; i < grd.Rows.Count - 1; i++)
            {
                for (int j = 0; j < grd.Columns.Count; j++)
                {
                   TERCER ERROR EN CELLS hoja_trabajo.Cells[i + 1, j + 1] = grd.Rows[i].Cells[j].Value.ToString();
                }
            }
            libros_trabajo.SaveAs(fichero.FileName,
                ERROR EN XLFORMART Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal);
            libros_trabajo.Close(true);
            ERROR EN QUIT aplicacion.Quit();
        }


text:
Q: Php combine the values of two array objects I have a oject that contains:and I want combine the content of [0][locationName and [1][locationName into another object/variable so the content would be "Weymouth and Bournemouth". I know there are similar questions on here but my keys in the array have the same name. How would this be done?
[destination] => stdClass Object
   (
   [location] => Array
    (
      [0] => stdClass Object
        (
          [locationName] => Weymouth
          )

      [1] => stdClass Object
      (
        [locationName] => Bournemouth
      )
  )
)

Many thanks in advance for your time.

A: Assuming that you have the reference to $destination as an object then perhaps you can try like this:
$arr=$destination->location;
$tmp=array();

foreach( $arr as $index => $obj )$tmp[]=$obj->locationName;

$tmp=implode(' and ',$tmp ); // do something with $tmp

Assuming I recreated the original object correctly
$obj=(object)array(
    'destination' => (object)array(
        'location'  =>  array(
            (object)array('locationName'=>'Weymouth'),
            (object)array('locationName'=>'Bournemouth')
        )
    )
);

The above produces a structure like this:
[destination] => stdClass Object
    (
        [location] => Array
            (
                [0] => stdClass Object
                    (
                        [locationName] => Weymouth
                    )

                [1] => stdClass Object
                    (
                        [locationName] => Bournemouth
                    )

            )

    )

$destination=$obj->destination;

pre( $obj );

$arr=$destination->location;
$tmp=array();

foreach( $arr as $index => $obj )$tmp[]=$obj->locationName;

$tmp=implode(' and ',$tmp ); // do something with $tmp
echo $tmp;  // --> outputs Weymouth and Bournemouth


text:
Q: What is the alternative to WebSocket for Firefox (and IE) When looking for WebSocket on Firefox (or IE) ...
if ("WebSocket" in window)
{
    ...
}
else
{
    alert('Your browser does not support websocket');
}

They are both failing !
If they dont have any WebSocket, is there a way in JS to exchange some TCP message with a server ? (connect/send/recv ???)

A: Check out Socket.IO and Faye for portable implementations.

A: You can also use the web-socket-js which uses Flash to add WebSockets support. In fact, Socket.IO uses web-socket-js as a fallback if the browser doesn't natively support WebSockets. Socket.IO is very nice but if you just want lower level WebSockets support without requiring your backend to be written in Javascript then there are many WebSockets servers that exist.


text:
Q: Allow App Data to be downloaded to iCloud (Nativescript) My Nativescript iOS app saves some user created data using the nativescript-localstorage plugin. I want to be sure that users have a place to back-up this data.
The most straightforward option seems to be that they can include the app's data in an icloud backup (ie, icloud -> icloud Drive -> then allow the app to be backed up in the drive).
When I have used "$ tns run ios" and run the app locally on my phone, the app properly runs on my phone, but it does not appear as an option for backing up to icloud. On the icloud backup screen where apps are listed that you can choose to backup, my app does not appear.
This might be because it is just a local build, and only full releases (apps received from the app store) can be included in icloud backups, but I have not seen this confirmed anywhere.
Do I need to do anything to enable my app to be available for icloud backup?

A: I have figured out the key piece I was missing--that there are two different types of iCloud uses:
(i) the system-wide iCloud backup that happens automatically if the user turns it on (app developer does not need to take special action) and (ii) the iCloud as a cloud storage solution for certain data that you as the programmer need to configure.
For iCloud with CloudKit to show up as a specific feature of your app, this requires (ii)--and further configuration than just enabling it.
Further detail in my answer here.


text:
Q: How to see if first character of a string is " " (a string starting with ") static boolean isLiteralTexto(String lexema) {
           String letra = [34];
            String caracter = "";
            int estado = 1;
            for (int i = 0; i < lexema.length(); i++) {
                caracter = lexema.charAt(i) + "";
                switch (estado) {
                case 1:
                    if (caracter.matches(letra))
                        estado = 2;
                                    System.out.println("HOLA");
                    else
                        estado = 3;
                    break;

I dont know how to make it, is JAVA could you help me?
 Im doing a lexer and a parser

A: Use standart java: yourstring.startsWith(" ");

A: you can check using the following snippet:
if(lexema.indexOf(" ")==0)


text:
Q: cannot get nodejs working on amazon ec2 instance I am trying to run nodejs server on amazon micro instance for the past 3-4 days with no success.
i followed so many tutorials and i cannot make the server work (so when its visited in browser or curl in powerShell and see the simple hello world).
Here are the last 3 tutorials I've tried:
http://iconof.com/blog/how-to-install-setup-node-js-on-amazon-aws-ec2-complete-guide/
http://techprd.com/setup-node-js-web-server-on-amazon-ec2/
http://devblog.daniel.gs/2014/01/deploying-node-apps-on-aws-ec2-with.html
I've tried ubuntu/ amazon linux.
I've also followed http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/install-LAMP.html just to see how the general process works and it did work fine.
I get to the point where i do something like: sudo node filename.js
and the server runs.
However when i try visiting or curl it. it doesnt work. when i ping it it pings fine.
in amazon i set the security group to basically allow everything like so:

in linux its self i followed : https://help.ubuntu.com/community/IptablesHowTo?action=show&redirect=Iptables to open the port i was trying to listen to and nothing.
when i type : sudo service iptables status i get :
1 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpts:1337:1347
2 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpts:1338:1348
3 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:10000
keep in mind i am not a server savvy guy.
Any help would be highly appreciated.
UPDATE: To start my node server i use the basic code found in nodejs.org :
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

This is exactly how my file look like

A: You haven't provided enough info, but I'll try and outline the general troubleshooting techniques.

*

*Is your node program running and serving requests?  Get on the Ec2 box and do curl -v localhost:8000 (or whatever your node port is.) It should spit out your app. If not, your node.js setup isn't right.

*Is your nginx running? Get on the box and type curl -v localhost. That will look on your port 80. If it doesn't proxy to your app, it's probably an nginx configuration problem.

*Can you reach the box via IP address? From your desktop/laptop, do curl -v x.x.x.x where x.x.x.x is your EC2 Public IP address. If that hangs, there is a firewall problem.

*Can you reach the box via your DNS? (Assuming you are trying to have foo.com point to it) Try curl -v http://foo.com/. If that doesn't work, your DNS may not be correct.

However when i try visiting or curl it. it doesnt work.

Please be more specific.


text:
Q: Does direction of current in Node Voltage method circuit analysis matter? I am trying to solve the following circuit using the node voltage method, but I'm having issues with figuring out how current is supposed to flow in and out of nodes.

I understand that the current arrows shown are just a reference for the direction in which you should write the answer (i.e., if $i_a$ is a positive current going right to left, the answer will be negative). When I try to write my equations, I set the bottom wire as ground and get the following by going through the steps of node voltage method:
\begin{align*}
\frac{v_1-v_3}{5}-\frac{v_3}{60}-\frac{v_4-v_3}{4} &= 0,\\
\frac{v_2-v_4}{10}-\frac{v_4}{80}+\frac{v_3-v_4}{4} &= 0.
\end{align*}
(Here $v_3$ is the voltage at the top left dot, $v_4$ at the top right dot.)
As I understand it, the sign on unknown currents is arbitrary since if the sign is wrong, then the result will simply be negative. However, in the way my signs are set, I get the wrong currents despite my equations matching the solution in all other regards as far as I can tell.
Is there an issue with my equations that I can't see, or am I misunderstanding something about how currents work?
The values I used for $v_1$ and $v_2$ were $112\,\mathrm V$ and $330\,\mathrm V$ respectively.

A: Can't add comments yet.
One issue here is the inconsistency with a current direction.
For instance, if you decided to consider currents flowing in as positive (as I believe you did), it is better to show the terms associated with these currents as positive everywhere. In your case, current Ie is flowing out, but is presented as positive.
Another issue is the inconsistency with deriving a current from node voltages.
If you assume that a current flows from a to b, it has to be expressed as (Va-Vb)/R. In your case, you assumed that Ic flows from node 3 to node 4, but you've expressed it as (V4-V3)/R.
NOTE: if you feel like doing the opposite, i.e., expressing it as (Vb-Va)/R, you should do to it the same way everywhere, which would essentially mean that all your arrows have to be flipped.
The term (v2-v4)/10 has two inconsistencies in it and, as a result, it is technically correct, but it would be easier to understand the equation if it was written as -(v4-v2)/10.

A: I would write the first equation as the sum of the currents entering (or leaving) the junction equal to zero.
As current flows from high potential to low potential the currents will all be of the following form as they are entering the node at potential $v_3$ which is at the "lower" potential.
$$\frac{v_{\rm x}-v_3}{R}$$
This gives
$$\frac{v_1-v_3}{5}+\frac{0-v_3}{60}+\frac{v_4-v_3}{4} = 0$$
Which is not quite the same as your first equation $$\frac{v_1-v_3}{5}-\frac{v_3}{60}-\frac{v_4-v_3}{4} = 0$$
I have assumed that the bottom node is at a potential of zero and completely ignored any current direction arrows that you have drawn in your diagram.
You can do the same for the other node at potential $v_4$ and then solve for  $v_3$ and  $v_4$.
Then, for example, $i_{\rm b}  = \dfrac{v_3-0}{60}$ as the direction of the current as shown in the diagram is from the node at potential $v_3$ to the node at potential zero.


text:
Q: JavaFX ColorPicker customizable via CSS I'm struggling with javafx as a starter. I am trying to find the  structure of a color picker that is modifiable with css.
Until now i've found that a colorpicker has a label child that can be customizable all fine.
Now what i want is to customize the background of the expanded colorpicker menu (i dont know the name of that):

I tried .color-picker * {
-fx-background-color: black
}
and worked like a charm, but i don't want to do a barbaric thing like this. I'm sure the exact structure of it has to be somewhere so i can modify it with CSS.
Looked into javafx css reference already, but found nothing relevant about this!
P.S: also, i would like ot know if it's possible to remove the "Custom Color..." dialog completely from the colorpicker somehow.


text:
Q: how to add foreign key to table that reference to column of data type blob My problem:
i created two tables using mysql
the first table called team and it has team id and team name
the second table media table and it has  id and image of type blob
i want to add foreign key in table team refernce to column image in media table
i searched google but i found that i can not do this way
so if i can not is there any way to add a foreign key reference to column that hold image data?
this is the team table
CREATE TABLE `team` (
  `TE_ID` INT(11) NOT NULL,
  `TE_Name` VARCHAR(255) NOT NULL,
  `image` VARCHAR(255) NOT NULL
) ENGINE=INNODB DEFAULT CHARSET=utf8;

and this media table
CREATE TABLE `media`(
`media_id` INT(11) NOT NULL,
`media_jpg` BLOB
);ENGINE=INNODB DEFAULT CHARSET=utf8;

i hope someone can help me

A: As a general rule keys should be small and easy to use, reference, etc. Don't use the BLOB as a foreign key, but use its ID instead. For example:
CREATE TABLE `media`(
  `media_id` INT(11) NOT NULL,
  `media_jpg` BLOB
);ENGINE=INNODB DEFAULT CHARSET=utf8;

Then, create the table that references this one:
CREATE TABLE `team` (
  `TE_ID` INT(11) NOT NULL,
  `TE_Name` VARCHAR(255) NOT NULL,
   image_id INT(11) NOT NULL,
   constraint fk1 foreign key (image_id) references `media` (`media_id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;

Also, you don't need to use backticks to enclose every column name. Use them only when you have names with spaces or special characters. It doesn't seem to be the case in any of your table or column names.


text:
Q: Compare TSV datasets for changes in database I've got a dataset in TSV format put into a Postgres database using Java and Hibernate divided into multiple tables with around 30 million of entries in each table. Now periodically I receive the same dataset with some entries changed and some new ones added added in TSV format again.
It is not stated which ones have changed.
I want to find out which entries where added and changed and add the new ones and update the changed ones in the database. How would I achieve that without manually checking each entry?
Data comes from IMDB database as:
tt0000177   1   The Burglar on the Roof US  \N  \N  \N  0
tt0000178   1   The Cavalier's Dream    US  \N  \N  \N  0
tt0000179   1   The Cave of the Demons  US  \N  \N  \N  0


text:
Q: Фон в Предложении

const buttons = document.querySelectorAll('button');
const display = document.querySelector('.display');

buttons.forEach(function(button) {
  button.addEventListener('click', calculate);
});

function calculate(event) {
  const clickedButtonValue = event.target.value;

  if (clickedButtonValue === '=') {
    if (display.value !== '') {
      let str = display.value
        .replace(/\^/g, "**")
        .replace(/%(\d+(?:\.\d+)?)/g, "*($1/100)");

      display.value = eval( str );
    }
  } else if (clickedButtonValue === 'C') {
    display.value = '';
  } else {
    display.value += clickedButtonValue;
  }

}
function soundClick() {
  var audio = new Audio();
  audio.src = 'https://www.myinstants.com//media/sounds/10_p895CLI.mp3';
  audio.autoplay = true;
}
function soundClick2() {
  var audio = new Audio();
  audio.src = 'https://www.myinstants.com//media/sounds/0447-mp3cut.mp3';
  audio.autoplay = true; }
  const s = window.screen;

const w = (q.width = s.width);
const h = (q.height = s.height);
const ctx = q.getContext("2d");

const p = Array(Math.floor(w / 10) + 1).fill(0);

const random = (items) => items[Math.floor(Math.random() * items.length)];

const hex = "0123456789ABCDEF".split("");

setInterval(() => {
  ctx.fillStyle = "rgba(0,0,0,.05)";
  ctx.fillRect(0, 0, w, h);
  ctx.fillStyle = "#0f0";
  p.map((v, i) => {
    ctx.fillText(random(hex), i * 10, v);
    p[i] = v >= h || v > 50 + 10000 * Math.random() ? 0 : v + 10;
  });
}, 1000 / 30);
* {
  padding: 0;
  margin: 0;
}

body {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #222831;
  font-family: sans-serif;
    margin: 0;
    overflow: hidden;

}

.calculator {
  width: 300px;
  padding-bottom: 15px;
  border-radius: 7px;
  background-color: rgb(0, 0, 0);
  box-shadow: 5px 8px 8px -2px rgba(0, 0, 0, 0.61);

}

.display {
  width: 100%;
  height: 80px;
  border: none;
  box-sizing: border-box;
  padding: 10px;
  font-size: 2rem;
  background-color: #f8d407;
  color: rgb(0, 0, 0);
  text-align: right;
  border-top-left-radius: 7px;
  border-top-right-radius: 7px;

}

.row {
  display: flex;
  justify-content: space-between;
}

button {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  border: none;
  outline: none;
  font-size: 1.5rem;
  background-color: rgb(34, 34, 34);
  color: #fff;
  margin: 10px;
}

button:hover {
  cursor: pointer;
}

.operator {
  background-color: #888888;
  color: rgb(0, 0, 0);
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" type="text/css" href="css/styles.css">
  <title>Calculator</title>
  <canvas id=q></canvas>

    <input type="text" class="display" disabled>

<button value="7">7</button>

<button value="8">8</button>

<button value="9">9</button>

<button value="+">+</button>

<button value="4">4</button>

<button value="5">5</button>

<button value="6">6</button>

<button value="-">-</button>

<button value="1">1</button>

<button value="2">2</button>

<button value="3">3</button>

<button value="*">*</button>

<button value="C">C</button>

<button value="0">0</button>

<button value="/">/</button>

<button value="=" class="operator">=</button>

<button value="(">(</button>

<button value=")">)</button>

<button value="^">^</button>

<button value="%">%</button>

Здравствуйте, хочу добавить фон к калькулятору, но когда добавляю, калькулятор перемешается вправо, а мне надо чтобы он был посредине, а сзади фон


text:
Q: Everything stopped because of one event @client.event
async def on_message(message):
    if message.channel.id == 872448587571789834:
        data = message.content.split(" ")
        user = re.sub("\D", "", data[0])

        user_object = client.get_user(int(user)) or await client.fetch_user(int(user))
        user = user_object
        await user_object.send("Hey, thanks for up-voting me on top.gg, here take 10,000 coins and a special role as an award ")
        #voted = discord.utils.get(message.guild.roles, name=" Voted for Legend Moderation")
        await open_account(user_object)

        users = await get_bank_data()

        users[str(user.id)]["wallet"] += 10000

        with open("bank.json", "w") as f:
            json.dump(users, f, indent=4)
    else:
        return

So, what I'm doing here. I'm checking if there is a message sent in that specific channel id and the id contains a user so its working the code works but all the other commands don't work when I put it

A: You have to change @client.event to @client.listen()

A: Try using client.process_commands(message)
example:
@client.event
async def on_message(message):
  await client.process_commands(message)

  if message.channel.id == 872448587571789834:
    data = message.content.split(" ")
    user = re.sub("\D", "", data[0])

    user_object = client.get_user(int(user)) or await client.fetch_user(int(user))
    user = user_object
    await user_object.send("Hey, thanks for up-voting me on top.gg, here take 10,000 coins and a special role as an award ")
    #voted = discord.utils.get(message.guild.roles, name=" Voted for Legend Moderation")
    await open_account(user_object)

    users = await get_bank_data()

    users[str(user.id)]["wallet"] += 10000

    with open("bank.json", "w") as f:
        json.dump(users, f, indent=4)
else:
    return

see if using client.process_commands(message) works.


text:
Q: Cant Find JetCreator in android studio I'm trying to use JetCreator to create sounds for my application and I can't figure out how the install it. As said in the JetCreator user's manual, I have installed Python (3.4) and wxPython. Unfortunately, I can't find any "jetCreator.py" file in the android sdk folder (the "jet" directory is not present in the "android-sdk/tools" folder).
Is JetCreator still available? Where can I find it? And where could I find an up-to-date user's manual?

A: Found this during my search...
jetCreator tool does not exist in the latest SDK -- Should be moved to extra. [37002989] - Visible to Public - Issue Tracker
https://issuetracker.google.com/issues/37002989


text:
Q: How would I output all the possible combination of 7 numbers from 30 different numbers in an array in Javascript? For example I've array generated with the loop like this.
var array=[];
for(var i=1; i<=30; i++)
  {
   array.push(i);

  }
 console.log(array);

I want to output the combination of all the possible group of 7 numbers from the array. For example a sample output may look like : [1,5,14,4,30,23,19]. If I would to calculate the possible combination with the combination formula. It would be something like this:
n!/r!(n-r)!
And it is going to be a huge number. I've found a  permutation solution here,
but what it does is that it prints out all the possible numbers according to the length of array. But my need is to find out the possible combination of 7 numbers from total 30 integers.
How would I solve this problem logically and practically with javascript.

A: First of all: this will generate bincoef(7,30) sets of integers, which is roughly 2mio. sets, so you should really consider whether you need this amount of data, since this algorithm will generate a mass of data and will require quite a lot of data. I can only offer pseudocode, since my javascript knowledge is rather basic.
void nextPermutation(int[] in, int[] set, int last_from_input, int at_element)
    //we can't generate further permutations from this position, since
    //there is aren't enough elements in the input-array left
    if(last_from_input >= 30 - at_element)
        return

    //the set is filled -> process the produced set
    if(at_element === 7)
        print(set)//process permutation
        return

    //add one element to the set and proceed with further elements
    for(int i in ]last_from_input, length(in) - (7 - at_element)[
        set[at_element] = in[i]

        nextPermutation(in , set , i, at_element + 1)

Basically this algorithm gets the following arguments:

*

*in : the 30 integer to select from

*set: the current part of the petmutation containing all elements we've added so far

*last_from_input: the index of the last element from in we added to set

*at_element: the index of the element in the set we're currently searching

This algorithm basically adds one element that has a higher index than the last added element and continue searching recursively searching for the next element. If the set is complete it can be processed. If there are more elements required to complete the set than elements left in in it's impossible to complete the set, we can break off with this part of the search. This is not optimally implemented regarding efficiency but I tried to keep things simple
Now we can simply generate all permutations in this way:
void genPermutations(int[] in)
    nextPermutation(in , new int[7],-1,0)

A: guess this is what you're after?
function cartesian_product(xs, ys) {
    var result = [];
    for(var i = 0; i < xs.length; i++) {
        for (var j = 0; j < ys.length; j++) {
            // transform [ [1, 2], 3 ] => [ 1, 2, 3 ] and append it to result []
            result.push([].concat.apply([], [ xs[i], ys[j] ]));
        }
    }
    return result;
}

function cartesian_power(xs, n) {
    var result = xs;
    for(var i = 1; i < n; i++) {
        result = cartesian_product(result, xs)
    }
    return result;
}

// in your case params are [ 1, 2... 30] and 7
console.log(cartesian_power([1, 2, 3, 4], 2));

output is:
[ [ 1, 1 ],
  [ 1, 2 ],
  [ 1, 3 ],
  [ 1, 4 ],
  [ 2, 1 ],
  [ 2, 2 ],
  [ 2, 3 ],
  [ 2, 4 ],
  [ 3, 1 ],
  [ 3, 2 ],
  [ 3, 3 ],
  [ 3, 4 ],
  [ 4, 1 ],
  [ 4, 2 ],
  [ 4, 3 ],
  [ 4, 4 ] ]

UPDATE
this one will require much less memory, since it will not store anything, it will just print the output. but still doubt it's practical.
function print_combs(arr, n, out) {
    if (n === 0) {
        console.log(out);
    } else {
        for(var i = 0; i < arr.length; i++) {
            print_combs(arr, n-1, out+arr[i]);
        }
    }
}

print_combs([1, 2, 3, 4], 2, "");


text:
Q: Refactoring similar method using a LinkedList This is a refactoring question mainly.
I am creating some methods to go back/forward through an actions history depending on its Id/PreviousId relationship (see basic class below):
public class Action
{
    public int Id { get; set; }
    public int PreviousId { get; set; }
    public string Title { get; set; }
}

Background Info:
I start off by getting a single action from the database. If the user selects 'GoBack', I need to get the previous action from the database and store it in a LinkedList. This means users can potentially revisit that same action (i.e. by going back then forward again) but by calling it from the LinkedList version rather than getting it from the database again. I don't want to initially retrieve all actions first either from the database. I have this functionality working but my GoBack() and GoForward() methods are pretty much identical.
I was hoping to see if there is a good way of refactoring this into a more generic method set rather than duplicating code? (Note - my code doesn't include the database calls to reduce reading so instead I've put dummy data into a List to act as my database).
Class level variables I'm referencing in the methods:
   //The list I'm using to pretend to be my database containing actions
   private List<Action> _actions { get; set; }

   private Action _currentAction { get; set; }
   private LinkedList<Action> _actionLinks { get; set; }

Here is my GoBack() method:
   private void GoBack()
   {
       var current = _actionLinks.Find(_currentAction);

       if (current == null)
           return;

       //If we've already stored the previous action. Just point to it
       if (current.Previous != null)
       {
           _currentAction = current.Previous.Value;
           return;
       }

       //We don't have this action stored so go get it from the database and cache it in the list
       var previousAction = _actions.FirstOrDefault(i => i.Id == _currentAction.PreviousId);

       //There are no previous actions
       if(previousAction == null)
           return;

       _actionLinks.AddBefore(current, previousAction);

       //Now reset the current action
       _currentAction = previousAction;
   }

Here is my GoForward() method:
   private void GoForward()
   {
       var current = _actionLinks.Find(_currentAction);

       if (current == null)
           return;

       //If we've already stored the next action. Just point to it
       if (current.Next != null)
       {
           _currentAction = current.Next.Value;
           return;
       }

       //We don't have this action stored so go get it from the database and cache it in the list
       var nextAction = _actions.FirstOrDefault(i => i.PreviousId == _currentAction.Id);

       //There are no further actions
       if (nextAction == null)
           return;

       _actionLinks.AddAfter(current, nextAction);

       //Now reset the current action
       _currentAction = nextAction;
   }

If you want to compile the code. I've added in my Constructor and BuildData method I'm using to test this:
Constructor:
   public LinkListTest()
   {
       _actionLinks = new LinkedList<Action>();
       _actions = new List<Action>();
       BuildData();

       //Just set current to the latest action id
       _currentAction = _actions.First(i => i.Id == 6);

       //Add it to the linkedlist
       _actionLinks.AddFirst(_currentAction);

       //Start navigating as a user would
       GoBack();
       GoBack();
       GoForward();
       GoBack();
       GoForward();
       GoBack();
       GoBack();
   }

BuildData method:
   private void BuildData()
   {
       for (int i = 6; i >= 0; i--)
       {
           var action = new Action();
           action.Id = i;
           if (i != 0)
               action.PreviousId = i - 1;
           else
               action.PreviousId = -1;

           action.Title = string.Format("Action {0}", i);

           _actions.Add(action);
       }
   }

Thanks in advance!

A: One way to de-duplicate some of the logic here is to use the visitor pattern.
    using ActionListAction = System.Action<System.Collections.Generic.LinkedList<Package.Action>, System.Collections.Generic.LinkedListNode<Package.Action> ,Package.Action>;

    ...

    private void GoBack()
    {
        Move(new BackwordVisitor());
    }

    private void GoForward()
    {
        Move(new ForwardVisitor());
    }

    private void Move(DirectionVisitor direction)
    {
        var current = _actionLinks.Find(_currentAction);

        if (current == null)
            return;

        var node = direction.Pointer(current);
        if (node != null)
        {
            _currentAction = node.Value;
            return;
        }

        var action = _actions.FirstOrDefault(i => direction.NextSelector(i, _currentAction));

        //There are no further actions
        if (action == null)
            return;

        direction.Add(_actionLinks, current, action);

        _currentAction = action;
    }

    private abstract class DirectionVisitor
    {
        public Func<LinkedListNode<Action>, LinkedListNode<Action>> Pointer { protected set; get; }
        public Func<Action, Action, bool> NextSelector { protected set; get; }
        public ActionListAction Add { protected set; get; }
    }

    private class ForwardVisitor : DirectionVisitor
    {
        public Forward()
        {
            Pointer = n => n.Next;
            NextSelector = (action, current) => action.PreviousId == current.Id;
            Add = (list, current, node) => list.AddAfter(current, node);
        }
    }

    private class BackwordVisitor : DirectionVisitor
    {
        public Backword()
        {
            Pointer = n => n.Previous;
            NextSelector = (action, current) => action.Id == current.PreviousId;
            Add = (list, current, node) => list.AddBefore(current, node);
        }
    }

Since there are only two options for moving through the list, this may be overkill for this particular scenario.  Passing an enum into the Move method with the direction and using conditionals may read better.


text:
Q: How to use treeview with angular ui grid Ho guys, i'm using angular ui grid in my project..heres my code :
 $scope.gridOptions = {
        enableSorting: false,
        enableRowSelection: true,
        multiSelect: false,
        exporterMenuCsv: false,
       // enableGridMenu: true,
        enableSelectAll: true,
        enableColumnResizing: true,
        enableSorting: true,

         onRegisterApi: function(gridApi) {
            $scope.gridApi = gridApi; //set gridApi on scope
             gridApi.core.on.renderingComplete($scope, function () {
              $timeout(function () {
                var gridBodyElem = document.getElementById(gridApi.grid.id + '-grid-container');
                gridBodyElem.addEventListener('mouseup', handleGridClick);
              });
            });
      },

columnDefs: [
      { field: 'name',displayName:'Name',cellClass: 'gridField'},
      { field: 'uniqueid',displayName:'ID',cellClass: 'gridField'},
      { field: 'devicetime',displayName:'GPS DATE',cellClass: 'gridField'},
      { field: 'adress',displayName:'Adresse',cellClass: 'gridField'},
      { field: 'company',displayName:'Company',cellClass: 'gridField'}
]

};
it works good but i want to use a treeview in this grid to obtain like this table grid below..

what i want exacly is, when i click on item, i want to show a html code below like the image above...is there anyone has any idea how to do this..??

A: Example controller :
var SomeController = function () {

    this.customHtml = '

render me please

';
}

Example view :

Gives :

    "

render me please

"


text:
Q: Deleting item on list MVC ASP.Net Well on this part it is intended to delete the appointed item, But when executed the item that will be deleted is always the top item.
public ActionResult Delete(string id)
{
    db = new RobinsonsDBContext();

    var slider = (from s in db.Sliders
                   where s.Id == new Guid(id)
                   select s).First();
    slider.IsDeleted = true;
    db.Entry(slider).State = EntityState.Modified;
    db.SaveChanges();

    return RedirectToAction("Index", "Sliders");
}

What is the problem? just a beginner on mvc.

A: Use Like
Slider oSlider=db.Sliders.Find(id);
db.Sliders.Remove(oSlider);
db.SaveChanges();

It will delete your desired item.


text:
Q: How do Async Javascript Programs Interact Back in the early days of web development, I picked up a bit of folk wisdom that, for code like this
<script src=".../program1.js"></script>
<script src=".../program2.js"></script>

the browser would pause, load the javascript, compile it, execute it, move on to the next script tag, and repeat.  In this way, the browser would work its way through all the javascript on a page and treat it as one linear program.
However, in the brave new modern javascript world, we have asynchronous loading via the async attribute
<script src=".../program1.js" async></script>
<script src=".../program2.js" async></script>

It's my understanding that this is a good thing because now the browser does not need to pause, download the script, and execute it. Instead it starts downloading the script, but will continue to parse the DOM.  i.e. the web page no longer blocks while waiting for javascript to download. (if this is not true I'd appreciate the correction).
However, what's less clear (and harder to test) is how these two programs interact.  They appear to run in the same shared space (i.e. javascript is still, from a userland perspective, single threaded with two (global, function) scopes).  However, what order they execute in seems ill-defined in the documentation I've read.
I've read through the MDN article on Concurrency model and Event Loop.  While interesting and useful, it doesn't quite answer my question.  From what I gather, when the browser loads program1.js or program2.js, javascript will add a message to the event queue, and that message will be processed as the javascript engine runs through the event loop.
What's missing for me is -- what does that message say?  Is it a single message for each program that says "compile and execute all this javascript code"?  Or does each program create multiple messages -- in my mind that might look something like

*

*Message 1: Extract all the functions from this program and compile them

*Message 2: Extract all statements and expressions in the global scope from this program

*Message 3-n: Add each statement and expression as an individual queue message for later processing.

And what happens when the browser is in the middle of processing program1.js, but finishes downloading program2.js?  Is it possible that execution of statements from each program will be interleaved?
I realize that, as a client developer, the best practice here is to not rely on global scope and write each program and function so it doesn't matter how it's called, and doesn't block other people's code.  However, I spend a lot of time dealing with other people's code, some of which isn't well behaved. I'd like to understand what's going on behind the scenes, or if this is behavior that's undefined and, engine independent, and won't line up between implementations.

A: There are two articles illustrate the "async" and "defer" properties in a practical sense (I'm green on the browser internals):
From 2014 with excellent + simple graphics:
http://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html
From 2016 why async might be an anti-pattern:
http://calendar.perfplanet.com/2016/prefer-defer-over-async/
Async
To your question, what "async" instructs the browser to do is:

*

*Start downloading this resource as early as possible.

*Move on and feel free to download other resources in parallel.

*But as soon as my download completes, stop rendering and begin executing me as early as possible.

Effectively "async" can still block rendering and subsequent execution, but it allows the parser to continue working right up until execution can begin.
Multiple async scripts have no guarantee what order they will execute in. Depends how quickly the load. That lets AMD-systems like RequireJS define dependencies and callbacks to load resources async but queue their execution until the "global" environment contains all the prerequisites and the execution order can be negotiated (by rune magic) hopefully.
Defer
Defer behaves like this:

*

*Start downloading this resource as early as possible.

*Move on and feel free to download other resources in parallel.

*But as soon as my download completes, do nothing until the parser is done.

*Now execute all the scripts in the order they were discovered.

On one hand, "defer" is faster because it can never block the parser or rendering. But "defer" can be slower because it must wait to execute until the pipeline is clear.
That sounds like "async" is always better, but if you load 2 MB of JS on weak-CPU phone with a fast connection you may end up waiting 10s for execution before the parser is allowed to finish rendering. Using "defer" would prevent that at the expense your interaction layer being delayed.
The distinction is fuzzier if you're talking client/server or client-side apps. It may be more beneficial to use defer in a backend heavy app like Magento where rendering is handled server-side.
In a fully client-side app you probably get zero content until the JS monolith is loaded, so "defer" doesn't really do anything for you, but then neither does "async" if your whole app is a massive JS bundle and there's nothing to do in parallel.

A:
Is it possible that execution of statements from each program will be interleaved?

No, absolutely not. JS is still single-threaded, and one program runs after the other (although which of them comes first might be unknown).

What does that event loop message say?

The message is a ScriptEvaluationJob. Assuming parsing of the script is successful, it will instantiate all declarations and evaluate the script body, all in one run.


text:
Q: Unable to get method to access characters in a String I am trying to make a Caesar Cipher app on Android Studio. I have the XML file and most of the other code ready but was unable to continue past the point in the code where I must access each element of the string. I have tried using the charAt() function.
Also I just want the character at the point in the array to increase by the number specified, I say this because I saw that after 'z' special characters like '|' appear and that is fine by me. This is my first app and could really use some help. The error is at line 47 and 61.
Here is my code:

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity
{

    EditText input;
    EditText output;
    EditText num;

    String inp;
    String out;
    int choice;
    Character c;

    Button enc, dec;

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

        input = (EditText) findViewById(R.id.input);
        output= (EditText) findViewById(R.id.output);
        num = (EditText) findViewById(R.id.num);

        enc = (Button) findViewById(R.id.enc);
        dec = (Button) findViewById(R.id.dec);

        enc.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                inp=input.getText().toString();
                choice= Integer.parseInt(num.getText().toString());
                for(int i=0;i<input.length();i++)
                {
                    inp.charAt(i)= (char) (inp.charAt(i)+choice);
                }
            }
        });

        dec.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v1)
            {
                inp=input.getText().toString();
                choice= Integer.parseInt(num.getText().toString());
                for(int i=0;i<input.length();i++)
                {
                    inp.charAt(i)= (char) (inp.charAt(i)-choice);
                }
            }
        });
    }
}

A: I believe your first problem is here:
inp.charAt(i)= (char) (inp.charAt(i)+choice);

You are trying to assign a value to a method return. This is not possible in Java.
Strings are immutable in Java - if you'd like to replace a value in a String, you must build a new String and resassign the reference that points to the old String to instead point to the new String.
There may be other issues that I have not had a chance to get to, but I believe this is the real issue. I don't fully understand what you're trying to do, so unfortunately I can't make a suggestion for what you should use instead.

A: Building on @corsiKa's answer, I suggest the following. First, convert your input string into a char[]:
char[] array = inp.toCharArray();

Now you can iterate over the array and modify its contents:
array[i] = array[i] + choice;

And, at the end, you can build your output string from that array:
output.setText(new String(array));


text:
Q: How to create many similar ViewControllers I would like to make a simple ViewController with two or three Buttons and labels. When I press the Button it plays an audio file.
I want to make hundreds of this similar screen, what is the best way to create it? (I am currently creating it with MainStoryBoard.)
For each page I would like to make small changes such as Buttons sizes ,Buttons numbers, label texts and audio files.
Drawing text bubbles or using xib file might be good, but I am not sure what I should.

A: You first need to have your own class for this UIViewController as a base class that has buttons, labels, etc.
Then use Factory Design pattern to generate the inherited UIViewController class which allows you to do some tweak that fits you need.
Factory Design Pattern
BaseViewController {
    UIButton *button1;
    UIButton *button1;
    UILabel *label1;
}

ChildViewControllerA : BaseViewController {
    UIButton *button3
}

ChildViewControllerB : BaseViewController {
    UIButton *button4
}

Factory : NSObject {
    + (BaseViewController)generateChildViewController: (int) type {
        switch (type)
            case 0:
                return [[ChildViewControllerA alloc] init];
            case 1:
                return [[ChildViewControllerB alloc] init];
     }
}

Main {
    - (void)createThreeViewControllers {
        BaseViewController *vc1 = [Factory generateChildViewController:0];
        vc1.button1.backgroundColor = [UIColor blueColor];
        BaseViewController *vc2 = [Factory generateChildViewController:0];
        vc2.button2.center = cgpointmake (100, 150);
        BaseViewController *vc3 = [Factory generateChildViewController:0];
        vc3.label1.text = @"vc3 test";
    }
}


text:
Q: Cannot construct a Request with a Request whose mode is 'navigate' and a non-empty RequestInit Consider this sample index.html file.
<!DOCTYPE html>
<title>test page</title>

test page

Using this Service Worker, designed to load from the cache, then fallback to the network if necessary.
cacheFirst = (request) => {
    var mycache;
    return caches.open('mycache')
        .then(cache => {
            mycache = cache;
            cache.match(request);
        })
        .then(match => match || fetch(request, {credentials: 'include'}))
        .then(response => {
            mycache.put(request, response.clone());
            return response;
        })
}

addEventListener('fetch', event => event.respondWith(cacheFirst(event.request)));

This fails badly on Chrome 62. Refreshing the HTML fails to load in the browser at all, with a "This site can't be reached" error; I have to shift refresh to get out of this broken state. In the console, it says:

Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'ServiceWorkerGlobalScope': Cannot construct a Request with a Request whose mode is 'navigate' and a non-empty RequestInit.

"construct a Request"?! I'm not constructing a request. I'm using the event's request, unmodified. What am I doing wrong here?

A: https://developers.google.com/web/ilt/pwa/caching-files-with-service-worker
var networkDataReceived = false;
// fetch fresh data
var networkUpdate = fetch('/data.json').then(function(response) {
  return response.json();
}).then(function(data) {
  networkDataReceived = true;
  updatePage(data);
});

// fetch cached data
caches.match('mycache').then(function(response) {
  if (!response) throw Error("No data");
  return response.json();
}).then(function(data) {
  // don't overwrite newer network data
  if (!networkDataReceived) {
    updatePage(data);
  }
}).catch(function() {
  // we didn't get cached data, the network is our last hope:
  return networkUpdate;
}).catch(showErrorMessage).then(console.log('error');

Best example of what you are trying to do, though you have to update your code accordingly. The web example is taken from under Cache then network.
for the service worker:
self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.open('mycache').then(function(cache) {
      return fetch(event.request).then(function(response) {
        cache.put(event.request, response.clone());
        return response;
      });
    })
  );
});

A: Based on further research, it turns out that I am constructing a Request when I fetch(request, {credentials: 'include'})!
Whenever you pass an options object to fetch, that object is the RequestInit, and it creates a new Request object when you do that. And, uh, apparently you can't ask fetch() to create a new Request in navigate mode and a non-empty RequestInit for some reason.
In my case, the event's navigation Request already allowed credentials, so the fix is to convert fetch(request, {credentials: 'include'}) into fetch(request).
I was fooled into thinking I needed {credentials: 'include'} due to this Google documentation article.

When you use fetch, by default, requests won't contain credentials such as cookies. If you want credentials, instead call:
fetch(url, {
  credentials: 'include'
})

That's only true if you pass fetch a URL, as they do in the code sample. If you have a Request object on hand, as we normally do in a Service Worker, the Request knows whether it wants to use credentials or not, so fetch(request) will use credentials normally.

A: Problem
I came across this problem when trying to override fetch for all kinds of different assets. navigate mode was set for the initial Request that gets the index.html (or other html) file; and I wanted the same caching rules applied to it as I wanted to several other static assets.
Here are the two things I wanted to be able to accomplish:

*

*When fetching static assets, I want to sometimes be able to override the url, meaning I want something like: fetch(new Request(newUrl))

*At the same time, I want them to be fetched just as the sender intended; meaning I want to set second argument of fetch (i.e. the RequestInit object mentioned in the error message) to the originalRequest itself, like so: fetch(new Request(newUrl), originalRequest)
However the second part is not possible for requests in navigate mode (i.e. the initial html file); at the same time it is not needed, as explained by others, since it will already keep it's cookies, credentials etc.
Solution
Here is my work-around: a versatile fetch that...

*

*can override the URL

*can override RequestInit config object

*works with both, navigate as well as any other requests

function fetchOverride(originalRequest, newUrl) {
  const fetchArgs = [new Request(newUrl)];
  if (request.mode !== 'navigate') {
    // customize the request only if NOT in navigate mode
    //    (since in "navigate" that is not allowed)
    fetchArgs.push(request);
  }

  return fetch(...fetchArgs);
}

A: In my case I was contructing a request from a serialized form in a service worker (to handle failed POSTs). In the original request it had the mode attribute set, which is readonly, so before one reconstructs the request, delete the mode attribute:
delete serializedRequest["mode"];
request = new Request(serializedRequest.url, serializedRequest);


text:
Q: Why isn't my content script block in my Edge extension working? I have a working extension for Chrome and Firefox and I tried to make it work in Microsoft Edge as well. for some reason the content script stuck on "runtime.sendMessage" function. I have using Edge 40.15063.
the Edge console says:
"API Call: 'runtime.sendMessage'"
"script block (9) (214,17)."
manifest.json:
{

  "manifest_version": 2,
  "name": "injecter",
  "version": "0.1.5.9",
  "author": "kovler",

  "description": "check the page url and then inject a code",
  "icons": {
    "48": "icons/icon32.png",
    "96": "icons/icon96.png"
  },
  "applications": {
    "gecko": {
      "id": "test@test.com",
      "strict_min_version": "45.0"
    }
  },
  "content_scripts": [{
    "matches": ["http://*/*", "https://*/*"],
    "js": ["edge.js", "content.js"]
  }],
  "background": {
    "scripts": ["edge.js", "constants.js", "promises.js", "main.js"],
    "persistent": true
  },
  "permissions": [
    "http://*/",
    "https://*/",
    "storage",
    "webNavigation",
    "tabs",
    "activeTab",
    "cookies",
    "webRequest",
    "webRequestBlocking"
  ],
  "-ms-preload": {
    "backgroundScript": "backgroundScriptsAPIBridge.js",
    "contentScript": "contentScriptsAPIBridge.js"
  }
}

edge.js:
if (typeof chrome == "undefined" || typeof chrome.runtime == "undefined")
    chrome = browser;

content.js:
(function(){

  function injectLocalScript (content, node) {
    var th = document.getElementsByTagName(node)[0];
    var s = document.createElement('script');
    s.setAttribute('type', 'text/javascript');
    s.innerHTML = content;
    th.appendChild(s);
  }

  function getAnswer(theMessageEvent) {
    if (theMessageEvent) {
      if (theMessageEvent.name === "Inject") {
        injectLocalScript(theMessageEvent.codeLine, 'body');
        console.log("injected");
      }
    }
  }

  chrome.runtime.sendMessage({ name: "injectionCompleted" }, getAnswer );

}());


text:
Q: @Query returning `Couldn't find PersistentEntity` when querying one column with null value Edited:
I also tested in the version 2.6.4 and still happens
I just upgraded spring-boot from 2.5.7 to 2.6.1 and I notice a change of behavior in a specific query. I'm trying to load only a specific column in a query, and when it's value in DB is null, it is throwing the Couldn't find PersistentEntity for type class java.lang.String! Exception.
This is my code in the Repository,
@Query("SELECT my_column " +
            " FROM mytable  " +
            " WHERE another_column = :secColumn " +
            " AND third_column = :thirdColumn")
    Optional<String> getMyColumn(@Param("secColumn") String secColumn,
                                 @Param("thirdColumn") String thirdColumn);
}

Observations:

*

*It works fine if the column it DB is not null

*It was working fine with a null value in DB for version 2.5.7

*If I return the whole entity inside the Optional, it works as expected

A: This is a bug in Spring Data JDBC which was already reported (and fixed).
The next set of releases should include that fix.


text:
Q: Recursive sequence with $\sin x$ and Taylor series I have been trying to solve that problem for two days but no answer yet. There it is:
there is a recursive sequence:
$a_{1}=1$
$a_{n+1}=\sin(a_{n})$
I am to proof that:
$$\lim_{n \to \infty} \sqrt{n}a_{n}=\sqrt{3}$$
What I know is that:
for $x>0: \sin(x) < x$
Thus:
$a_{2}=\sin(a_{1})<a_{1}<1$
$a_{3}=\sin(a_{2})<a_{2}<a_{1}<1$
$...$
$a_{n+1}=\sin(a_{2})<a_{2}<a_{1}<1$
Now we know that $a_{n}$ is decreasing. And from that and Banach's theorem we know that:
$\lim\limits_{n \to \infty}a_{n}=0$
However I have no idea how to proof the other limit.


text:
Q: Javascript undefined, empty strings, and if statements I am not some one who has done alot in javascript. My background is in Java/C++. I am currently working on a project that is using alot of javascript however and I came across something that doesn't make sense to me but hopefully some javascript guru out there can give me a nice logical explanation.
var noDefinition = undefined;
var emptyString = "";
var noDefinitionAndEmptyString = noDefinition + emptyString;

console.log("NoDefinition");
console.log(noDefinition);

console.log("EmptyString");
console.log(emptyString);

console.log("noDefinition+emptyString");
console.log(noDefinitionAndEmptyString);

console.log("************************");
if(noDefinition == undefined)
{
    console.log("No Definition is undefined");
}

if(emptyString == undefined)
{
    console.log("emptyString is undefined");
}

if(noDefinitionAndEmptyString == undefined)
{
    console.log("noDefiniton and emptyString is undefined");
}

The code above produces the following results in my console:
 [INFO] NoDefinition
 [INFO]
 [INFO] EmptyString
 [INFO]
 [INFO] noDefinition+emptyString
 [INFO] undefined
 [INFO] ************
 [INFO] No Definition is undefined
So as you can see when I output the variables noDefinition and emptyString to the console, it produces blank output. When I concatenate them the console will produce undefined. However if I then proceed to use an if statement and compare each of them to undefined. The only if that executes is the first one.
This occurs even though when put to a console the value just shows up blank. Also     the concatenation which shows up as undefined in the console fails its compare against undefined and never executes.  I am confused by this and I am hoping out there some one can give me an explanation about what is going on.

A: *

*console.log doesn't print anything when it receives a undefined value (implementation-specific).

*When you concatenate undefined with an empty string, the resulting value is "undefined". That's printed.

The previous bullet points explain your observations.

A: When you concatenate undefined with a string it becomes a string
var foo = undefined;
var bar = "";
console.log(foo+bar, typeof(foo+bar));
* output *
undefined string

ECMAScript Docs - http://www.ecmascript.org/docs.php
Not sure but reading the doc on Page 141 you can find this

15.5.1 The String Constructor Called as a Function
When String is called as a function rather than as a constructor, it performs a type
  conversion.

Which lets me to believe why concatenation of anything with a string outputs a string

A: Rewriting your example might shed more light on what actually happens when concatenating a string and an undefined value:
var noDefinition = undefined;
var emptyString = "";
var noDefinitionAndEmptyString = noDefinition + emptyString;
console.log("************************");
console.log("NoDefinition:" + " " + noDefinition + " " + typeof(noDefinition));

console.log("EmptyString:"+ " " + emptyString + " " + typeof(emptyString));

console.log("noDefinition+emptyString: " + noDefinitionAndEmptyString + " " + typeof(noDefinitionAndEmptyString));

console.log("************************");

Results in:
************************
NoDefinition: undefined undefined
EmptyString: string
noDefinition+emptyString: undefined string
************************

A: Use this instead:
if (typeof noDefinition == "undefined") ...

A: noDefinitionAndEmptyString is actually a string (you can use console.info(typeof noDefinitionAndEmptyString)) and its value is 'undefined'. This happens because of the concatenation - an implicit cast to string occurs, and undefined variable, casted to string, is the string 'undefined'

A: if(noDefinition == null) covers typeOf 'undefined' and typeOf 'null', but you may want to add an and statement to make sure it's just not an empty string... like so:
if(noDefinitionAndEmptyString == null || noDefinitionAndEmptyString == "")


text:
Q: jquery ui selecting data range using datepicker I am using the jquery datepicker.
So i am enabling the users to select a checkin date.
From general knowledge, you can't select a check out date earlier than the check in date.
I have been trying to set the check out date outmatically as soon as the user selects the checkout date and make sure it is at least a day after.
That is, if the user selects the date to be 07/23/2014 then the checkout field should be automatically set to 07/24/2014 before the user changes.
The code below does not seem to do that.. please help
$('#checkindate').datepicker(
{
    showButtonPanel: true,
    minDate:0,
     onClose: function(selectedDate)
    {
        $( "#checkoutdate" ).datepicker("option","minDate",selectedDate);
        alert(selectedDate+"1D");
    }
});

A: In the following sample I got 2 datetime selectors like you, I edited with the name of your items:
var startDateTextBox = $('#checkindate');
var endDateTextBox = $('#checkoutdate');

// Start-End Date pickers
startDateTextBox.datepicker({
    // Update other date from selection
    onClose: function (dateText, inst) {
        var testStartDate = startDateTextBox.datepicker('getDate');
        if (endDateTextBox.val()) {
            var testEndDate = endDateTextBox.datepicker('getDate');
            if (testStartDate > testEndDate)
                endDateTextBox.datepicker('setDate', testStartDate);
        }
        else {
            endDateTextBox.datepicker('setDate', testStartDate);
        }
    },
    onSelect: function (selectedDate) {
        endDateTextBox.datepicker('option', 'minDate', startDateTextBox.datepicker('getDate'));
    }
});

endDateTextBox.datepicker({
    // Update other date from selection
    onClose: function (dateText, inst) {
        var testStartDate = startDateTextBox.datepicker('getDate');
        if (startDateTextBox.val()) {
            var testEndDate = endDateTextBox.datepicker('getDate');
            if (testStartDate > testEndDate)
                startDateTextBox.datepicker('setDate', testEndDate);
        }
        else {
            startDateTextBox.datepicker('setDate', testStartDate);
        }
    },
    onSelect: function (selectedDate) {
        startDateTextBox.datepicker('option', 'maxDate', endDateTextBox.datepicker('getDate'));
    }
});


text:
Q: How to get access token from Yammer without user login? Here is Yammer Docs: https://developer.yammer.com/
When I try to make a request via browser, successfully I'm able to get access token
https://www.yammer.com/oauth2/authorize?client_id=[:client_id]&response_type=code&redirect_uri=[:redirect_uri]
However I must do it programmatically. So While my API is making a request to any endpoint of Yammer, should generate a new access token if access token expires. But I came across the following screenshot:

I think about headers of my request. I've added some headers (user agent)
    public function getCode(Request $request)
{
    $code = $request->get('code');

    $client = new \GuzzleHttp\Client();

    if (!is_null($code)) {
        $res = $client->request(
          'GET',
          'https://www.yammer.com/oauth2/access_token.json?client_id='.$this->clientId.'&client_secret='.$this->clientSecret.'&code='.$code
        );
        echo $res->getBody();
    }else {
        $res = $client->request(
          'GET',
          'https://www.yammer.com/oauth2/authorize?client_id='.$this->clientId.'&response_type=code&redirect_uri='.$this->redirectUri,
          [
              'headers' => [
                  'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'
              ]
          ]
        );

        echo $res->getBody();
    }
}

P.S: redirect uri was the same action for my sample code.

A: After making a request try the below code instead of  echo $res->getBody();
$response =json_decode($res->getBody(), true);
return $response;


text:
Q: Android Kernel Drivers for Camera Device I have a problem interfacing a video decoder(tvp5150) as a camera to a android samsung dev-kit works on FIMC API.
As far as I goggled the decoders do work as camera interface for composite cameras. I added the drivers in the kernel from menuconfig , updated the board file, but when I launch the DEFAULT CAMERA application the drivers are never initialized however the device was probed successfully.
All I can see is black screen and no vsync/hsync on chip.
My questions are

*

*do I need to use a custom application in user-space that opens the new camera device.

*do I need to add driver information in framework or other layers as well like kernel layer

*do I need to add configuration in ioctl functions too.

*what is mem2mem_test_dev.c in /kernel/drivers/media/video/  for. virtual camera test pattern? if yes how can I use it in android?

*what did I missed here i am new to kernel and clueless what else to do after adding kernel drivers

I need some help and some detailed examples if possible.

A: You need to write/port camera HAL (libcamera) - see TI porting guide http://processors.wiki.ti.com/index.php/TI-Android-DevKit-Camera_Porting_Guide


text:
Q: Xamarin Forms Custom Composite Control for Picker with Filter I am creating a custom composite component with an entry field and a list and I am having problems figuring out how to set up the bindable properties to display the items in the list. The purpose of the component is to be a filterable picker for lists that have hundreds or thousands of items. The idea is that this will control will be similar to the modal popup of a picker, but with a filter above the list. I can do this on a page, but am having difficulty doing this as a re-usable custom control with bindable properties. Here is what it looks like on a page:

To reduce the complexity I was planning on the component just being what you see in the modal popup, rather than having the two parts of the picker control--the entry-like part that you see on the page as well as the modal popup. So the control XAML is just for the modal popup and is fairly simple:
<?xml version="1.0" encoding="UTF-8"?>
<Grid xmlns="http://xamarin.com/schemas/2014/forms"
      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
      xmlns:yummy="clr-namespace:Xamarin.Forms.PancakeView;assembly=Xamarin.Forms.PancakeView"
      xmlns:localeffects="clr-namespace:ReceivingApp.Effects"
      xmlns:localcontrols="clr-namespace:ReceivingApp.Controls"
      x:Class="ReceivingApp.Controls.FilterPicker"
      RowSpacing="0"
      ColumnSpacing="0">

    <Grid.RowDefinitions>
        <RowDefinition Height="24"/>
        <RowDefinition Height="64"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="32"/>
    </Grid.RowDefinitions>

    <Label x:Name="PlaceholderLabel" HorizontalOptions="StartAndExpand" />

    <!-- filter -->
    <localcontrols:PancakeEntry x:Name="FilterEntry" Grid.Row="1" Margin="0,8"  />

    <!-- list -->
    <yummy:PancakeView Grid.Row="2"
                       BackgroundColor="#F9F9F9"
                       Margin="0,0,0,16"
                       Padding="8, 2, 8, 2"
                       BorderColor="#D3D3D3"
                       BorderThickness="1"
                       CornerRadius="8"
                       VerticalOptions="FillAndExpand"
                       >
        <ListView x:Name="ListPicker"
                  Margin="0,12"
                  HorizontalOptions="FillAndExpand"
                  SeparatorVisibility="None">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Grid>
                            <Label x:Name="LabelDisplayItem" />
                        </Grid>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </yummy:PancakeView>

    <Button Text="CANCEL" Grid.Row="3" HorizontalOptions="End" WidthRequest="100" Command="{Binding FilterPickerCancelCommand}"/>
</Grid>

The problem is that there is a ListView in the control and I need to set its ItemsSource BindableProperty to that of the ItemsSource BindableProperty of the control, which is fine. But how do I also include a BindableProperty that is the field to display in the ListView--the LabelDisplayItem.Text? There will only be one field displayed and it is in the context of the object that is the list of objects displayed by the ListView.
Here is the code-behind that doesn't work that shows what I am trying to do with the ItemsSource and DisplayField BindableProperties.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace ReceivingApp.Controls
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class FilterPicker : Grid
    {
        public static readonly BindableProperty DisplayFieldProperty =
            BindableProperty.Create(nameof(DisplayField)
                , typeof(string)
                , typeof(FilterPicker)
                , default(string)
                , BindingMode.OneWay);

        public static readonly BindableProperty ItemsSourceProperty =
           BindableProperty.Create(nameof(ItemsSource)
               , typeof(IEnumerable)
               , typeof(FilterPicker)
               , default(IEnumerable)
               , BindingMode.TwoWay);

        // Other BindableProperties go here such as PlaceholderProperty

        public IEnumerable ItemsSource
        {
            get => (IEnumerable)GetValue(ItemsSourceProperty);
            set => SetValue(ItemsSourceProperty, value);
        }

        public string DisplayField
        {
            get => (string)GetValue(DisplayFieldProperty);
            set => SetValue(DisplayFieldProperty, value);
        }

        // Other properties here

        protected override void OnPropertyChanged(string propertyName = null)
        {
            base.OnPropertyChanged(propertyName);

            if (propertyName == DisplayFieldProperty.PropertyName)
            {
                //how to get the appropriate context to set the LabelDisplayItem?
                LabelDisplayItem.Text = [bind this to the display field]
            }

            else if (propertyName == ItemsSourceProperty.PropertyName)
            {
                ListPicker.ItemsSource = ItemsSource;
            }
        }

        // Other code to use Linq to filter the values of the List -- resetting the ItemSource to the filtered list.

    }
}

It is no problem to do this on an individual page because I know the object in the ListView that I am working with and can bind to the appropriate field of the object to display it. But I haven't been able to figure out how to do this as a re-usable control.
Thoughts and ideas are appreciated.

A: One technique for solving such problems, is to pass in to the custom control an Action that can do what you need.
Also, instead of attempting to manipulate a UI item directly, manipulate its model.
Suppose the "consumer" (of your custom control) has a model list List<MyModel> Models;.
And MyModel has a string that is bound to the UI item to be changed:
public class MyModel : ObservableObject
{
    public string MyString
    {
        get => _myString;
        set { _myString = value; OnPropertyChanged(); }
    }
    private string _myString;

    public Action<string> GetActionThatSetsMyString()
    {
        return (value) => MyString = value;
    }
}

Then if, in the consumer, this is the model to be changed:
MyModel model = Models[i];
You could set a property on custom control, to the needed action:
public Action<string> UseChangedString { get; set; }
...
myControl.UseChangedString = model.GetActionThatSetsMyString();
...
// When you have a new value for string:
UseChangedString(newValue);