text:
Q: How to create dictionary from multiple list of string? I want to create a dictionary from list of strings. For example I have these list
AAAA
AAAA
AAAA
BBBB
BBBB
CCCC
CCCC
CCCC
....
Then I want to create a dictionary with numbering value from that, how to do that?
I explored some code but still have no idea
import os
path = "directoryA"
dirList = os.listdir(path)

with open("check.txt", "w") as a:
    for path, subdirs, files in os.walk(path):
        for filename in files:
            # I have splitted the text and now I want to create dictionary
            #from it

            mylist = filename.split("_") # the text format is AAAA_0 and I split
                                         #it so I can have list of 'AAAA' and '0'

            k = mylist[0] #I only take 'AAAA' string after splitting
            print(k) # here the output only give text output. From this I want to
                     # put into dictionary

This is the output after print(k) and these are not list
AAAA
AAAA
AAAA
BBBB
BBBB
CCCC
CCCC
CCCC
....
This is my expected result
myDic ={
    'AAAA': 0,
    'BBBB': 1,
    'CCCC': 2,
    'DDDD': 3,
    # ... and so on
}

A: Assuming the contents of check.txt looks like li, start by getting all unique elements in your list of strings  by using a set, and then sort the unique list alphabetically
After that, use dictionary comprehension and enumerate to generate your dictionary
li = [
    "AAAA",
    "AAAA",
    "AAAA",
    "BBBB",
    "BBBB",
    "CCCC",
    "CCCC",
    "CCCC"]

#Get the list of unique strings by converting to a set
li = (list(set(li)))

#Sort the list lexicographically
li = sorted(li)

#Create your dictionary via dictionary comprehension and enumerate
dct =  {item:idx for idx, item in enumerate(li)}
print(dct)

The output will be
{'AAAA': 0, 'BBBB': 1, 'CCCC': 2}

We should be able to create the list of strings li like so
import os
path = "directoryA"
dirList = os.listdir(path)
li = []

with open("check.txt", "w") as a:
    for path, subdirs, files in os.walk(path):
        for filename in files:
            # I have splitted the text and now I want to create dictionary
            #from it

            mylist = filename.split("_") # the text format is AAAA_0 and I split
                                         #it so I can have list of 'AAAA' and '0'

            k = mylist[0]
            #append item to li
            li.append(k)

A: You can use itertools.groupby to group the strings assuming they are sorted as you have them (it not, sort them first). Then enumerate() over the groups which will give you the count:
from itertools import groupby
l = [
    "AAAA",
    "AAAA",
    "AAAA",
    "BBBB",
    "BBBB",
    "CCCC",
    "CCCC",
    "CCCC"]

d = {key:i for i, (key, group) in enumerate(groupby(l))}
# {'AAAA': 0, 'BBBB': 1, 'CCCC': 2}

If you are reading from a file and the strings are not sorted, you can add an entry and increment each time you find something not yet in the dict. The values will be sorted based on the first time you see a given string. For example:
from itertools import count, filterfalse

i = count(1)
d = {}

with open('test.txt') as f:
    for line in filterfalse(lambda l: l.strip() in d, f):
        d[line.strip()] = next(i)

A: You can use dict.fromkeys() to build a dict and count() to fill values:
from itertools import count

lst = ["AAAA", "AAAA", "AAAA", "BBBB", "BBBB", "CCCC", "CCCC", "CCCC"]

dct = dict.fromkeys(lst)
c = count()

for key in dct:
    dct[key] = next(c)

print(dct)
# {'AAAA': 0, 'BBBB': 1, 'CCCC': 2}

A: Assuming keys of dictionary are :
keys = ['A', 'B', 'C']

Then:
id = range(len(keys))
d = dict(zip(keys, id))

A: I would do it following way:
data = ['A','A','A','B','B','C','C','D','C']
unique = [i for inx,i in enumerate(data) if data.index(i)==inx]
print(unique) # ['A', 'B', 'C', 'D']
d = {(i,inx) for inx,i in enumerate(unique)}
print(d) # {('D', 3), ('A', 0), ('B', 1), ('C', 2)}

Idea behind this method might be described as: get value from list only if it occurs first time (same value did not appear earlier). I utilized fact that .index method of list, always returns lowest value possible. Note that in this method same values do not have to be neighbors.

A: first you have to remove duplicates based on this answer:
How do you remove duplicates from a list whilst preserving order?
so it will be like this:
def f7(seq):
    seen = set()
    seen_add = seen.add
    return [x for x in seq if not (x in seen or seen_add(x))]

l = [
"AAAA",
"AAAA",
"AAAA",
"BBBB",
"BBBB",
"CCCC",
"CCCC",
"CCCC"]

#first remove duplicates
s = f7(l)

#create desired dict
dict(zip(s,range(len(s))))
#{'AAAA': 0, 'CCCC': 1, 'BBBB': 2}


text:
Q: How can i get the profile picture of a user who have registered my website via the facebook social plugin I have a registration plugin embeded via an iframe on my website, The registration plugin works fine , I am also able to get the unique user_id of each user by using the following line of code in the signed_request file which can be located here
The line of code i use to get the user_id is: $response["user_id"];
Now that i have a unique id of each user, i want a way by which i can get the link to the profile image of that user, i know i can get the thumbnail of the profile picutre
using open graph,
But i am looking for a way by which i can get the link to the complete or the original profile picture, not the thumbnail.
Is there a way this can be done? Using open graph or something like that?

A: You need user_photos permissions first. Then something like this should do it:
SELECT cover_object_id FROM album WHERE owner=me() and type='profile'

Substitute me() with the user you are querying for.
It returns the photo object that you can then use to pull the full version from.

A: Make an API call to /user_id/?fields=picture using the access_token in the same signed_request

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to capture screenshot from FrameBuffer? I want to capture screenshot from FrameBuffer in Android, I use the code below, but just got a fuzzy image.I contains 3 main steps. first, read data and info from FrameBuffer, second, convert the raw data to 24 bits, third, construct the BITMAP structs and write to bmp file. But I got fuzzy images, does anyone could help?I will appreciate it.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/ioctl.h>

typedef unsigned char BYTE;
typedef unsigned short WORD;
typedef unsigned int DWORD;
typedef long LONG;

typedef struct tagBITMAPFILEHEADER {
    WORD  bfType;
    DWORD bfSize;
    WORD  bfReserved1;
    WORD  bfReserved2;
    DWORD bfOffBits;
}__attribute__((packed)) BITMAPFILEHEADER, *PBITMAPFILEHEADER;

typedef struct tagBITMAPINFOHEADER {
    DWORD biSize;
    LONG  biWidth;
    LONG  biHeight;
    WORD  biPlanes;
    WORD  biBitCount;
    DWORD biCompression;
    DWORD biSizeImage;
    LONG  biXPelsPerMeter;
    LONG  biYPelsPerMeter;
    DWORD biClrUsed;
    DWORD biClrImportant;
}__attribute__((packed)) BITMAPINFOHEADER, *PBITMAPINFOHEADER;

typedef struct tagRGBQUAD {
    BYTE rgbBlue;
    BYTE rgbGreen;
    BYTE rgbRed;
    BYTE rgbReserved;
}__attribute__((packed)) RGBQUAD;

#define FRAME_BUFFER_PATH                "/dev/graphics/fb0"

int take_screenshot(char *path)
{
    int i;
    int img_fd, fb_fd;
    int data_size;
    char *img_buf;
    struct fb_var_screeninfo var_info;
    struct fb_fix_screeninfo fix_info;
    BITMAPFILEHEADER file_head;
    BITMAPINFOHEADER info_head;
    //RGBQUAD rgb_quad;

    /*open files*/
    fb_fd = open(FRAME_BUFFER_PATH, O_RDWR);
    if (img_fd < 0) {
            perror("open framebuff");
            return -1;
    }
    if (ioctl(fb_fd, FBIOGET_VSCREENINFO, &var_info) < 0) {
            perror("ioctl FBIOGET_VSCREENINFO");
            close(img_fd);
            return 0;
    }
    printf("xres %d, yres %d\n", var_info.xres, var_info.yres);

    if (ioctl(fb_fd, FBIOGET_FSCREENINFO, &fix_info)){
      debug("Error reading fixed information\n");
      close(img_fd);
            return 0;
    }

    img_fd = open(path, O_RDWR | O_CREAT, 0644);
    if (img_fd < 0)
    {
            perror("open image");
            close(img_fd);
            return -1;
    }

    data_size = var_info.xres*var_info.yres*(var_info.bits_per_pixel/8);
    /*initialize bmp structs*/
    file_head.bfType = 0x4d42;
    file_head.bfSize = sizeof(file_head) + sizeof(info_head) + data_size;
    file_head.bfReserved1 = 0;
    file_head.bfReserved2 = 0;
    file_head.bfOffBits = sizeof(file_head) + sizeof(info_head);

    info_head.biSize = sizeof(info_head);
    info_head.biWidth = var_info.xres;
    info_head.biHeight = -var_info.yres;
    info_head.biPlanes = 0;
    info_head.biBitCount = 24;
    info_head.biCompression = 0;
    info_head.biSizeImage = data_size;
    info_head.biXPelsPerMeter = 3780;
    info_head.biYPelsPerMeter = 3780;
    info_head.biClrUsed = 0;
    info_head.biClrImportant = 0;

    img_buf = (char *)malloc(data_size);
    if (img_buf == NULL)
    {
            printf("malloc failed!\n");
            close(fb_fd);
            close(img_fd);
            return -1;
    }

  /*read img data and */
  read(fb_fd, img_buf, data_size);

  write(img_fd, &file_head, sizeof(file_head));
  write(img_fd, &info_head, sizeof(info_head));

/*********************/
  int w, h;
  int depth;
  unsigned short *bits;

  w = var_info.xres;
  h = var_info.yres;
  depth = var_info.bits_per_pixel;

  uint8_t *rgb24;
  if (depth == 16) {
      rgb24 = (uint8_t *)malloc(w * h * 3);
      int i = 0;
      for ( ; i < w*h; i++) {
          uint16_t pixel16 = ((uint16_t *)img_buf)[i];
          // RRRRRGGGGGGBBBBBB -> RRRRRRRRGGGGGGGGBBBBBBBB
          // in rgb24 color max is 2^8 per channel (*255/32 *255/64 *255/32)
          rgb24[3*i+0]   = (255*(pixel16 & 0x001F))/ 32;    //Blue
          rgb24[3*i+1]   = (255*((pixel16 & 0x07E0) >> 5))/64;  //Green
          rgb24[3*i+2]   = (255*((pixel16 & 0xF800) >> 11))/32;   //Red
      }
  } else if (depth == 24) {
      rgb24 = (uint8_t *)img_buf;
  } else if (depth == 32) {
      //skip transparency channel
      rgb24 = (uint8_t *) malloc(w * h * 3);
      int i=0;
      for ( ; i <w*h; i++) {
          uint32_t pixel32 = ((uint32_t *)img_buf)[i];
          // in rgb24 color max is 2^8 per channel
          rgb24[3*i+2]   =  pixel32 & 0x000000FF;     //Blue
          rgb24[3*i+1]   = (pixel32 & 0x0000FF00) >> 8; //Green
          rgb24[3*i+0]   = (pixel32 & 0x00FF0000) >> 16;  //Red
      }
  } else {
  };

  write(img_fd, rgb24, w*h*3);

  close(fb_fd);
  close(img_fd);
  return 0;
}

A: Sometime the framebuffer's row size will be larger than the resolution. So you shouldn't use the xres to determine where the next line begins. There is a total memory size attribute saved in the fixed info, so you could divide it with the yres. There is also a row-stride attribute but I'm not sure whether it works. Maybe you could try it.


text:
Q: Mysql - Help for optimizing query I have this query:
SELECT bi.id,
       bi.location,
       bi.expense_group,
       bi.level,
       bi.is_active,
       bi.type,
       full_name,
       ( bl.bud_amount )                                     AS BudgetAmount,
       ( COALESCE(( ( bl.bud_amount * 3 ) - (
                    + bal.bal_amount1 + bal.bal_amount2
                    + bal.bal_amount3 ) ), 0) ) AS Difference,
       ( COALESCE(Round(( + bal.bal_amount1 + bal.bal_amount2
                          + bal.bal_amount3 ) / 3), 0) )     AS Average,
       bal.bal_amount1                                       AS BAL1,
       bal.bal_amount2                                       AS BAL2,
       bal.bal_amount3                                       AS BAL3
FROM   (SELECT *
        FROM   budget_items bi
        WHERE  bi.location IS NOT NULL) AS bi
       LEFT JOIN (SELECT budget_item_id,
                         Sum(CASE
                               WHEN budget_id = 21491 THEN amount
                             END) AS bud_amount
                  FROM   budget_lines
                  GROUP  BY budget_item_id) AS bl
              ON bl.budget_item_id = bi.id
       JOIN (SELECT budget_item_id,
                    Ifnull(Sum(CASE
                                 WHEN balance_id = 12841 THEN amount
                               END), 0) AS bal_amount1,
                    Ifnull(Sum(CASE
                                 WHEN balance_id = 18647 THEN amount
                               END), 0) AS bal_amount2,
                    Ifnull(Sum(CASE
                                 WHEN balance_id = 18674 THEN amount
                               END), 0) AS bal_amount3
             FROM   balance_lines
             GROUP  BY budget_item_id) AS bal
         ON bal.budget_item_id = bi.id
ORDER  BY bi.location

It takes a lot of time. In the budget_lines and balance_lines tables I have more than 5,000,000 rows in each.
I also attach the EXPLAIN of the query, so you'll ne able to see the problem.
All ids in every table are indexed. Is there any column that if would be indexed spped up the query? Or maybe I need to change it.
*** LEFT JOIN is necessary because I need to get all the items from nudget_items, even if they don't exist in the balance/budget_line table.
Schema is: every budget has its budget_lines. Every balance has its balance_lines. The query is aimed to have ONE table to summarize the differences between a budget and several balances.

You can see a bigger image here: http://i.stack.imgur.com/dlF8V.png
EDIT:
After @Sebas answers:

For @sabes hunger, I put here the DESCRIBE:
budget_items

budget_lines

balance_lines

A: Maybe something like this; but without sample data, and indexes it's difficult to see
SELECT *
FROM   budget_items bi
WHERE  bi.location IS NOT NULL) AS bi
INNER JOIN  --Added inner for clarity  -changed order I just like my inner's before my outers.
  (SELECT budget_item_id, Sum(CASE WHEN balance_id = 12841 THEN coalesce(amount,0) END), 0) AS bal_amount1,
                          Sum(CASE WHEN balance_id = 18647 THEN coalesce(amount,0) END), 0) AS bal_amount2,
                          Sum(CASE WHEN balance_id = 18674 THEN coalesce(amount,0) END), 0) AS bal_amount3
   FROM   balance_lines
   WHERE balance_ID in (12841, 18647, 18674) --This way balance_IDs which aren't in this list don't even get evaluated
   GROUP  BY budget_item_id) AS bal
 ON bal.budget_item_id = bi.id
LEFT JOIN
 (SELECT budget_item_id, Sum(CASE WHEN budget_id = 21491 THEN coalesce(amount,0) END) AS bud_amount
  FROM   budget_lines
  WHERE budget_Id = 21491 --Again since we only care about anything but budget_ID 21491, we can limit the results to JUST that
  GROUP  BY budget_item_id) AS bl
 ON bl.budget_item_id = bi.id


text:
Q: How many images do I need to train a Deep Neural Network I am currently working on a small program that is trying to determine whether an apple is rotten or not. To start this off, I followed TensorFlow's MNIST tutorial which would identify a handwritten digit. From what I heard, MNIST contains 60,000 or so images to train my neural network. If I were to train my neural network to identify either 1 or 0, rotten or not, if an apple is rotten or not, how many images would I need in a csv to teach it? If I need over a thousand images, is there a way I can crawl through images from google to find what I need?

A: I'd say you could get away with less than 1000 images per class if you use Google's Inception classifier as a starting point. You can find a very gentle tutorial here.


text:
Q: Electron : How to show chrome extension on Address bar? I have added extension in my Electron App Code. But How can I check or debug my code whether my extension installed or not.
I have added Below code to add extension
BrowserWindow.addExtension('/home/raman/Downloads/extension/');


text:
Q: watching promise with $watch I build a directive that have attribute that point on promise. and when promise resolved i want to running a function that do something with the data. like that :
 scope.$watch('source', function (dataSource) {
               if( !dataSource ) return ;
               dataSource.then(function ( d ) {
                   dataToView( d );
               });
           });

but there a problem . source can change multiple times in a very short time and every time I register a handler to current promise.
so for example if source changed 3 times dataToView() called 3 times! for promises that not any more relevant .
what I realy want is to call dataToView() just when the promise binding to source resolved .
anyone have idea how to solved that ?

A: You need somekind of cancelable callback,
you can do this that way:
 scope.$watch('source', function (dataSource) {
    if( !dataSource ) return ;
    var currentCallbackId = Date.now();
    dataSource.then(function (myId, d ) {
        if (myId !== currentCallbackId) {
            return;
        }

       dataToView( d );
    }.bind(null, currentCallbackId));
});

Explanation:
You generate to each callback unique id, that the callback aware to when it invoked. (using bind that passes it as the first param to the callback)
You save the latest callback id in a closure var (can be also on the 'this') and when the callback invoked, it checks if its still relevant

A: I find a simplest solution :
scope.$watch('source.$$state.value', function (data) {
    if( !data ) return ;
    dataToView( data );
});

that make sure I not register to anyting but get the fresh Data when it done on the current source


text:
Q: How to remove data frame header and make it a row I am using tabula to read tables form pdf files.
tables = tabula.read_pdf(file, pages="all")

This works fine. Now tables is a list of dataframes, where each data frame is a table fromt eh pdf file.
However the table rows are indexed 0,1,2,3.. etc. But the first row is taken as the column name or header of each dataframe.
Current dataframe:
  Component manufacturer               DMNS
0         Component name               KL32/OOH8
1         Component type               LTE-M/NB-IoT
2       Package markings               <pin 1 marker>\ ksdc 99cdjh
3              Date code               Not discerned
4           Package type               127-pin land grid array (LGA)
5           Package size               26.00 mm × 10.11 mm × 3.05 mm

Desired Dataframe:
        0                                1
0       Component manufacturer           DMNS
1       Component name                   KL32/OOH8
2       Component type                   LTE-M/NB-IoT
3       Package markings                 <pin 1 marker>\ ksdc e99cdjh
4       Date code                        Not discerned
5       Package type                     127-pin land grid array (LGA)
6       Package size                     26.00 mm × 10.11 mm × 3.05 mm

How can I do this transformation?

A: As the tabula docs on read_pdf state, you can add pandas_options and they even give the one you need as an example - {'header': None}. So (something like) this should do the trick:
tabula.read_pdf(file, pages="all", pandas_options={'header': None})

Edit: So apparently that should only work if you set multiple_tables to False which is not the default. I'd play with the options a bit and if it doesn't give the desired result, here is a post on how to turn the column names into the first row.

A: Here's a way to do what your question asks:
df = df.T.reset_index().T.reset_index(drop=True)

Output:
                        0                              1
0  Component manufacturer                           DMNS
1          Component name                      KL32/OOH8
2          Component type                   LTE-M/NB-IoT
3        Package markings    <pin 1 marker>\ ksdc 99cdjh
4               Date code                  Not discerned
5            Package type  127-pin land grid array (LGA)
6            Package size  26.00 mm × 10.11 mm × 3.05 mm

Explanation:

*

*Transpose the dataframe so we can use reset_index() to convert the index (i.e., the original column labels) to a new initial column

*Transpose it again so the new initial column becomes an initial row, and use reset_index() to get a fresh integer index.


text:
Q: Flutter: Gradle build failed to produce an .apk file. It's likely that this file was generated under \build, but the tool couldn't find it I am trying to test drive an app. I keep getting a strange issue with this problem as app fail to debug/run. SDK version is 28 while the rest is below:
Flutter 1.13.9-pre.79 • channel master • https://github.com/flutter/flutter.git
Framework • revision 9eb9ea0ffa (6 hours ago) • 2020-01-13 21:30:42 -0800
Engine • revision 0235a50843
Tools • Dart 2.8.0 (build 2.8.0-dev.0.0 28c335d5a2)

Gradle build failed to produce an .apk file. It's likely that this
  file was generated under C:\Development\\build, but the tool
  couldn't find it.

Is there a way to pass this issue or a configuration that can allow me to run by providing or giving the output path to Gradle? The .apk seems to generated as the error states.

UPDATE:
Android Studio -v 3.5.3
Gradle -v 3.4.2
Gradle Wrapper -v 5.1.1

A: I solved my problem by disabling split
splits {

    abi {

        enable false

    }
}

A: Added the flavor name in Build name from Edit Configurations and it worked!

A: Sometimes this issue happens when you have the following code mentioned in build.gradle file. Comment this code and try running the build and it succeeded for me. If you want to build multiple apk files please use them while taking release build and remove it for debug builds. From the screenshot you shared I can see multiple apk generated for you and commenting split apks will help you fix it.
splits {
    abi {
        enable true
        reset()
        include 'armeabi', 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
        universalApk true
    }
}

A: In my case, it was setting debuggable false in android app build.gradle that caused this issue. I agree not a lot of people are going to modify debuggable configuration, but it might help someone one day to reference this.
 buildTypes {
    debug {
        debuggable false <= causing problem
        ...
    }

A: I add the following section to app/build/gradle file , for I only need arm64-v8a versio apk,
splits {
    abi {
        enable true
        reset()
        include 'arm64-v8a'
        universalApk true
    }
}

then the error occurred, so my workaround to fix this just to make a symbol-link named app-debug.apk to the new named app-arm64-v8a-debug.apk in folder build/app/outputs/flutter-apk/
it works!

A: Add below code in to the app level build.gradle file after buildTypes:
flavorDimensions "flavor"

productFlavors {
    staging {
        dimension "flavor"
    }
}

And Modify your Edit Configurations like below Image :

A: Ok, I found that it's args in launch.json if you use vscode

A: After confirming the android/app/build.gradle have no issues related to flavor, please run command
flutter run --flavor dev lib/main_dev.dart

instead of
flutter run lib/main_dev.dart --flavor dev

A: in my case I have a multi flavor app like this:
update 04/15/2021:
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
            {
                    "name": "YOUR_PROJECT_NAME",
                    "program": "lib/main.dart",
                    "request": "launch",
                    "type": "dart",
                    "args": [
                            "--flavor",
                            "ADD_YOUR_FLAVOR_NAME_HERE" //development or staging or production
                        ]
            }
    ]

Another way:
 android {

    ...

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }

    flavorDimensions "flavor-type"

    productFlavors{
        development{
            dimension "flavor-type"
        }
        staging{
            dimension "flavor-type"
        }
        production{
            dimension "flavor-type"
        }
    }
}

So if you want to run app you have to write the flavor name and then the class name that hold main() function
flutter run --flavor staging -t lib/main_staging.dart

and I solved my error and built the .apk

A: In my case, the problem was that a module specific SDK was not set for my Android API module.
The solution I found is:
Open Android Studio->File->Project Structure->Project SDK box->set Android API

A: I don't know if it is gonna help you or not but I solved my problem by following solution-1.
Solution-1

Replace your project level build.gradle file with following replace
the versions and classpath with your own.
buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.3'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

The Most Important Part:
Make sure your are using two subprojects
 rootProject.buildDir = '../build'
 subprojects {
     project.buildDir = "${rootProject.buildDir}/${project.name}"
 }
 subprojects {
     project.evaluationDependsOn(':app')
 }

Source
Solution-2

*

*Try rebuilding your android files rename the android folder to
something else to deactivate it like "android-old" or whatever.

*Then, go in the parent folder of your project, and run below command
   flutter create --org your.organization <your appname>

This will rebuild any missing files.
That worked for me

A: After a day of struggling to figure out this problem I found where to start to really solve it. Before we insert random code we have to search what is the exact name of the apk it is generating.
Flutter Build Folder -> app -> outputs -> apk
here you will see exactly what the apk name is called if it is in release or debug mode.
In this case if the name has app-staging.apk or some other weird name there is something in your gradle build that is not working well. In my case it was because I had a flavor that was not needed with the name staging.
If this is not the case in your case, then surely it will always be some gradle setting to check. Try to change from release to debug mode
or the opposite from "launch.json", in this case you will be able to see if one side and the other not and understand the configuration differences.

A: I found out that these lines in build.gradle cause the issue
splits {
abi {
    enable true
    reset()
    include 'armeabi', 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
    universalApk true
}}

and also found out that we don't need it, to build split apk run
flutter build apk --split-per-abi

this will generate v7, v8a & x86_64 automatically

A: I found out that these lines in build.gradle cause the issue. Then I solved this problem set splits abi enable false
splits{
    abi{
        enable false
        reset()
        include "x86", "x86_64", "armeabi", "armeabi-v7a", "arm64-v8a"
        universalApk false
    }
}

A: Steps to follow.
1- cd your_project
2- flutter create .
3- finally flutter run

A: In my case, I don't add flavor section in gradle files at all. after a few times trying, finally I solved this by adding the following code in root build.gradle file:
rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
    project.evaluationDependsOn(':app')
}

A:
Adding the line in the image after the comment in the root android folder build.gradle in subprojects section solved the problem  for me
This is the line to add:
project.buildDir = "${rootProject.buildDir}/${project.name}"

A: As others suggested, in my case it was indeed a flavors issue. I checked out a fresh copy of my repo and tried running the app with default settings, which triggered this error. Turns out I forgot to edit my "Run/Debug Configurations", which are stored in Android Studio's settings (.idea/) that are not tracked by my repo. I needed to re-add my flavor options, which was as simple as adding a Flutter configuration (See Run > Edit Configurations... > + button in upper left corner) and specifying its dart entrypoint file+Build flavor name to be able to build anything.

A: Go to .vscode then open the launch.json file and add
{
   "name":"app name",
   "request":"launch",
   "type":"dart",
   "flutterMode":"debug",
   "program":"lib/'main of that flavor'",
   "args":[
      "--flavor",
      "<name of flavor'"
   ]
}


text:
Q: Error when checking target: expected activation_2 to have shape (512,) but got array with shape (1,) Having trouble with the error in the title. I do actually know why I'm receiving this error but after researching I struggle to understand the concept as I'm new to ML. The error is relating to not having X_TRAIN and Y_TRAIN but I'm unable to understand what they consist of. All images have been resized to the same dimensions. I'm using the CUB 2011 dataset with a split of 90:10 training/validation, here is my code below that relates to the error. I'm using Keras.
classifier.add(Conv2D(256, (3, 3), input_shape = (467,386,3)))
classifier.add(Activation('relu'))

#Smaller for precise pooling
classifier.add(MaxPooling2D(pool_size = (2, 2)))

classifier.add(Flatten())

#Add 512 unit layer
classifier.add(Dense(units = 512, activation = 'relu'))

A: The problem is in the discrepancy between your final Dense(512, ...) layer and the fact that your data targets are just 1 dimension. You can either fix by converting the model to output the expected dimensions, or adjust the data to the expected model outputs. That depends on what you are trying to achieve. To fix the model you can add another Dense layer:
classifier.add(Dense(units = 512, activation = 'relu'))
classifier.add(Dropout(0.2)) #prevent overfitting
classifier.add(Dense(units=1, activation='sigmoid')) # HERE ---

Or have a look at the what generator is outputting by print(next(train_generator)) to see why the target array is 1 dimensional.


text:
Q: Beamer justified numbering I am trying to follow the solution to give justified environments in beamer without needing to explicitly type justifying everywhere. However, I am not sure how to get the numbering correct, as the enumerate item should start at 1. (I have no idea how to do the description field as well, but that's an extra, as I rarely use it). I have tried naively adding a +1 where item occurs, but without success.

CODE / MWE
\documentclass{beamer}
\usepackage{ragged2e}
\usepackage{lipsum}

\makeatletter
\renewcommand{\itemize}[1][]{%
    \beamer@ifempty{#1}{}{\def\beamer@defaultospec{#1}}%
    \ifnum \@itemdepth >2\relax\@toodeep\else
    \advance\@itemdepth\@ne
    \beamer@computepref\@itemdepth% sets \beameritemnestingprefix
    \usebeamerfont{itemize/enumerate \beameritemnestingprefix body}%
    \usebeamercolor[fg]{itemize/enumerate \beameritemnestingprefix body}%
    \usebeamertemplate{itemize/enumerate \beameritemnestingprefix body begin}%
    \list
    {\usebeamertemplate{itemize \beameritemnestingprefix item}}
    {\def\makelabel##1{%
            {%
                \hss\llap{{%
                        \usebeamerfont*{itemize \beameritemnestingprefix item}%
                        \usebeamercolor[fg]{itemize \beameritemnestingprefix item}##1}}%
            }%
        }%
    }
    \fi%
    \beamer@cramped%
    \justifying% NEW
    %\raggedright% ORIGINAL
    \beamer@firstlineitemizeunskip%
}
\makeatother

% My attempt at getting enumerate working.
\makeatletter
\renewcommand{\enumerate}[1][]{%
    \beamer@ifempty{#1}{}{\def\beamer@defaultospec{#1}}%
    \ifnum \@itemdepth >2\relax\@toodeep\else
    \advance\@itemdepth\@ne
    \beamer@computepref\@itemdepth% sets \beameritemnestingprefix
    \usebeamerfont{itemize/enumerate \beameritemnestingprefix body}%
    \usebeamercolor[fg]{itemize/enumerate \beameritemnestingprefix body}%
    \usebeamertemplate{itemize/enumerate \beameritemnestingprefix body begin}%
    \list
    {\usebeamertemplate{enumerate \beameritemnestingprefix item}}
    {\def\makelabel##1{%
            {%
                \hss\llap{{%
                        \usebeamerfont*{enumerate \beameritemnestingprefix item}%
                        \usebeamercolor[fg]{enumerate \beameritemnestingprefix item}##1}}%
            }%
        }%
    }
    \fi%
    \beamer@cramped%
    \justifying% NEW
    %\raggedright% ORIGINAL
    \beamer@firstlineitemizeunskip%
}
\makeatother

\begin{document}
    \begin{frame}
        \begin{itemize}
            \item \lipsum[66]
        \end{itemize}
        \begin{enumerate}
            \item \lipsum[75]
        \end{enumerate}
        \begin{description}
            \item[Item] \lipsum[66]
        \end{description}
    \end{frame}
\end{document}

A: As the enumerate and description are different enough that "guessing" the code based on the itemize environment won't work - however you can find the all definitions in beamerbaselocalstructure.sty and modify them in the same way then itemize:
\documentclass{beamer}
\usepackage{ragged2e}
\usepackage{lipsum}

\makeatletter
\renewcommand{\itemize}[1][]{%
    \beamer@ifempty{#1}{}{\def\beamer@defaultospec{#1}}%
    \ifnum \@itemdepth >2\relax\@toodeep\else
    \advance\@itemdepth\@ne
    \beamer@computepref\@itemdepth% sets \beameritemnestingprefix
    \usebeamerfont{itemize/enumerate \beameritemnestingprefix body}%
    \usebeamercolor[fg]{itemize/enumerate \beameritemnestingprefix body}%
    \usebeamertemplate{itemize/enumerate \beameritemnestingprefix body begin}%
    \list
    {\usebeamertemplate{itemize \beameritemnestingprefix item}}
    {\def\makelabel##1{%
            {%
                \hss\llap{{%
                        \usebeamerfont*{itemize \beameritemnestingprefix item}%
                        \usebeamercolor[fg]{itemize \beameritemnestingprefix item}##1}}%
            }%
        }%
    }
    \fi%
    \beamer@cramped%
    \justifying% NEW
    %\raggedright% ORIGINAL
    \beamer@firstlineitemizeunskip%
}

\def\beamer@enum@{%
  \beamer@computepref\@itemdepth% sets \beameritemnestingprefix
  \usebeamerfont{itemize/enumerate \beameritemnestingprefix body}%
  \usebeamercolor[fg]{itemize/enumerate \beameritemnestingprefix body}%
  \usebeamertemplate{itemize/enumerate \beameritemnestingprefix body begin}%
  \expandafter
    \list
      {\usebeamertemplate{\beamer@enumtempl}}
      {\usecounter\@enumctr%
        \def\makelabel##1{{\hss\llap{{%
                \usebeamerfont*{enumerate \beameritemnestingprefix item}%
                \usebeamercolor[fg]{enumerate \beameritemnestingprefix item}##1}}}}}%
  \beamer@cramped%
  \justifying
%  \raggedright%
  \beamer@firstlineitemizeunskip%
}

\def\@@description{%
  \advance\beamer@descdefault by \labelsep%
  \usebeamerfont{description body}%
  \usebeamercolor[fg]{description body}%
  \usebeamertemplate{description body begin}%
  \list
  {}
  {\labelwidth\beamer@descdefault\leftmargin\beamer@descdefault\let\makelabel\beamer@descriptionitem}%
  \beamer@cramped%
%  \raggedright
\justifying
  \beamer@firstlineitemizeunskip%
}

\makeatother

\begin{document}
    \begin{frame}
        \begin{itemize}
            \item \lipsum[66]
        \end{itemize}
        \begin{enumerate}
            \item \lipsum[75]
        \end{enumerate}
        \begin{description}
            \item[Item] \lipsum[66]
        \end{description}
    \end{frame}
\end{document}


text:
Q: Why can we supply a Comparator to TreeSet but not something like Hasher to HashSet? In Java 6, my understanding is that you can supply a Comparator to a TreeSet when creating it to override the "natural ordering" of the objects in the set.
Do you have any thoughts why Java doesn't support supplying a "Hasher" that overrides the "natural hashing" of objects in the set as well?
EDIT:
Getting input from you might help me when designing APIs in the future.
Thanks.

A: A Hasher object would be redundant to the hashCode() method in the Object class.
If you want to effect the nature of the hashing, you should override the hashCode() method defined on Object.  Just be sure to override equals(Object) as well, since these two should always go together.
A HashSet or other similar data structure will use the objects hashCode() method to get a hash value to determine bin storage.  It will then use equals() to compare that object to other objects in the same bin to determine equality.
The hash code generated needs to be unique to that specific class of object.  This can be ensured simply by overriding the hashCode() method and doesn't need to change from implementation to implementation.  A Hasher object would just obfuscate and serve no additional purpose.  I couldn't think of a single use case where multiple hash codes would be needed for storage in different data structures.

A: Here are several likely reasons:

*

*Simplicity - most people don't need multiple hash functions, so to keep the API simple it makes sense to rely on a single Object.hashCode() approach

*Performance - In the standard library at least,
HashSets and HashMaps etc. need to be
pretty heavily optimised as they are
so widely used. It doesn't make sense
to have the overhead of calling a
separate "hasher", however small that
overhead may be.

*Private fields - there is the issue that
hashCode() may rely on private
fields, it may be difficult to
create external "hashers" for some
objects.

A: It does! Check out the Object.hashCode method.
After reading your question again I might have jumped the gun. I now see that you said "override" the natural hshing. Usually we override the hash value at the object level and forgo the use of a overriding Hasher.
Hashes are meant to be more universal that comparators. That is, hashes should almost always create uniform distrusted values with little chance of collision. The container in which they are used should rarely need a specialized hasher.

A: It has already been asked.

A: You can change the hash code of an object by wrapping in an Object which inplements hash code your way.  The assumption is that you may want to have a objects sorted a numebr of ways, but not have multiple hashing strategies.
c.f. Trove4j supports hashing strategies for its HashMap and while I use this library often I have only used a custom hashing strategy once I can remember.


text:
Q: Is there a notation for the region bounded by a Jordan curve (and higher-dimensional analogues)? If we have a subset $S$ of a topological space $X$, then its boundary is denoted by $\partial S$. But is there notation to go the other direction? For instance, in $X=\mathbb{R}^2$, if we have a simple closed contour $C$, then the Jordan curve theorem ensures that $\mathbb{R}^2 \setminus C$ has two connected components, commonly called the interior $I$ (which is bounded) and the exterior $E$ (which is unbounded). Is there any precedence in the literature for a notation for these sets in terms of $C$? In general, if $C$ is a closed $n$-manifold (or even simply the image of $S^n$ under an injective, continuous mapping) in $\mathbb{R}^{n+1}$, is there a notation for the $(n+1)$-dimensional region bounded by $C$?

A: Some people use the notation $int(C)$ (the "interior" of $C$), for the open region on $R^2$ bounded by the Jordan curve $C$, see for instance Carsten Thomassen, "The Jordan-Schonflies Theorem and the Classification of Surfaces". I do not particularly like this notation, but I do not think there is a better one.


text:
Q: how to use grep in R to get the specified character? I have
str=c("00005.profit", "00005.profit-in","00006.profit","00006.profit-in")

and I want to get
 "00005.profit"  "00006.profit"

How can I achieve this using grep in R?

A: Here is one way:
R> s <- c("00005.profit", "00005.profit-in","00006.profit","00006.profit-in")
> unique(gsub("([0-9]+.profit).*", "\\1", s))
[1] "00005.profit" "00006.profit"
R>

We define a regular expression as digits followed by .profit, which we assign by keeping the expression in parantheses. The \\1 then recalls the first such assignment -- and as we recall nothing else that is what we get. The unique() then reduces the four items to two unique ones.

A: Dirk's answer is pretty much the ideal generalisable answer, but here are a couple of other options based on the fact that your example always has a - character starting the part you wish to chop off:
1: gsub to return everything prior to the -
gsub("(.+)-.+","\\1",str)

2: strsplit on - and keep only the first part.
sapply(strsplit(str,"-"),head,1)

Both return:
[1] "00005.profit" "00005.profit" "00006.profit" "00006.profit"

which you can then wrap in unique to not return duplicates like:
unique(gsub("(.+)-.+","\\1",str))
unique(sapply(strsplit(str,"-"),head,1))

These will then return:
[1] "00005.profit" "00006.profit"

Another non-generalisable solution would be to just take the first 12 characters (assuming string length for the part you want to keep doesn't change):
unique(substr(str,1,12))
[1] "00005.profit" "00006.profit"

A: I'm actually interpreting your question differently.  I think you might want
grep("[0-9]+\\.profit$",str,value=TRUE)

That is, if you only want the strings that end with profit. The $ special character stands for "end of string", so it excludes cases that have additional characters at the end ... The \\. means "I really want to match a dot, not any character at all" (a . by itself would match any character).  You weren't entirely clear about your target pattern -- you might prefer "0+[1-9]\\.profit$" (any number of zeros followed by a single non-zero digit), or even "0{4}[1-9]\\.profit$" (4 zeros followed by a single non-zero digit).


text:
Q: jQuery changing the location based on the html Ok, so I have this ul listed below and the buy now link under it that currently goes to /two_hours. I want it to change the location based on what is clicked. For example if I click the 4 hour button i want the url to the buy now button to go to four_hours and so on.
Here is my jQuery so far:
$(function () {
  $('.box-ul .btn .dot').click(function () {
    $('.box-ul .btn .dot').not(this).removeClass('clicked');
    $(this).toggleClass('clicked');
  });
});

HTML:

Easy to Use

Step by Step
details instructions

Setup time
under 30 mins

2 hours

4 hours

8 hours

12 hours

  Buy Now

A: Maybe you can add change the attr of the buy link when jquery detect a click?
$('.btn > .hour4').click(function(){ $('a.buy').attr('href','/four_hours')});

of course that would mean you have to label the fourhour buttn with an class hour4

A: $('.box-ul .btn .dot').click(function () {
    $('a.buy').href = '/'+ $(this).siblings('p').html();
    // other code...
});

I will leave the conversion of "2 hours" to "two_hours" as an exercise to the reader.

A: I would change the HTML structure to embed the link inside the paragraph itself to make it more semantic from

2 hours

to

2 hours

for each of the four links. Then assign a handler to each link:
$('p.left a').click(function() {
    $('.buy').attr('href', this.href);
    return false; // don't follow the link
});


text:
Q: Merging of 2 custom List objects in c# Can someone help me out or can give me any pointer of solving this particular issue. Merging of list objects, by comparing 2 List of objects.
It is manageable with simple for loops and linq, as data is huge I was searching for optimum way or any algorithm for this purpose would be of great help.
class user
{
    string userID;
    string userName;
    //...
    List<role> objRoles;
}
class role
{
    List<pemission> objPermisison;
}
class pemission
{
    bool newlyAdded;
    //...
}

List<User> List1 :

User1
 - Role_1
     - Permission_1
     - Permission_2
 - Role_2
     - Permission_3
     - Permission_4

List<User> List2 :

User1
 - Role_1
     - Permission_3
     - Permission_4
 - Role_2
     - Permission_5
     - Permission_4

Required Result :

List<User> Resultant_List :

User1
 - Role_1
     - Permission_1
     - Permission_2
     - Permission_3 - Flag (Newly Added)
     - Permission_4 - Flag (Newly Added)
 - Role_2
     - Permission_3
     - Permission_4
     - Permission_5  - Flag (Newly Added)

A: According to here to merge two lists without duplicates, a dictionary merge is the fastest method...
"This solution converts list2 to a dictionary and then it loops a single time over list1. It either adds to the dictionary or replaces the value of list2 if it was a duplicate. This seemed to be a much more efficient algorithm."
var dict = list2.ToDictionary(p => p.userID);

foreach (var person in list1)
{
    dict[person.userID] = person;
}

var merged = dict.Values.ToList();


text:
Q: Vuejs internet explorer compatibility issues (versions 10 and 11) I hope this question/answer saves time for those having the same cross-compatibility issues with internet explorer.

Problem:
I used vuejs2 in one of my projects, and it turned out that there were some compatibility issues in earlier releases of internet explorer.
at first, it went down to this error:

SCRIPT1014: Invalid character

And then this one:

'Promise' is undefined

A: the first error refers to the use of Ecmascript6 back thicks (`) that simplifies the use of strings in javascript.
the solution is to use the old way which is concatenating your HTML.
As for the second error, the use of promises is not handled in earlier versions of internet explorer, the solution is to use polyfill (which is an api that ensures backwards compatibility in older browsers, example: promises)
in my case I used this:
<script src='https://cdn.polyfill.io/v2/polyfill.min.js'></script>


text:
Q: Compiling C++ with external library to Wasm using Wasmer I'm trying to compile C++ file linked with external library using Wasmer.
I built external library using:
git clone -b main https://github.com/open-quantum-safe/liboqs.git
cd liboqs
mkdir build && cd build
wasimake cmake -GNinja ..
wasimake ninja

As a result I've got liboqs.a library which I want to reuse in code that I'm trying to compile to Wasm.
Here is the code:
#include <stdio.h>
#include <oqs/oqs.h>

int main(void)
{
   uint8_t public_key[OQS_KEM_frodokem_640_aes_length_public_key];
   uint8_t secret_key[OQS_KEM_frodokem_640_aes_length_secret_key];

   OQS_STATUS rc;
   rc = OQS_KEM_frodokem_640_aes_keypair(public_key, secret_key);

   printf("%d\t", (int)rc);

   return 0;
}

Compiling file with this command:
wasicc -I ../../build/include "liboqs.a" "example.cpp" -o example.wasm

../../build/include - path to build folder of external library.
I'm getting this error:
wasm-ld: error: liboqs.a(rand.c.o): undefined symbol: __memory_base

I don't understand what does this error mean and what can be the reason of it.

A: Not sure if this helps, but I was able to build this C file below:
cd liboqs
mkdir build && cd build
cmake -GNinja ..

wasicc \
  -o example.wasm \
  -I liboqs/build/include \
  example.c

#include <stdio.h>
#include <oqs/oqs.h>

int main(void)
{
  uint8_t public_key[OQS_KEM_frodokem_640_aes_length_public_key];
  uint8_t secret_key[OQS_KEM_frodokem_640_aes_length_secret_key];

  return 0;
}


text:
Q: SQLite with Android Studio, return all records selected by 2 arguments let's assume that i have a table with columns such as:
ID    SSID      BSSID      RSSI
1     abcd     hs:hd:sd    -60
2     abcd     hs:hd:po    -68

There are about 5000 records with the same SSID, slighltly different BSSID and the LEVEL values. My device is scanning the nearest environment for WiFi networks, therefore I know their MAC address and level of RSSI. I pick 3 with the highest value od RSSI.
First thing I would like to know if it is possible to search through the database to get all the records with the LEVEL value equal or close to 60, for instance 59,58,61.
Secondly, is there a way to query the database to return all the records with the same MAC addresses and RSSI values as from the 3 best scan result? If so, how would that query look like?
EDIT: Thanks for all the answers. What I'm trying to do now is to compare 3 scans with records stored in database with getRequiredData function. I would like to pass 2 parameters to this function, mac address and level and find records with same value for both parameters. The rawQuery seems to be fine, code is compiling but the app is crashing with the first scan. I cant find the cause of it, is it because my logic of getting these parameters is wrong or does it have something to do with query?
public Cursor getRequiredData(String mac, int level){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("SELECT BSSID, RSSI FROM TABLE_NAME WHERE BSSID =? AND RSSI=?", new String[] {mac, level});
    return res;
}

scan part:
class WifiReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        sb = new StringBuilder();
        Comparator<ScanResult> comparator = new Comparator<ScanResult>() {
            @Override
            public int compare(ScanResult o1, ScanResult o2) {
                return (o1.level>o2.level ? -1 : (o1.level==o2.level ? 0 : 1));
            }
        };
        lista = wifiManager.getScanResults();
        Collections.sort(lista, comparator);
        for (int i = 0; i < lista.size(); i++) {
            scanResult = wifiManager.getScanResults().get(i);
                sb.append(new Integer(i + 1).toString() + ". " + (lista.get(i)).SSID + "  " + (lista.get(i)).BSSID + "  " + (lista.get(i)).level + "\n");
                boolean isInserted = myDb.insertData(lista.get(i).SSID.toString(), lista.get(i).BSSID.toString(), lista.get(i).level);
                if (isInserted = true)
                    Toast.makeText(MainActivity.this, "Data inserted", Toast.LENGTH_LONG).show();
                else
                    Toast.makeText(MainActivity.this, "Data not inserted", Toast.LENGTH_LONG).show();
        }
        for (int i=0; i<4; i++)
        {
            scanResult = wifiManager.getScanResults().get(i);
            match = myDb.getRequiredData(lista.get(i).BSSID.toString(), lista.get(i).level);
        }
        Log.i("match values: ", DatabaseUtils.dumpCursorToString(match));
        txt.setText(sb);
        wifiManager.startScan();
    }
}

Here is what match contains:
2018-12-10 16:36:26.334 13347-13347/com.example.maciek.wifiscann I/match values:: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@e1a86d1
0 {
   BSSID=f4:c5:ed:5c:s6:20
   RSSI=-69
}
1 {
   BSSID=f4:c5:ed:5c:s6:20
   RSSI=-69
}
2 {
   BSSID=f4:c5:ed:5c:s6:20
   RSSI=-69
}
3 {
   BSSID=f4:c5:ed:5c:s6:20
   RSSI=-69
}
4 {
   BSSID=f4:c5:ed:5c:s6:20
   RSSI=-69
}
5 {
   BSSID=f4:c5:ed:5c:s6:20
   RSSI=-69
}
<<<<<

A:
First thing I would like to know if it is possible to search through
  the database to get all the records with the LEVEL value equal or
  close to 60, for instance 59,58,61.

SELECT * FROM your_table WHERE level BETWEEN 59 AND 61;

*

*where your_table is the respective table name.

*Note if levels are negative (as per example data) then BETWEEN requires the lowest value first so it would be BETWEEN -61 AND -59.

Secondly, is there a way to query the database to return all the
  records with the same MAC addresses and RSSI values as from the 3 best
  scan result? If so, how would that query look like?

SELECT * FROM your_table WHERE your_mac_address_column = 'the_mac_address_value' AND RSSI = 'the_rssi_value' ORDER BY LEVEL DESC LIMIT 3

*

*Note the above assumes that the MAC address is stored in a column (if NOT then cannot be done unless the mac address can be correlated to a column).

*Assumes best LEVEL is lowest so -1 is better than -60 (if not then use ASC instead of DESC)

*Again your_table, your_mac_address_column, the_mac_address_value and the_rssi_value would be replaced accordingly with actual values (note that strings should be in single quotes).

A: To get the 3 rows with the closest values to 60 in column LEVEL:
SELECT * FROM tablename ORDER BY ABS(LEVEL - 60), LEVEL LIMIT 3

For the 2nd part of your question, you should provide sample data of the table. Edit:
From the sample data that you posted I don't see a column RSSI, but if it exists in the table then the SELECT statement is ok.
Change the 2nd parameter of rawQuery() to:
new String[] {mac, String.valueOf(level)}

because level is int.
In onReceive() you use myDb. I don't know how you initialize it.
If the app crashes you must copy the log, the part that identifies the problem and post it.


text:
Q: Access to android/media on android 11 I have an app that need access to "Android/Media*", but due google play policies i cant use "manage all files" permision,
Could any show me how to access to external storage(read files on any path of device), with out "manage al files" permision,
Note: with that permission the app work great, but with out that, i cant access to "android/media" thats is required by app to work


text:
Q: Instagram Stories, how do they detect @username? I have been using Instagram stories lately and they have such an incredible feature where in a picture/snap you can mention another user such as @username wherever you want in the picture and when you are viewing it you can click on that username and a pop-up lets you click into it. Similarly, they let you post a location.
If you are familiar with Stories you can write on an image anywhere and post that. So I am wondering how did they manage to do this? Do they perform image rec on the snap when viewing it and look for text? Or do they save the location in the image where that was posted and link it to data? Any tips?

A: Instagram stories work same as any other Instagram photos or Facebook photos. When you are tagging a friend in an Instagram story the text gets written on the photo. At the same time there will be external tag on the story letting you to click the photo so it redirects you the mentioned profile. It is all in the code.


text:
Q: jQuery run on elements loaded via ajax in previous function I'm aware of the use of .ajaxComplete however the code I am working with is independent from the function that runs the ajax.
I'm also aware of .live however this is deprecated.
I have a function which loads in some HTML, including a div called main.home
In a different function, I want to make main.home .slideDown
/* First function loads the HTML */
$(document).ready(function() {
    $("#quiz-section").load("home.php");
    $( document ).ajaxComplete(function() {
        $( ".inner-wrap" ).fadeIn(2000);
    });
});

/* Second function called on button click */
function nextQuestion(page){
    $("main.home").slideDown("fast");
}

.slideDown does not seem to work but no errors are presented in the console. I believe that maybe it cannot find the element main.home  because it is loaded via ajax?
Any advice appreciated.
Edit to add the call for nextQuestion as requested:

Take our 'Love Match' test

HTML as so rudely asked for is nothing but:

Take our 'Love Match' test

There you go.

A: What slideDown do ?
It make visible an hidden element with a slide motion.
So, you should have this :
HTML:

    Some stuff here

Take our 'Love Match' test

Javascript :
$("#clickme").click(function() {
    $("main.home").slideDown("fast");
});

"Some stuff here" is hidden and when you click on the link, it make your element main appears with a slide motion.


text:
Q: Android App stuck for a few seconds while generating list of informations with images I made an Android App with Titanium Appcelerator where you can search for products in a local SQLite database. The list I generate when the user clicks "Show all" takes the first 50 entries and displays the info as a list. All works fine as long as i have no images. When I include the images to the app (about > 10.000 images in a folder), the app is stuck the first time I make a database request and generate the listview.
If I go back and repeat the step, it will work immediately. If I restart the app it will stuck. I don't know how to fix that. Could it be, that one folder with thousands of files is the problem? Could it help to split the images into different folders?
I create the window and send data to it, before I open it
if (!onlineSearchContainerWindow) {
    var onlineSearchContainerWindow = SearchWindow();
}
onlineSearchContainerWindow.fireEvent('setDataArr', {
    first : self.first
});
onlineSearchContainerWindow.open();

I had a Template for the Listview with a imageview included
                childTemplates : [{
                    type : 'Ti.UI.View',
                    bindId : 'artPicContainer',
                    properties : {
                        left : '0dp',
                        width : Number((dpuDeviceWidth / 2) - 25) + 'dp',
                        height : Number((dpuDeviceWidth / 2) - 25) + 'dp',
                        borderWidth : 2,
                        borderColor : '#6c6c6c',
                        borderRadius : 4,
                        backgroundColor : '#fff'
                    },
                    childTemplates : [{
                        type : 'Ti.UI.ImageView', // artPic ICON
                        bindId : 'artPic',
                        properties : {
                            isLoaded : true,
                            size : {
                                width : Number((dpuDeviceWidth / 2) - 25) + 'dp',
                                height : Number((dpuDeviceWidth / 2) - 25) + 'dp',
                            }
                        }
                    }]
                },

I open the database, execute the statement with a limit of 50
db = Titanium.Database.open("productsDB");
var dbData = db.execute(statement + " LIMIT " + String(number * maxDisplay) + ", " + Number(maxDisplay + 1));

Then I create a data object with the image path for id artPic and other values and push it into an array
var listviewData = {
            firstLevelContainer : {
                artikelnummer : xxx,
            },
            artNrLabel : {
                text : xxx
            },
            artPic : {
                image : "/images/path/" + imagename + ".jpg"
            }
        };

I create a Listviewsection and link the array with the datasets. Then I create the Listview and set the template and the section
   itemListView = Ti.UI.createListView({
            top : 0,
            templates : {
                'template' : myTemplate
            },
            defaultItemTemplate : 'template',
            footerView : endRow,
            sections : [itemListSection],
        });
        mainCon.add(itemListView);

After that I hide the preloader for the window. But till then, the Preloader stucks for a long time, stop turn around an freezing.
I dont link the building process to the open event.
The image size is around 1-3 kb each.
All together:

A: According to the information that you have provided their can be two possibilities causing delay of action :

*

*You are saving the image files in the SQLite database

Solution : If this is the case then try saving the Image URL in the database and not the images. You can get the image URL by using the FileSystem API.

*Your Database is Installed when you click on the 'Show All' button

Solution : If this is the case then remove the install method from the eventListener and place it in the alloy.js or index.js, this would help you speed up the process when you click on the 'Show All' button.
Good Luck & Cheers
Ashish Sebastian


text:
Q: Turbo C++: Why does printf print expected values, when no variables are passed to it? A question was asked in a multiple choice test: What will be the output of the following program:
#include <stdio.h>

int main(void)
{
    int a = 10, b = 5, c = 2;

    printf("%d %d %d\n");

    return 0;
}

and the choices were various permutations of 10, 5, and 2. For some reason, it works in Turbo C++, which we use in college. However, it doesn't when compiled with gcc (which gives a warning when -Wall is enabled) or clang (which has -Wformat enabled and gives a warning by default)  or in Visual C++. The output is, as expected, garbage values. My guess is that it has something to do with the fact that either Turbo C++ is 16-bit, and running on 32-bit Windows XP, or that TCC is terrible when it comes to standards.

A: It is an undefined behaviour. So it could be anything.
Try to use
printf("%d %d%d", a,b,c)

Reason:- Local variables are called on the stack and printf in Turbo C++ sees them in the same order in which they were assigned in the stack.
SUGGESTION(From comments):-
Understanding why it behaves in a particular way with a particular compiler can be useful in diagnosing problems, but don't make any other use of the information.

A: The answer here is that the program could do anything -- this is undefined behavior.  According to printf()s documentation (emphasis mine):

By default, the arguments are used in the order given, where each '*' and each conversion specifier asks for the next argument (and it is an error if insufficiently many arguments are given).

If your multiple-choice test does not have a choice for "undefined behavior" then it is a flawed test.  Under the influence of undefined behavior, any answer on such a multiple-choice test question is technically correct.

A: What's actually going on is that arguments are normally passed on the call stack.  Local variables are also passed on the call stack, and so printf() sees those values, in whatever order the compiler decided to store them there.
This behavior, as well as many others, are allowed under the umbrella of undefined behavoir

A: The code has undefined behaviour.
In Turbo C++, it just so happens that the three variables live at the exact positions on the stack where the missing printf() argument would be. This results in the undefined behaviour manifesting itself by having the "correct" values printed.
However, you can't reasonably rely on this to be the case. Even the slightest change to your build environment (e.g. different compiler options) could break things in an arbitrarily nasty way.

A: No, it's not related to architecture.  It is related to how TurboC++ handles the stack.  Variables a, b, and c are locals and as such allocated in the stack.  printf also expects the values in the stack.  Apparently, TurboC++ does not add anything else to the stack after the locals and printf is able to take them as parameters.  Just coincidence.


text:
Q: PHP - Attributing a value to a var depending on the value of another var I'm trying to attribute a value to a var depending of its text value.
I can't just attribute the numerical value directly (via my form) because i'm also saving in my database the text value.
$section = $_POST['section']; // required
$page = $_POST['page']; // required

if ($_POST['page'] == 'Template') { $Code == '00'; }
elseif ($_POST['page'] == 'Menu') { $Code == '01'; }
elseif ($_POST['page'] == 'Home Page') { $Code == '02'; }
elseif ($_POST['page'] == 'About Us') { $Code == '03'; }
elseif ($_POST['page'] == 'Contact Us') { $Code == '04'; }

$Code_Page = $Code.''.$section;

Exemple, the code for the section 18 of the Home Page is 0218.
I don't understand why it doesn't work ?
Only the second part is saved ($section), not the first 2 numbers.
Thanks in advance

A: EDIT: Author has clarified what he is after now. I've kept the original answer in as I feel it is a better solution.
To define a variable in PHP, you use a single equals sign (=). You've used two equals signs (==) when defining $Code, which is a comparison operator.
Original answer:
I'm assuming that you wish to optimize this code. If so, I feel the best way to do so is to either create an array, or pull from the database you mentioned from. Once you have the dataset in an array, you can do some simple checking:
Static array method:
$pages = array('Template' => '00', 'Menu' => '01', 'Home Page' => '02', 'About Us' => '03', 'Contact' => '04');
if (in_array($_POST['Page'], $pages))
{
    //We have a match, deal with output here
    $Code_Page = $pages[$_POST['Page']].$section
}
else
{
    //Output an error message here, the page isn't in the array
}

A: add $Code declaration first
$section = $_POST['section']; // required
$page = $_POST['page']; // required
$Code = ''; // This was missing

if ($_POST['page'] == 'Template') { $Code == '00'; }
elseif ($_POST['page'] == 'Menu') { $Code == '01'; }
elseif ($_POST['page'] == 'Home Page') { $Code == '02'; }
elseif ($_POST['page'] == 'About Us') { $Code == '03'; }
elseif ($_POST['page'] == 'Contact Us') { $Code == '04'; }

$Code_Page = $Code.''.$section;

A: It seems like the code you have provided gives you the code you are looking for the homepage of 0218. The only error I see is you are not assigning the $Code. Your $Code == '02' should be $Code = '02'


text:
Q: "Every time no one's around" or "every time when no one's around"
I couldn't help but stare at him every time when no one's around

Or

I couldn't help but stare at him every time no one's around

Which is correct?

A: The construction every time when... is not idiomatic. No examples of it can be found on Google Books Ngram Viewer.
Every time can either be followed by that or by the clause that follows without that. For example:

Every time that he comes here, he brings flowers

or

Every time he comes here, he brings flowers.

The construction no one's is likely to be understood as no one is although it might possibly be interpreted in some contexts as no one was or no one has.
So you need to phrase your sentences either in the present tense as:

I can't help but stare at him every time (that) no one's [is] around.

or, in the past tense as:

I couldn't help but stare at him every time (that) no one was around.

https://books.google.com/ngrams/graph?content=everry+time+when%2Cevery+time+tha

A: They are both correct.
The second form is a bit better, because it is shorter.
The meaning of both is exactly the same.

A: These both sound wrong; "no one's" is a contraction for "no one is", but we would want "no one was" there, instead.
That being said, the second one is better because the "when" is redundant - we already have said "time", so saying "when" is repeating ourselves a bit.
Also I would prefer "any" to "every", but the differences are subtle.  Also, "anytime we were alone" is worth considering.


text:
Q: Is there a way to exclude {ignore-on-commit} changes from TortoiseSVN Explorer icon decorations? TortoiseSVN shows icon decorations in Windows Explorer which show whether there are any uncommitted changes in a particular directory tree.  For example:

The above image shows that somewhere in the directory tree of Trunk there is a changed file.
However, I often use the ignore-on-commit changelist to hold changes which I never want to commit - for example Web.config changes related to connection strings.
I cannot rely on the icon decorations letting me know whether I have changes, as they will also show up with a red (!) even if there's only Web.config changes.  This adds unnecessary noise to Explorer.
Is there a way to change this so that only changes I want to commit are flagged as changes in Explorer?

A:
Is there a way to change this

No. Icon overlays work

*

*for all files

*by the same manner

*always

A: I recently upgraded to TortoiseSVN version 1.8.3 (I was using 1.7.x before) and it appears that there is now an option to do exactly this!  It works perfectly.


text:
Q: Running console application/batch file interactively inside Inno Setup From this post, I see that we can monitor the cmd output and show it in Inno setup UI:
Embedded CMD in Inno Setup installer (show command output on a custom page)
In my case , in Run section I launch a bat, which will do some process based on a user input.
(e.g whether install / modify a package - user will input Y/n – something like that)
Is it possible to embed an interactive cmd in to Inno Setup GUI? The problem is if user closes the cmd prompt in-between then the installation will not be proper and leads to corrupted files.
What is right way to handle this?

A: It's probably doable – but a lot of work and not user-friendly anyway.

I'd use Inno Setup GUI to ask all questions in advance and then run the batch file non-interactively.

*

*Either by modifying the batch file to accept parameters to control its options.
See Inno Setup: How to pass variable from [Code] to [Run] (or other section)

*Or, if you cannot modify the batch file, by providing an answer file.
See How to provide an input to a batch file ran using Inno Setup installer?


text:
Q: Save Failed Negative Time Aptana Studio 3.4 I have searched everywhere and cannot find a fix for this problem. Every time I try to save a file it says the Title -Aptana Studio 3.4. The only way I've been able to fix it is a full reinstall, and I shouldn't have to do that every two files saved.
Please help! D:

A: actually the simple solution is to change the date/time of your files in some how , the simple way is to open these files with any other editor and change any thing and save again so it will get your current time and it will work very fine


text:
Q: how to set textview and edittext params programmatically in a table row? i wanted to add textview and edittext params by code.
here is my code
private void draw_table() {
    // TODO Auto-generated method stub
    TableLayout ll = (TableLayout) findViewById(R.id.input_table_2);

    for (int i = 0; i < 2; i++) {

        TableRow row = new TableRow(this);
        TableRow.LayoutParams lp = new TableRow.LayoutParams(
                TableRow.LayoutParams.MATCH_PARENT,
                TableRow.LayoutParams.WRAP_CONTENT);
        row.setLayoutParams(lp);
        // setting textVIEW
        textview = new TextView(this);
        textview.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        //textview.setPadding(0, 0, 5, 10);
        //textview.setTextAppearance(this,
        //      android.R.style.TextAppearance_Medium);
        textview.setText("Hello");
        // setting editText
        edittext = new EditText(this);
        edittext.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        //edittext.setEms(10);
        //edittext.setHint("gpa");
        //edittext.setInputType(InputType.TYPE_CLASS_NUMBER);
        row.addView(textview);
        row.addView(edittext);
        ll.addView(row, i);
    }
}

but nothing appear on the screen. whats wrong in this code ?thanks in advance :)

A: Use TableRow.LayoutParams to set your widgets LayoutParams. Like this
textview.setLayoutParams(new TableRow.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));

also see how add and delete rows to table layout in java programically


text:
Q: Angular 6 material table schematic: howto load data from remote? I'm using the material table schematic and can't figure out how to
I think the important part is the connect() method in the datasource.ts file. this.data is just an array.
  /**
   * Connect this data source to the table. The table will only update when
   * the returned stream emits new items.
   * @returns A stream of the items to be rendered.
   */
  connect(): Observable<any[]> {
    // Combine everything that affects the rendered data into one update
    // stream for the data-table to consume.
    const dataMutations = [
      observableOf(this.data),
      this.paginator.page,
      this.sort.sortChange
    ];

    // Set the paginators length
    this.paginator.length = this.data.length;

    return merge(...dataMutations).pipe(
      map(() => {
        return this.getPagedData(this.getSortedData([...this.data]));
      })
    );
  }

How can I update this.data such that the table reflects the data?  I only need to load the data once.  I'd like filtering/sorting etc all to be done client side.
I found this guide, but it seems like overkill and was written before this schematic was created.
Isn't there some way to update this.data since its wrapped in an observableOf()?

A: I had this same problem. Changing dataSource.data = newData was not being detected by observableOf(this.data),.
Fixed it with the solution from this thread and shown in this example.
You have to replace that observableOf(this.data) with a this.datastream. So that connect method will end up looking like this:
connect(): Observable<DataTableItem[]> {
  const dataMutations = [
  this.dataStream,
  this.paginator.page,
  this.sort.sortChange

And in the beginning of the class, instead of declaring the variable data: TableItem[] = EXAMPLE_DATA;, you replace that with:
dataStream = new BehaviorSubject<DataTableItem[]>(EXAMPLE_DATA);
set data(v: DataTableItem[]) { this.dataStream.next(v); }
get data(): DataTableItem[] { return this.dataStream.value; }

Now you can call dataSource.data = newData anywhere with any new data and it just works. The datastream detects the change and the table gets updated. The problem was that observable of this.data was not really detecting any change. The datastream does.

A: The data source for the table needs to be an Observable.
As long as this.data is an array, there is no mechanism that will notify the data table when items are added, removed, or modified in the array.

A: After searching for tutorials I reverted back to the Official Example that turned out to be very intuitive.
I had a similar requirement to your question, Just load the data once and manage the manipulation at client-side.
However, I ended handling the manipulation at the server side.
Let me make an assumption, you have an endpoint that returns a list of objects.

/api/books/

1: Create a service with an http-call method to get your books endpoint(book.service.ts)
private booksUrl = "/api/books";
 _getBooks(bookId: number, filter='', sortOrder='asc', pageNumber=0,
pageSize=3):Observable<Book[]>{
    return this.http.get(this.booksUrl, {
      params: new HttpParams()
          .set('bookId', _bookId.toString())
          .set('filter', filter)
          .set('sortOrder', sortOrder)
          .set('pageNumber', pageNumber.toString())
          .set('pageSize', pageSize.toString())
      }).pipe(
          tap(_ => this.log('fetched books')),
          catchError(this.handleError('getBooks', [])),
          map(res =>  {
        res["payload"] = res;
        return res["payload"];
      })
      );
    }

Define your Book class

export class Book{
    bookId: string;
    Title: string;
}

Then I created a Material-Table component using the data-table schematics.
I Edited the table-datasource as such

import { Book } from '../books';
import { BookService } from '../book.service';

/**
 * Data source for the Masterlist view. This class should
 * encapsulate all logic for fetching and manipulating the displayed data
 * (including sorting, pagination, and filtering).
 */
export class BooksDataSource implements DataSource<Book> {

  private booksSubject = new BehaviorSubject<Book[]>([]);
  private loadingSubject = new BehaviorSubject<boolean>(false);

  public loading$ = this.loadingSubject.asObservable();

  constructor(private bookService: BookService) {}

  /**
   * Connect this data source to the table. The table will only update when
   * the returned stream emits new items.
   * @returns A stream of the items to be rendered.
   */
  connect( collectionViewer:CollectionViewer): Observable<Book[]> {
    return this.booksSubject.asObservable();
  }

  /**
   *  Called when the table is being destroyed. Use this function, to clean up
   * any open connections or free any held resources that were set up during connect.
   */
  disconnect(collectionViewer: CollectionViewer): void {
    this.booksSubject.complete();
    this.loadingSubject.complete();
  }

  loadBooks(bookId: number, filter = '', sortDirection = 'asc', pageIndex = 0, pageSize = 3) {
    this.loadingSubject.next(true);
    this.bookService._getBook(bookId, filter, sortDirection,pageIndex, pageSize).pipe(
      catchError(e => throwError(e)),

      finalize(() => this.loadingSubject.next(false))
      )
      .subscribe(_books => this.booksSubject.next(_books));
}
}

Finally, on the Books.Components.ts(your component)

export class BooksComponent implements OnInit {

  constructor(private bookService: BookService){}

  dataSource: BooksDataSource;

  /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
  displayedColumns = ['bookId', 'Title'];

  ngOnInit() {
    this.dataSource = new MasterlistDataSource(this.bookService);
    this.dataSource.loadBooks(1);
  }
}

From here you can map the datasource to your table.

The the Official Example continues to show how to implement sorting, pagination, filtering.
Happy coding :-)

A: Please try @matheo/datasource to setup your database service and your datasource in a clean way.
I've built a demo on StackBlitz and presented it details at:
https://medium.com/@matheo/reactive-datasource-for-angular-1d869b0155f6
I will try to get the time to provide an Schematic too with some boilerplate code as the official material one.
Looking forward for your opinion!


text:
Q: Symfony 3.4 Doctrine: Change referenced table on runtime In my symfony application products are stored in the table products. There is an Entity Product and Repository ProductRepository for it.
Some products automatically get archived and stored in another table, called products_archived. I created an Entity ProductArchived and duplicated the ProductRepository file to the file ProductArchivedRepository.php.
The tables products and products_archived have exactly the same structure and fields.
My goal:
When in the code a product is identified as an archived product, I want to be able to apply a function from the ProductRepository and NOT having to refer to a separate ProductArchivedRepository. I want to avoid having to use duplicated code.
Example:
ProductRepository.php:
public function getProductDataById($productId)
{
   $qb = $this->createQueryBuilder('p');

   // ...

   return $qb->getQuery()->getArrayResult();
}

ProductArchivedRepository.php:
public function getProductDataById($productId)
{
   $qb = $this->createQueryBuilder('p');

   // ...

   return $qb->getQuery()->getArrayResult();
}

ProductService.php:
public function getProductDataById($productId)
{
    $repoProduct = $this->productRepository;
    $repoProductArchived = $this->container->productArchivedRepository;
    if ($repoProduct->findOneBy(['id' => $productId]) instanceof Product) {
        $repoP = $repoProduct;
    } else if ($repoProductArchived->findOneBy(['id' => $productId]) instanceof ProductArchived) {
        $repoP = $repoProductArchived;
    } else {
        throw new NotFoundHttpException(
            'Product neither found in table product nor in table product_archived.'
        );
    }

    $productData = $repoP->getProductDataById($productId);

    return $productData;
}

How do I achieve that ProductArchivedRepository.php becomes redundant?

A: You can use an abstract class that regroup the duplicated method(s)
abstract class AbstractProductRepository extends EntityRepository
{
    public function getProductDataById($productId)
    {
        $qb = $this->createQueryBuilder('p');

        // ...

        return $qb->getQuery()->getArrayResult();
    }
}

And now, both of your repository can extend the abstract class instead of EntityRepository :
class ProductRepository extends AbstractProductRepository
{
    // ...
}

class ProductArchivedRepository extends AbstractProductRepository
{
    // ...
}


text:
Q: Access non static function from static function Here is some insight: I am working with UnityScript in Unity 4.6.3. I have one script called Pause.js and it contains this function:
function fadeMusicOut () {
    while (audio.volume >= 0.005) {
    yield WaitForSeconds(0.1);
    Debug.Log("Loop Entered: " + audio.volume);
    audio.volume = (audio.volume - 0.015);
}

Another script GameManager.js has this function:
static function Score (wallName : String) {
    if (wallName == "rightWall") {
        playerScore01 += 1;
    }
    else {
        playerScore02 += 1;
    }
    if (playerScore01 == SettingsBack.scoreLimit || playerScore02 == SettingsBack.scoreLimit)
    {
        startParticles = 1;
        SettingsBack.gameOver = 1;
        BallControl.fadeSound = 1;
        yield WaitForSeconds(4);
        Camera.main.SendMessage("fadeOut");
        Pause.fadeMusic = 1;
        SettingsBack.soundVolume = 0;
        yield WaitForSeconds(2);
        playerScore01 = 0;
        playerScore02 = 0;
        SettingsBack.soundVolume = oldSoundVol;
        Application.LoadLevel("_Menu");
    }
}

So pretty much I want to call the fadeMusicOut() function from static function Score, but it will not let me because it says it needs an instance of that object.
The Pause.js script is not attached to any game objects, but it is attached to 2 buttons that call their specific functions. The GameManager.js script is attached to an object called GM. So how can I go about calling fadeMusicOut() from the Score function?
I have tried setting new vars that import the game object but still no luck. I tried making fadeMusicOut() a static function, but it creates many errors.
Any help at all is appreciated.


text:
Q: Ubuntu 13.04 network connection is no more I' using Ubuntu 13.04. Two days ago I had a problem with the connectivity of the Wifi. I followed these instructions
"...Now download the latest NetworkManager, in case you need to reinstall it if WICD doesn't work sudo apt-get install -d --reinstall network-manager network-manager-gnome
Then to install it sudo apt-get install wicd-gtk
And now you need to uninstall NetworkManager: sudo apt-get remove --purge network-manager-gnome network-manager.
Now you can find WICD in your menu Start WICD, find the network you want to use and enter the information needed, password, encryption, etcetera and choose Automatically Connect to this network. You should be good to go!"
But when I tried to connect to wicd: "Could not connect to wicd's D-Bus interface. Check the wicd log for error messages" and upon checking with System Testing Report I found this "Error:root: could not find def gateway info in /proc" and "Error:root: could not find default gateway by running route"
Lastly when I removed wicd-gtk and installed network-manager-gnome network-manager and tried to run "network" in the settings, it again says "The system network services are not compatible with this version"
Can you help?

A: OK, two possible solutions to the two parts of your problem.
Firstly, to get Network Manager back up try running this from the command line:
sudo service network-manager start

If that works, then you probably need to make that change permanent by editing the file /etc/rc.local and adding the line
NetworkManager

before the line that says 'exit'. Reply if you need help doing that.
(See Restarted computer during update; "the system network service is not compatible with this version" for source of above.)
Secondly, if you want to try wicd again then it looks like you're experiencing a symptom of this bug: https://bugs.launchpad.net/ubuntu/+source/wicd/+bug/1132529
The solution that worked for me was to run the following commands from the command line (see comment #22 from above link):
sudo service wicd stop
rm /etc/resolv.conf
ln -s /run/resolvconf/resolv.conf
rm /var/lib/wicd/resolv.conf.orig
ln -s /run/resolvconf/resolv.conf /var/lib/wicd/resolv.conf.orig
sudo service wicd start

Hope that helps!


text:
Q: Why is UTF-8 output to C console working with Cygwin but not with MinGW? I want my code to output unicode characters.
This is my code:
printf("\u2660"); //Spade character

When compiling and executing with Cygwin, it works just fine and the spade character (♠) is displayed.
However, it doesn't work with MinGW, as the UTF-8 encoding is displayed as three characters (ÔÖá).
In the executable, the character is stored as UTF-8 in both cases, so the issue doesn't come from compiling.
So, why is the console behaving differently between Cygwin and MinGW?
Is there a fix to display UTF-8 with MinGW too?

A: How are you running your MinGW application in a console?
There are different ways:

*

*Command Prompt

*MinTTY (typically how MSYS2 shell is started)

*some other tool like Conzole2 or ConsoleZ

Either way you should go to Properties or Options (for the first 2 by clicking on the icon on the top left of the console window) and change the font to a font that supports Unicode.
Also, in your application use wide character output like this: wprintf(L"\u2660");


text:
Q: KeyError: 'kivy.garden.graph', Kivy app can't launch I am trying to generate my apk, and I added garden dependency to requirements part in my .spec file as follow:
requirements = sqlite3,kivy,kivy_garden.graph

But my apk can't be ;aunch, so I run logcat and notice this error.
09-08 15:14:43.525  5572  5594 I python  :  KeyError: 'kivy.garden.graph'
09-08 15:14:43.525  5572  5594 I python  : Python for android ended.

Can anyone help? Is this method outdated?


text:
Q: ¿Cómo podría configurar el zoom de Firefox para todas las páginas web? ¿Hay alguna manera de establecer el valor del zoom (por ejemplo al 80%) para que al iniciar Firefox o abrir una nueva pestaña. El zoom predeterminado sea 80%?

A: Sin extensión:
1- Pones esto en el la barra de navegación (y accedes):about:config
2- Aceptas los riesgos:

3- Buscas: browser.zoom.siteSpecific
4- Le das doble click para ponerlo en False (tiene que estar en false)

Ahora respetara el zoom que pongas, es decir, si pones zoom 80% todas las páginas lo tendrán (aunque cierres y abras el navegador) *no afecta a los iconos, etc...
Con extensión:
https://addons.mozilla.org/es/firefox/addon/zoom-page/

A: Sin addons

*

*Escribir en la barra de dirección about:config

*Aceptar los riesgos

*Buscar la propiedad layout.css.devPixelsPerPx

*Setearla en 0.8 (80%)

Nota: Esto también cambiará el tamaño de los íconos y pestañas.


text:
Q: Reading in data from text file into a VBA array I have the following VBA code:
Sub read_in_data_from_txt_file()

Dim dataArray() As String
Dim i As Integer

Const strFileName As String = "Z:\sample_text.txt"
Open strFileName For Input As #1

' -------- read from txt file to dataArrayay -------- '

i = 0
Do Until EOF(1)
    ReDim Preserve dataArray(i)
    Line Input #1, dataArray(i)
    i = i + 1
Loop
Close #1

Debug.Print UBound(dataArray())

End Sub

I'm trying to read in text line by line (assume 'sample.txt' is a regular ascii file) from a file and assign this data to consecutive elements in an array.
When I run this, I get all my data in the first value of the array.
For example, if 'sample.txt' is:
foo
bar
...
dog
cat

I want each one of these words in a consecutive array element.

A: What you have is fine; if everything ends up in dataArray(0) then the lines in the file are not using a CrLf delimiter so line input is grabbing everything.
Instead;
open strFileName for Input as #1
dataArray = split(input$(LOF(1), #1), vbLf)
close #1

Assuming the delimiter is VbLf (what it would be coming from a *nix system)

A: Here is a clean code on how to use for each loop in VBA
Function TxtParse(ByVal FileName As String) As String
    Dim fs, ts As Object
    Dim strdic() As String
    Dim oitem As Variant
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set ts = fs.OpenTextFile(FileName, 1, False, -2)

    strdic = Split(ts.ReadAll, vbLf)

    For Each oitem In strdic
        If InStr(oitem, "YourString") <> 0 Then
        Else
            If InStr(1, oitem, vbTab) <> 0 Then
                    Debug.Print "Line number is : "; "'" & Replace(oitem, vbTab, "','") & "'"
            Else
                    Debug.Print "Line number is : "; "'" & Replace(oitem, ",", "','") & "'"
            End If
        End If
    Next
End Function


text:
Q: Is this use of dispatch queues and CIFilters likely to get my app rejected? I've been looking around all day at various ways to apply a single CIFilter dynamically in an animation.
I'm looking to apply a strong CIPixellation filter to an image and gradually animate out to the original image, without using something like an alpha fade, which just wouldn't have the desired animation effect.
I looked at Brad's GPUImage, but importing MB's of framework into a very simple app scared me off slightly, even though it looks like it would be a perfect fit.
So then the only thing left to do felt a little bit hacky and cheaty, so I'm asking; Would the below code be likely to get my app rejected? And if so, on what grounds?
Cheers.
- (void)pixellateImage:(UIImage *)image fromValue:(int)from toValue:(int)to

{

dispatch_queue_t bgQueue = dispatch_queue_create("bgqueue", NULL);

for (int i = from; i >= to; i--) {

    dispatch_async(bgQueue, ^{
        CIContext *context  = [CIContext contextWithOptions:nil];

        CIImage *ciImage = [[CIImage alloc] initWithImage:[UIImage imageNamed:@"c3po"]];

        CIFilter *blur = [CIFilter filterWithName:@"CIPixellate"];

        [blur setValue:ciImage forKey:kCIInputImageKey];
        [blur setValue:[NSNumber numberWithInt:i] forKey:@"inputScale"];

        CGImageRef imageRef = [context createCGImage:blur.outputImage fromRect:[blur.outputImage extent]];

        UIImage *returnImage = [UIImage imageWithCGImage:imageRef];

        CGImageRelease(imageRef);

        dispatch_async(dispatch_get_main_queue(), ^{
            self.imageView.image = returnImage;
        });
    });
}

}

A: As long as you aren't using private API's, hacky code won't get you rejected.


text:
Q: Java repository - Spring Data JPA I'm doing a dummy project in spring to remember old skills. I've implemented the following Repository.
User Repository
@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    User findByUuid(String uuid);

    User findByEmail(String email);

    @Override
    List<User> findAll();
}

User Entity with getters and setters, removed for clarity
@NamedQueries({
    @NamedQuery(name = "User.findByEmail", query = "SELECT u FROM User u WHERE u.email = :email")})
public class User implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(nullable = false)
    private Long id;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 64)
    @Column(nullable = false, length = 64)
    private String uuid;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 128)
    @Column(nullable = false, length = 128)
    private String username;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 128)
    @Column(nullable = false, length = 128)
    private String email;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 64)
    @Column(nullable = false, length = 64)
    private String password;
}

After run the project and using the query findByEmail I'm getting the following error:

java.lang.IllegalArgumentException: Parameter with that position [1]
  did not exist

So, I've searched for some possible solutions for my problem and actually found one. Replacing the query for:
User findByEmail(@Param("email") String email);

This is not my first attempt on spring and I've developed some minor projects using this framework, and I've used the normal approach without any problems. I've read the documentation trying to find an explanation for this but I didn't manage to find any.

*

*Can someone explain to me why my first attempt didn't work?

A: Please see the following jira ticket DATAJPA-733
From Oliver Gierke

You can only use named parameters in your query if you either use Java 8 with -parameters enabled for compilation or use @Param annotations on the query method arguments as documented in the reference documentation.
The reason for the required annotation is that prior to Java 8 there was no way to retain the variable names in the code for interface methods.

The workaround provided is to delete the named query


text:
Q: Width of rotated circular segment from frontal view With all in mind we know about circular segment. Is it possible to calculate "width" of the circular segment when rotated and still seen from frontal view? I know the chord (C), angle, height and radius and would like to calculate L as can be seen in image here. Notice the start (left side) of the frontal view width starts at the edge of the circular segment. Could not come up with an aproach that would allow me to calculate the length of the "width" (L) of the segment. Is it even possible to calculate?
What I have tried is to somehow fit two triangles (dotted green and black). And that is when it ends before it starts. Because there is too many unknown. I have not come up with another feasible solution.


text:
Q: Active Model Serializers nested associations that calls methods with arguments for example if I have these models with these associations
class User
  has_many :posts
  has_many :comments

  def posts_has_comments_in_certain_day(day)
    posts.joins(:comments).where(comments: { created_at: day })
  end
end

class Post
  has_many :comments
  belongs_to :user

  def comments_in_certain_day(day)
    Comment.where(created_at: day, post_id: id)
  end
end

class Comment
  belongs_to :user
  belongs_to :post
end

now I want active model serializer to get me all the users with their posts that has comments in a certain day including these comments too.
I've tried but all I could get is user with his posts that have comments in that certain day .. but I couldn't include the comments too.
thats what I did
class UserSerializer < ActiveModel::Serializer
  attributes :id, :name, :day_posts

  def day_posts
    object.posts_has_comments_in_certain_day(day)
  end
end

and this is working fine
but when I try to include the comments !!! ..
class UserSerializer < ActiveModel::Serializer
  attributes :id, :name, :day_posts

  def day_posts
    object.posts_has_comments_in_certain_day(day).map do |post|
    PostSerializer.new(
      post,
      day: instance_options[:day]
    )
  end
end

class PostSerializer < ActiveModel::Serializer
  attributes :id, :body, :day_comments

  def day_comments
    object.comments_in_certain_day(day)
  end
end

this is not working .. can any one help me with this ?

A: Call .attributes on serializer instance
class UserSerializer < ActiveModel::Serializer
  attributes :id, :name, :day_posts

  def day_posts
    object.posts_has_comments_in_certain_day(day).map do |post|
    PostSerializer.new(
      post,
      day: instance_options[:day]
    ).attributes
  end
end

if you need to customise comments attributes do the same thing for comments too.
class PostSerializer < ActiveModel::Serializer
  attributes :id, :body, :day_comments

  def day_comments
    object.comments_in_certain_day(day).map do |comment|
        CommentSerializer.new(comment).attributes
    end
  end
end


text:
Q: Problem with Schema Model type when using PrismaJS and NestJS I have Members model in my Prisma schema as follows:

where branch is a relation to Branch model with branchId foreign key.
I'm using this schema in members services as follows:

Where lastBranchFromMember returns user with populated branch in select.
The problem occurs when I want to access branch name in controllers but branch doesn't get recognize in controllers, I can only select branchId or branchOrder when I type lastBranchFromMember.branch.name

Did I do something wrong in my Prisma Schema? or do I have to do something else?
Thank you for your help.
Here I attach exported prisma client file for Member where branch does not exists but still can be access with { include: { branch: true }} I'm confused

A: You need to use { include: { branch: true } } and the return type is incorrect. It should be the following:
import { Prisma } from '@prisma/client'

type MemberWithBranch = Prisma.MemberGetPayload<{
  include: { branch: true }
}>

async lastBranchFromMember(branchId: string): Promise<MemberWithBranch> {
  // function
}


text:
Q: Solve $x = a(1-c \exp(-bx)) $ I am trying to solve the following equation
\begin{align}
x = a(1-c \exp(-bx))
\end{align}
for some $a>0$, $c \in (0,1)$ and $b\in (0,1)$.
One can find an exact solution for this equation in terms of Lambert_W function, which is given by
\begin{align}
x=\frac{W\left(-a b c e^{-a b}\right)}{b}+a
\end{align}
However, this not very useful for me.
I was wondering if instead, we can find an upper bound on the solution in terms of standard functions.

A: You can use a linear approximation for the exponential to get an upper bound for the solution. Note that $-e^{-bx} \leq -1+bx$. This gives $$x=a(1-ce^{-bx}) \\ x \leq a(1-c(1-bx)) \\ x \leq \frac{a(1-c)}{1-abc}$$
This works well when b is small. You could do an asymptotic expansion about $0$ for b if the answer when b is small is important, or a cubic approximation. A quadratic approximation is easily solvable but would give a lower bound instead.

A: You are looking for the zero(s) of function
$$f(x)=x-a \left(1-c e^{-b x}\right)$$ for which
$$f'(x)=1-a b c e^{-b x}\qquad \text{and} \qquad f''(x)=a b^2 c e^{-b x}\quad >0 \quad \forall x$$
The first derivative cancels at
$$x_*=\frac{\log (a b c)}{b}$$ which, by the second derivative test, corresponds to a minimum. So, to have roots the requirement is
$$f(x_*)\leq 0 \implies \frac{1+\log (a b c)}{b}-a \leq0$$
If this is the case, you can approximate the roots using a Taylor expansion around $x_*$. This would give
$$f(x)=f(x_*)+\frac 12 f''(x_*) (x-x_*)^2+O\big((x-x_*)^3\big)$$ which would give
$$x_\pm=x_*\pm \sqrt{-2\frac{f(x_*)}{f''(x_*)}}=\frac{\log (a b c)\pm \sqrt{2} \sqrt{a b-\log (a b c)-1}}{b}$$ from which you could start Newton method.
Now, the question is : are $x_\pm$ upper or lower bounds of the solution ? The answer is not so obvious : by Darboux theorem, since $f''(x) > 0 \,\, \forall x$, if $f(x_\pm) > 0$ then $x_\pm$ is a upper bound of the solution and if $f(x_\pm) < 0$ then $x_\pm$ is an lower bound of it (but this must be switched depending on the sign of $x_\pm$).
Let us try with $a=2$, $b=\frac 12$ and $c=\frac 13$. This will give
$$x_*=-2 \log (3)$$ $$x_-=-4 \left(\sqrt{\frac{\log (3)}{2}}+\frac{\log (3)}{2}\right)\approx -5.16\qquad x_+=4 \left(\sqrt{\frac{\log (3)}{2}}-\frac{\log (3)}{2}\right)\approx 0.77$$
$$f(x_-)\approx 1.64432\qquad\qquad f(x_+)\approx -0.77839$$
Using Lambert function or Newton iterations, the solutions are $-4.57856$ and $1.71755$.
So, effectively $x_- <0$  and $x_+>0$ make them both lower bounds of the solution.