text:
Q: Error reporting tool/service I was wondering if there is any tool out there which could be easily integrated into my existing application infrastructure and handle the error reporting. Kind of a service.
It should allow me (as an application developer) to send unhandled errors into it .. e.g. using a webservice, etc.

A: Have a look at SmartInspect.

A: Somehow none of the tools mentioned did fulfill my requests.
I have found one which meets the requirements best .. although it could require some more additions. (its open source so thats great)

*

*ELMAH

A: You should look for a bug/issue tracking system with webservice interface. For example Bugzilla is very popular. It's has an xml-rpc interface and client libraries for some langauages.

A: For global capturing of errors you will have to have some kind of application-specific handling mechanism.
For everything else use a logging framework like log4net, which can log to the Windows Event Log (which can be monitored remotely via WMI) or a remote Syslog server (which is centralised by definition).

A: I hope if Microsoft Enterprise Library will work for you.

A: We created just such a service, "BugsVoice", inspired also by your question:
http://bugsvoice.com


text:
Q: retrieving data from many to many extra column in spring jpa uisng an id I have user entity and category entity and they are as followed.One user can subscribe to many categories and similarly same category can be subscribed by many users.
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name="users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long userId;

   @NotBlank(message = "username can't be blank")
    private String username;

    @Email
    @NotEmpty(message = "Email is required")
    @Column(unique=true)
    private String email;

    @NotBlank(message = "Password is required")
    private String password;

    // Each user is going to be mapped to a Location
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(
            name = "location_id",
            referencedColumnName = "locationId"
    )
    @NotNull
    private Location location ;

    @EqualsAndHashCode.Exclude
    @ToString.Exclude
    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
    @JoinTable(name = "users_categories",
            joinColumns = {
                    @JoinColumn(name = "user_id", referencedColumnName = "userId",
                            nullable = false, updatable = false)},
            inverseJoinColumns = {
                    @JoinColumn(name = "category_id", referencedColumnName = "categoryId",
                            nullable = false, updatable = false)})
    private Set <Categories> categories = new HashSet<>();

}

And categories entity
@Data
@AllArgsConstructor
@Entity
@Table(name="categories")
public class Categories {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long categoryId;

    @NotBlank(message = "Please Add Category name ")
    @Length(max =100 ,min =2)
    private String categoryName ;

    @Length(max=500,min=2)
    private String categoryDescription;

    @EqualsAndHashCode.Exclude
    @ToString.Exclude
    @ManyToMany(mappedBy = "categories", fetch = FetchType.EAGER)
    private Set<User> users = new HashSet<>();

}

and I have this table where user and categories are mapped .
mysql> select * from users_categories where category_id=5;
+---------+-------------+
| user_id | category_id |
+---------+-------------+
|       3 |           5 |
|       7 |           5 |
+---------+-------------+
2 rows in set (0.00 sec)

I want to retrieve all userId with a specific category. How do we achieve this in spring boot and JPA?
Here is my user repository
import java.util.Optional;
@Repository
public interface UserRepository extends JpaRepository<User, Long>{
    Optional<User> findByUsername(String username);
}

A: I didn't test it but try to add this to your UserRepository:
  @Query("select u from User u inner join u.categories c where c.categoryId =:id")
  List<User> findByCategory(@Param("id") Long id);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Beamer poster theorem style without boxes I'm making a poster using beamer and when I use \begin{theorem} and \begin{proof} it makes the theorems and proofs in a box just like a block title would be.
I understand this is the default setting when using beamer but I want my theorems and proofs to look like the default when just writing an article in LaTeX. Is there a way I can change the theorem style or theorem environment so that theorem and proof are no longer in boxes?

A: The style is defined by

*

*\setbeamertemplate{theorem begin} and

*\setbeamertemplate{theorem end}
Check page 122 of beameruserguide.pdf. In the following I have just deleted the \inserttheoremblockenv commands from the definition in the manual.
\documentclass[]{beamer}
\usetheme{boadilla}
\setbeamertemplate{theorem begin}{{
\inserttheoremheadfont
\inserttheoremname
\inserttheoremnumber
\ifx\inserttheoremaddition\@empty\else\ (\inserttheoremaddition)\fi%
\inserttheorempunctuation
}}
\setbeamertemplate{theorem end}{}
\begin{document}
\begin{frame}
\begin{theorem}
Hello World!
\end{theorem}
\end{frame}
\end{document}

A: Here is a naive approach at defining your own mytheorem and myproof environments.

\documentclass{beamer}% http://ctan.org/pkg/beamer
\usetheme{Warsaw}

\newenvironment<>{mytheorem}[1][]
  {\alert{\upshape\textbf{Theorem}} #1\hspace*{\fill} \\
   \itshape}
  {}
\makeatletter
\newenvironment<>{myproof}[1][\proofname]{%
  \par
  \def\insertproofname{#1\@addpunct{.}}%
  \pushQED{\qed}
  \alert{\textbf{\insertproofname}} \hspace*{\fill} \\}
{\popQED}
\makeatother

\begin{document}
\begin{frame}
  \frametitle{This is a frame title}
  \begin{theorem}
    This is a theorem statement.
  \end{theorem}

  \begin{proof}
    This is a theorem proof.
  \end{proof}
\end{frame}

\begin{frame}
  \frametitle{This is a frame title}
  \begin{mytheorem}
    This is a theorem statement.
  \end{mytheorem}

  \begin{myproof}
    This is a theorem proof.
  \end{myproof}
\end{frame}

\end{document}

In the above example, mytheorem typesets Theorem using in boldface, upright and "alerted" font (\alert{\upshape\textbf{...}}) just to show that there is freedom in the formatting. The same goes for myproof.
It would be possible to completely duplicate the theorem environment that would allow (1) a bracketed optional argument and (2) even a theorem number, if needed. However, since this still forms part of a presentation where numbering doesn't make much sense, it's been left out. At the moment, specifying an optional parenthesized theorem addition is obtain using \begin{mytheorem}[(...)].
Defining your own, new environment for theorems and proofs allows you to switch between or back to the regular theorem and proof environments, if needed.


text:
Q: Conjure Dragon Priest spell Ok, just recently got all dragon priests masks and I read on the Wiki that once I get Konahrik's mask I should have the ability to summon dragon priests. It's not in my conjuration spells, I can't buy it anywhere, is there a certain skill level that I have to be in conjuration that lets me obtain it?

A: The way it works is you wear the mask and when you're low on health the mask automatically activates one of two effects. The first one knocks back nearby enemies, activates flame cloak, and heals you and your allies. The other one is conjure Dragon Priest. It's not really an additional spell, but more of a safety net.

A: Once you get Konahrik's mask, while wearing it, when your health drops below a certain threshold it has a chance to activate one of two effects, one is that it summons a dragon priest (Supposedly Konahrik himself) to protect you and assist you with attacking enemies he can also conjure his own atronachs, and second the mask emmits a shockwave not unlike unrelenting force which knocks enemies within range backwards and deals minor damage, it then gives you a moderately damaging flame cloak which burns enemies for every second they are in melee range and heals you and any allies around you (Very much like the Avoid Death Restoration perk but without the daily limit)
These effects may not activate all of the time but it has a high chance to do so.


text:
Q: Is there a way to single out data within an SQL column?
So I'm working with an old joomla site and trying to export only useful data, and I found a pretty hacky way of accomplishing what I wanted to do.
So for the column I want to get to, images, even though there's been no useful information input into it, joomla automatically populates it with the following:
{"image_intro":"","float_intro":"","image_intro_alt":"","image_intro_caption":"","image_fulltext":"","float_fulltext":"","image_fulltext_alt":"","image_fulltext_caption":""}

I Ideally only want to search for fields where the value for image_fulltext is not empty, and only get the value of the field.
My original idea was this hacky snippet just to find the relevant rows at least.
SELECT id, images FROM `JOOMLAPREFIX_content` WHERE images !='{"image_intro":"","float_intro":"","image_intro_alt":"","image_intro_caption":"","image_fulltext":"","float_fulltext":"","image_fulltext_alt":"","image_fulltext_caption":""}'

This gets the me the relevant rows, but it also gets me more information than I want. (The first suggested solution, while a much less "hackey" query, gets me the same result, as you can see in the SQL snippet.)
Id          Images

7           {"image_intro":"","float_intro":"","image_intro_alt":"","image_intro_caption":"","image_fulltext":"images\/featuredimage1832014.jpg","float_fulltext":"","image_fulltext_alt":"","image_fulltext_caption":""}

Is there a way to target only the value of image_fulltext, in the case of this row: "images/featuredimage1832014.jpg"?
SQL Fiddle

A: Try this:
SELECT id, images FROM `JOOMLAPREFIX_content` WHERE images NOT LIKE '%"image_fulltext":""%'


text:
Q: What options do I have to do a cached searching in my objects with Entity Framework 6 I have a MVC 5 app running with EntityFramework 6.
On of the pages will be search results returned based on a query from users. The data is not updating that offen and it would not be a problem if search results are cached.
I am using unity for dependency injection of the entity framework context. Its in the default case of giving a new instance on every controller (hence on every request).
What can I do to cache the search results?
Should I change such there are not returned a new context on every controller and let entity framework cache the objects?
Can I just enable some caching in MVC and leave it at that?

A: Have a look at Entity Framework extended nuget package. We use it for Caching EF queries. Although we use EF5. If it doesn't work it may be just a case of getting its source and adjust a few namespaces
Alternatively just manually cache your EF result (make sure you have it fully loaded by enumerating to list). Either cache it without filtering (if you have huge variability) or cache filtered versions and just cache that in HTTP cache. Could also create a query service that gets your data for you. Could cache the data in the query service or alternatively if you want cleaner code you could use a decorator to wrap the query service to give you cached versions
Your context per request is the correct setup. Every request should have a new context. Don't try to have a long lived context it will cause you no end of troubles.
Could also enable page level output caching of MVC (and make sure you cache based on parameters passed) However your mileage on that may vary depending on number and ranges of paramters


text:
Q: Which design pattern can I use to solve this situation? First of all, I'm using Objective-C, but this doesn't matter at all.
My situation is:
I have two different scenarios. I distinguish them by a preprocessor macro like:
#ifdef USER
    do some stuff for scenario 1
#else
    do some stuff for scenario 2

Both scenarios works with a list of items all across the application, but the difference is the way of getting those items.
In the first one I get the items by sending a request to a server.
In the second one, I get them from the local device storage.
What I have now is the second scenario implemented. I have a singleton class that returns to me the list of items by getting them from the local storage. (like a traditional database singleton)
I want to add the other scenario. Since the items can be get from any point across the app, I want this to be a singleton too.
Does it make sense to have a singleton superclass, and then two subclasses that implement the different ways of getting the items? Singleton hierarchies sound quite strange to me.

A: Factory combined with Strategy.
Factory as the pattern of using another class to make your instance rather than using just a constructor. You are already doing that with your Singleton most likely.
Strategy for the ability to configure which kind of object is actually created by the factory at rutime.

A: That's not exactly hierarchy. The superclass you're mentioning is actually an interface for your 2 concrete classes, which can be singletons if you want. The interface is an abstract entity thus any instance-related term is irrelevant to it.
You're statically defining your program behavior by using preprocessor to do the scenario choice. If you stick to this approach and it fits your requirements, you don't need any design patterns. In your code just use the interface I mentioned above, which is a port to your statically instantiated data. If you want to have more flexibility (this sounds likely), you can do your scenario choice at runtime. In this case you may find the Strategy pattern useful for applying scenarios and Factory pattern for instancing.


text:
Q: database comparison/ API calls I have a scenario where I am comparing 2 databases. One is the central database which I don't have access to and another is my local database which I can access. The developers would be making some API calls to the central database and populating our local database( around 5000 records). After it is done, I would have to compare the records if they are retrieved correctly and that nothing has been missed. Please suggest me the best solution to do this. I have the following in my head -
A)Make API call to the central database for the key tab and retrieve all the records as a response
 Then make API call to the local data store for the similar entity and then compare both the records (HOW?)
B) Make API call to the central database and after I have got the response for the desired fields write SQL query to compare both..
C) Any other better, quicker and accurate approach?
Thanks


text:
Q: Vuex do not mutate vuex store state outside mutation handlers - Vuetify I am building a nuxt app with Vuetify. My use case is that i want to implement a global bottom-sheet.
My code below works fine until when i click outside the sheet and it throws an error.
What am I missing below?
Error: [vuex] do not mutate vuex store state outside mutation handlers.

What i have tried so far.
<template>

    <v-bottom-sheet v-model="$store.state.sheet">
      <v-card>
        <v-card-title>Hi there</v-card-title>
        <v-card-subtitle>This is a demo sheet</v-card-subtitle>
      </v-card>
    </v-bottom-sheet>
    <v-btn class="mt-5" @click="openSheet">Sheet</v-btn>

</template>

Store/index.js
export const state = () => ({
  sheet: false
})

export const mutations = {
  openSheet(state){
    state.sheet = !state.sheet
  }
}

A: When you clicked outsise, you tried to modify the state directly. You need to mofify it with a mutation, one way is to create a computed property and set it to v-model:
<template>

    <v-bottom-sheet v-model="sheet">
      <v-card>
        <v-card-title>Hi there</v-card-title>
        <v-card-subtitle>This is a demo sheet</v-card-subtitle>
      </v-card>
    </v-bottom-sheet>
    <v-btn class="mt-5" @click="openSheet">Sheet</v-btn>

</template>


text:
Q: objective c mapkit click button in annotation Hi i have a map view page in my app where i display 200 + markers.
I initiate these at present with
MapViewAnnotation *newAnnotation = [[MapViewAnnotation alloc] initWithTitle:currentobjectarray.title andCoordinate:location];

These produces a text label when the marker is clicked.  How can i add a button to the annotation view so that when it is clicked i can navigate to a "more info" page for the selected marker?.  Its the button part i am not sure of.
Any help much appreciated

A: You need to create a UIButton and assign it to the rightCalloutAccessoryView property of your MKAnnotationView.
In the mapView:viewForAnnotation: method, where your are returning you custom MKAnnotationView instance, insert this code to create a button and associate it with an action.
I assumed that your MKAnnotationView instance is called annotationView and that your method to be called is presentMoreInfo.
UIButton * disclosureButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[disclosureButton addTarget:self
                     action:@selector(presentMoreInfo)
           forControlEvents:UIControlEventTouchUpInside];
annotationView.rightCalloutAccessoryView = disclosureButton;

Your presentMoreInfo method can be something like
- (void)presentMoreInfo {
    DetailsViewController * detailsVC = [DetailsViewController new];

    //configure your view controller
    //...

    [self.navigationController pushViewController:detailsVC animated:YES];
}


text:
Q: Scanning for Java executable I'd like my program to scan the user's hard drive for java.exe.
I was considering using a for-loop and then going through each directory and then check if the directory names match the ones I would set up and then check in those for the java exe, but I'm sure there is a much more efficient way of doing so.
Any ideas on how to approach this?
Edit:
I've gone ahead and done some foreach loops, but it isn't going too well. I'm probably missing something:
// Scan for Java executable (java.exe)
        foreach (String dir in Directory.GetDirectories("C:/"))
        {
            if (dir == "Program Files")
            {
                foreach (String _dir in Directory.GetDirectories(dir)) {
                    if (_dir == "Java")
                    {
                        foreach (String javaDir in Directory.GetDirectories(_dir))
                        {
                            if (javaDir == "jre7")
                            {
                                foreach (String binDir in Directory.GetDirectories(javaDir)) {
                                    if (binDir == "bin")
                                    {
                                        foreach (String file in Directory.GetFiles(binDir))
                                        {
                                            if (file == "java.exe")
                                            {
                                                javaExe = file;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

A: Do you only want to see if java.exe is there?
File.Exists(@"C:\Program Files\Java\jre7\bin\java.exe")

You might need additional logic to look in the Program Files (x86) folder if needed. Also this will obviously fail if the user installed java somewhere else.
If you want to know where is java, take a look at this other Stack Overflow post.

A: You are looking for java.exe. So
Firstly you should look for directory where oracle always install it's java.exe
which should be at

C:\Windows\System32

to limit your search and then search in other directories.
         var paths = new List<string>
        {
           Environment.SystemDirectory,
           Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)+@"\java",
           Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)+@"\java",
           Environment.GetFolderPath(Environment.SpecialFolder.Programs)+@"\java"
           //C:\
           //rest
        };
        foreach (string path in paths)
        {
            var ser = Search("java.exe", path);

            if (!string.IsNullOrEmpty(ser))
            {
                if (File.Exists(ser))
                {
                    javaExe = ser;
                    break;
                }
            }
        }

Search function:
 private static string Search(string pattern, string root)
    {
        if (!Directory.Exists(root))
        {
            return string.Empty;
        }
        var paths = new Queue<string>();
        paths.Enqueue(root);
        while (paths.Count > 0)
        {
            root = paths.Dequeue();
            string[] temp = Directory.GetFiles(root, pattern);
            foreach (string t in temp)
            {
                return t;
            }
            temp = Directory.GetDirectories(root);
            foreach (string t in temp)
            {
                paths.Enqueue(t);
            }
        }

        return string.Empty;
    }

Also it's preferred to use this search method to avoid Access permissions.
Note:
You could find java.exe in more than one place.


text:
Q: What actions are required when your app get an applicationWillResignActive call? This question io3->ios4 upgrade said to support applicationWillResignActive.  While implementing this call, I also implemented applicationDidEnterBackground and applicationWillEnterForeground.  However, I found that my app would crash.  After some debugging on the simulator I determined that I needed to reinitialize a key data structure in applicationWillEnterForeground.  So my question is how would I have known that from reading the documentation?  (In fact, I may be doing the wrong thing and just so happened to get it working again.)  Is there an exact description of what to do when these methods are called?
Thanks.

A: The only things you should do when supporting multitasking, is saving the state of your app when it enters the background, and reload it when it becomes active. (If you generate a new template in Xcode, you'll see this.)
Saving state means writing any user preferences or data to disk. Reloading the state involves reading saved preferences and data, recreating any in memory data structures that might need it (like in your example you gave).
In most circumstances, there's little else you need to do. The only thing that would crash your app that is unique to multitasking would be trying to run code in the background for longer than the allotted amount of time, (which is 10 minutes.) Otherwise, it sounds like you have got other problems with your code.


text:
Q: Manage Delegate out UIViewController class I would like to understand what would be the best way to implement a delegate out UIViewController class
How can I manage the delegate using controller: UIViewController parameter of my function in AuthManager?
These are the two classes I'm working with .. I show you small examples to make you understand
 class StartController: UIViewController {

    @objc private func presentAuthFacebookController() {
        AuthManager.signInWithFacebook(controller: self)
    }
}

class AuthManager {
static func signInWithFacebook(controller: UIViewController) {

    let loginManager = LoginManager()
    loginManager.logIn(permissions: [.publicProfile, .email], viewController: controller) { (result) in

        switch result {
        case .cancelled : print("\n AuthFacebook: operazione annullata dall'utente \n")
        case .failed(let error) : print("\n AuthFacebook: \(error) \n")
        case .success(granted: _, declined: let declinedPermission, token: _):

            let authVC = ExistingEmailController()

            authVC.delegate = // ?????? (controller)

            UIApplication.shared.windows.first?.rootViewController?.present(authVC, animated: true, completion: nil)
        }
    }
}
}

A: I personally don't think StartController should know about/conform to ExistingEmailControllerDelegate. But if you really want, you can declare controller as a composition type:
static func signInWithFacebook(controller: UIViewController & ExistingEmailControllerDelegate) {
    ...
    authVC.delegate = controller

In my opinion, the whole point of having a AuthManager is to create a layer of abstraction on top of ExistingEmailController, and to encapsulate the logic of authentication. Therefore, StartController shouldn't know, or care, about ExistingEmailControllerDelegate. It only knows about AuthManager.
AuthManager should be the delegate of ExistingEmailController, which implies that signInWithFacebook should not be static, and AuthManager can have an AuthManagerDelegate that StartController conforms to:
class AuthManager : ExistingEmailControllerDelegate {
    weak var delegate: AuthManagerDelegate?

    func signInWithFacebook(controller: UIViewController) {

        ...

        let authVC = ExistingEmailController()

        authVC.delegate = self

        UIApplication.shared.windows.first?.rootViewController?.present(authVC, animated: true, completion: nil)
    }

    func someMethodFromExistingEmailControllerDelegate() {
        delegate?.someMethod() // delegating it self.delegate, which StartController conforms to
    }
}

protocol AuthManagerDelegate : class {
    func someMethod()
}

 class StartController: UIViewController, AuthManagerDelegate {

    var authManager: AuthManager!

    override func viewDidLoad() {
        authManager = AuthManager()
        authManager.delegate = self
    }

    @objc private func presentAuthFacebookController() {
        authManager.signInWithFacebook(controller: self)
    }

    func someMethod() {
        // write here the code that you would have written in someMethodFromExistingEmailControllerDelegate
    }
}


text:
Q: how to track language changes in iPad? I'm new in developing  iOS app. So I've recently faced a problem with localization of my app. I would like to perform some actions in response to language change in system settings.
To get language ID I use
[[NSLocale preferredLanguages] objectAtIndex:0];

in applicationDidFinishLaunchingWithOptions method. First time it returns language ID right (e.g. "en" for English).  Then, I close my application (or send it to background) and change language to German. After that I restart my app, but instead of "de", it still returns "en". I think my app might probably store old settings somewhere... but where exactly? How to retrieve valid current value?

A: take a look at this old answer:
Getting current device language in iOS?
EDIT:
NSString *testLang = [[NSLocale preferredLanguages] objectAtIndex:0];
NSString *testLang1 = [[NSLocale preferredLanguages] objectAtIndex:1];
NSString *testLang2 = [[NSLocale preferredLanguages] objectAtIndex:2];
NSString *testLang3 = [[NSLocale preferredLanguages] objectAtIndex:3];
NSString *testLang4 = [[NSLocale preferredLanguages] objectAtIndex:4];
NSLog(@"LINGUA SYS:%@:%@:%@:%@:%@",testLang,testLang1,testLang2,testLang3,testLang4);

in debugger console:
LINGUA SYS:en:it:fr:de:ja
or:
LINGUA SYS:es:en:it:fr:de
or:
LINGUA SYS:pt-PT:en:es:it:fr
so the code you posted is right, the error should be somewhere else...

A: if you do something like that:
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"en",@"es", nil] forKey:@"AppleLanguages"];

the value is stored on NSUSerDefaults and changes on settings don't apply.

A: I found the source of my problem. It was iOS Simulator. I installed my app on device and all problems disappeared.


text:
Q: Cordova file plugin returns non existed path I want to get the path to the folder where some files will be downloaded from my server. This code looks like:
// Get path to cache and download
window.resolveLocalFileSystemURL(cordova.file.externalCacheDirectory, entry => {
   console.log('download to', entry);
   // My download function
   fileDownload('some string url', entry.toUrl());
}, err => {
   console.log('error', err);
});

// Download function
function fileDownload(url, fileURL) {
  let fileTransfer = new FileTransfer();
  let uri = encodeURI(url);

  fileTransfer.download(
      uri,
      fileURL,
      entry => {
          console.log("download complete: " + entry.toURL());
      },
      error => {
         console.log("download error", error);
      },
      true
  );

  return fileTransfer;
}

If config.xml contains lines
<preference name="AndroidPersistentFileLocation" value="Internal"/>
<preference name="AndroidExtraFilesystems" value="files, cache, sdcard, cache-external, files-external"/>

this races error FileError.code = 5 (ENCODING_ERR)
If used Compatibility
<preference name="AndroidPersistentFileLocation" value="Compatibility"/>

this returns entry path file:///storage/emulated/0/Android/data/<my-app-id>/cache but this path does not exist in my Nexus 5 and the code with download races error 1 (FILE_NOT_FOUND_ERR)
FileTransferError {...}
body: null
code: 1
exception: "/storage/emulated/0/Android/data/<my-app-id>/cache: open failed: EISDIR (Is a directory)"
http_status: 200
source: "http://my.domain.com/photos/photo.jpg"
target: "file:///storage/emulated/0/Android/data/<my-app-id>/cache/"

I see in ES File Manager correct path as /sdcard/Android/data/<my-app-id>/cache and think the problem is that.
Any ideas how to get correct path?


text:
Q: Getting all the tenants a user belongs to using grah api I have an app which uses the AUTH v2 auth provider and the common tenant (login.microsoftonline.com/common/v2.0/) for authentication.
Now, since my users can belong to any AAD tenant, and I want my users to be able to select the tenant in which they are performing operations, I started looking for a way to get all the AAD tenants the logged-in user is part of.
I went through the graph API (graph.microsoft.com) documentation and the closest I could find was this: https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/user_getmemberobjects) but it looks like this operation requires the 'Directory.Read.All' scope which according to graph.microsoft.io/en-us/docs/authorization/permission_scopes requires 'admin consent'.
Is there a way to get all the tenants a logged in user has access to using the graph api, and without requiring admin consent?

A: This API is not available.  Can you indicate the scenario that requires this API, please? Also please file a request for this feature/API on uservoice.


text:
Q: MS Word Mail Merge field format lost when using FieldMergingCallback in aspose word I have a template that have some merge fields that are in side and out side a table. The values for these fields are query and cached to map then set to the field by a cusstom FieldMergingCallback, here is the java code:
// doc is a Document object
doc.getMailMerge().setFieldMergingCallback(new IFieldMergingCallback() {
    @Override
    public void fieldMerging(FieldMergingArgs arg0) throws Exception {
        if (fieldCache.containsKey(arg0.getFieldName())) {
            arg0.setText(fieldCache.get(arg0.getFieldName()));
        }
   }

   @Override
   public void imageFieldMerging(ImageFieldMergingArgs arg0) throws Exception {
       return;
   }
});

The problem is I lost all field format (\* Caps, \* Upper, etc…) when using setText method, I have tried to call doc.updateFields() after the call to executeWithRegions() but the format still lost.
How can I reserve format in the call back?
This is a legacy system so we are stuck in aspose word 14.5.0

A: You can use field code to get switches and format the value accordingly. Please see the following code:
        doc.getMailMerge().setFieldMergingCallback(new IFieldMergingCallback() {
            @Override
            public void fieldMerging(FieldMergingArgs args) throws Exception {

                // This is a dummy value.
                String value = args.getFieldName();
                // Get field code to check formatting switches.
                String fieldCode = args.getField().getFieldCode(false);

                // Format the value according to the switches in the field code.
                if (fieldCode.contains("\\* Upper"))
                    value = value.toUpperCase();
                if (fieldCode.contains("\\* Lower"))
                    value = value.toLowerCase();

                args.setText(value);
            }

            @Override
            public void imageFieldMerging(ImageFieldMergingArgs arg0) throws Exception {
                return;
            }
        });

Hope this helps.
Disclosure: I work at Aspose.Words team.

A: UPDATE 02-2020: Aspose word 20.2 has implemented this feature. https://forum.aspose.com/t/merge-field-format-lost-when-using-fieldmergingcallback/206900/5
According to the replies to the same question of mine on aspose forum, currently there is no support for keeping formatting in FieldMergingCallback. So, I end up with a work around, the idea is in every call back, I create a fake document and clone the current field to this fake document, excute it to get the final result, then set it back to the actual field with setText function:
doc.getMailMerge().setFieldMergingCallback(new IFieldMergingCallback(){
    @Override
    public void fieldMerging(FieldMergingArgs e)throws Exception{
        if(cache.containsKey(e.getFieldName())){
            Document fakeDoc=new Document();
            DocumentBuilder builder=new DocumentBuilder(fakeDoc);
            builder.insertField(e.getField().getFieldCode());
            fakeDoc.getMailMerge().setFieldMergingCallback(new IFieldMergingCallback(){
                @Override
                public void fieldMerging(FieldMergingArgs arg)throws Exception{
                    DocumentBuilder innerBuilder=new DocumentBuilder(arg.getDocument());
                    innerBuilder.moveToMergeField(arg.getFieldName(),false,false);
                    innerBuilder.startBookmark(arg.getFieldName());
                    innerBuilder.moveToMergeField(arg.getFieldName(),true,false);
                    innerBuilder.endBookmark(arg.getFieldName());
                }

                @Override
                public void imageFieldMerging(ImageFieldMergingArgs arg){

                }
            });
            fakeDoc.getMailMerge().execute(new String[]{e.getFieldName()},new Object[]{cache.get(e.getFieldName())});
           // Set the formatted text to the actual field
            e.setText(fakeDoc.getRange().getBookmarks().get(0).getText());
        }
    }

    @Override
    public void imageFieldMerging(ImageFieldMergingArgs args){
    }
});


text:
Q: PHP : Execute sql queries in background I'm using PHP (Yii framework) and Postgresql for the db. Basically a wappstack. I just mentioned them if ever they are a concern for this problem.
Anyway, what i'm trying to achieve is I have a submit action:
public function actionSubmitData($id){

    //Execute Sql queries here

$this->render('view',array(
                //some data
            ));
}

The problem is that I will be processing a large amount of data; About 50,000 records will be processed in each of 4 tables of roughly 10 columns each table, that is fairly large. The use case is that the user submits, then the sql statements are executed in background, but the view 'view' should already be rendered, not requiring the user to wait for the records to be processed. He/she can check on it later on after the records are processed.
A normal request would execute sql statements first, then render the view. The problem is when the page takes about 3-5 min. The page never loads; and the creation of records is not finished, just a white page appears when the requests are intensive.
In other words, how do I execute sql queries in background? Leaving the user able to browse the application still while the request is being processed? And somewhere in the background, records are being processed? What is the workaround for this problem? Thanks!

A: I'd suggest push your queries (jobs) to some messaging system as RabbitMQ or Gearman. It will let do your work in parallel. You even be able scale your jobs easily.

*

*Gearman: Getting Started

*Gearman: Examples

*Yii German extension

A: It must be done using Cron Job.

*

*User submits data.

*System writes all data to some temp file for later use.

*User is redirected to view page to continue browsing.

*Cron Job process looks for new file, marks it as in process and process it.

*Cron Job deletes file after processing.

Since Cron Job runs in CLI, you will not get timeout of script.


text:
Q: Is this component being rendered? I'm trying to do the same thing as this answer, then created a component named ProtectedRoute.
Placed ProtectedRoute in App.tsx. This is supposed to render multiple ProtectedRoute components maping over ProtectedRoutes.
When the ProtectedRoute component gets rendered it sends an HTTP request to verify the token.
useLayoutEffect(() => {
        axios
            .get('http://localhost:5000/authorization', {
                withCredentials: true,
            })
            .then((response) => {
                setHasValidToken(true);
                console.log('valid token!');
            })
            .catch((error) => {
                if (error.response.data.message) {
                    console.error(error.response.data.message);
                } else {
                    console.error(`Error: ${error}`);
                }
                setHasValidToken(false);
                navigate('/login');
            });
    }, [navigate]);

Based on the result, it sets the state hasValidToken. Then return the following.
return (
        <>
            {hasValidToken ? (
                <Route path={path} element={element} />
            ) : (
                <Navigate to="/login" />
            )}
        </>
    );

However, this ternary operator seems not working correctly.  What's more, it never console log the messages in the component. (I placed some console.log in the component)
I also tried to comment out everything inside return in the component, but still all protected route's path got rendered.
It's weird that all routes still can be rendered even though ProtectedRoute returns nothing.
I hope this makes sense and get help to figure out what's going on and what I might miss.


text:
Q: How to parse any constant Lua table preferably without loading it in the Lua VM? I have a bunch of data in the form of a Lua table and I would like to parse that data into a usable structure in C#.
The problem with Lua tables is that there are optional fields, tables are very dynamic and are not just a dictionary with one type for the key and one type for the value. It's possible to have one Lua table with both string and integer keys, and values of type integer, string and even table.
Sadly, the data that I'm parsing makes use of the dynamic nature of the language and isn't really structured in any straight-forward way. This requires a dynamic representation of the data, using for example Dictionary<object, dynamic>.
The format of the data is e.g. (from http://ideone.com/9nzXvt)
local mainNode =
{
    [0] =
        {
            Name = "First element",
            Comments = "I have comments!",
            Data = { {123, 456}; foo = { "bar" } }
        },
    [1337] =
        {
            Name = "Another element",
            Data = { {0}; foo = nil }
        }
}

Are there any libraries out there to do this? Is there any way to accomplish this without parsing the data character by character?

A: You can use the luainterface library
There's some sample code here.
You'll want to use a combination of DoFile (to load the file) and GetTable to read the table into a LuaTable object that you can use the result from c#. The LuaTable exposes an IDictionaryEnumerator through GetEnumerator.
EDIT:
if you had this table constructor:
local t = { os.time() }
print(t[1]);

the function in the constructor would need to be executed to initialize the data.
for constant literals, you can have string constants like so:
local a = [==[
  hello
  there""\"]==]

with different levels of equal signs
a numeric literal can have the form:
0X1.921FB54442D18P+1

with P as a binary exponent.
faithfully reproducing the lua syntax for constant literals without using the lightweight lua VM would require re-implementing a good chunk of the lua language spec. not much benefit it re-inventing the wheel.

A: I know this is an old post, but this could be useful for people who arrive here after this post...
You could also look at Xanathar's MoonSharp (Moon#) project; I have just started to try it and it seems to work well with wrapping up the dynamic tables, with nested tables etc. You just give the interpreter a a script and it will parse and hold the parsed objects in the interpreter context.
Links:

*

*http://www.moonsharp.org

*https://github.com/xanathar/moonsharp/
Example:
[TestMethod]
    public void Test_GetProperty_ForValidTypeAndKey_ReturnsValue()
    {
        // Arrange
        String luaScript = MockLuaScripts.TEST_OBJECT_WITH_STRING;
        Script context = new Script();
        String expectedResult = MockLuaScripts.ValidValue1;

        // Act
        /* Run the script */
        context.DoString(luaScript);

        /* Get the object */
        DynValue resultObject = context.Globals.Get(MockLuaScripts.ObjectInstance1);

        /* Get the property */
        DynValue tableValue = instance.Table.Get((MockLuaScripts.ValidKey1);
        String actualResult = tableValue.String();

        /* Or you can use..
            String actualResult = tableValue.ToObject<String>();
        */

        // Assert
        Assert.AreEqual(expectedResult, actualResult);
    }

Apologies if the above code is not exactly correct as it is taken from one of my test classes and converted for posting here. Please excuse the wrapped up mock-data constants, but they are in essence the Lua script and expected values.
When trying to access entries in Lua table via an incorrect key the DynValue has a DataType of "Nil", so are easy to handle with a conditional check.
More examples on usage of Xanathar's Moonsharp can be found on Xanathar's website and his git hub repo. (See links below). He seems to be very helpful with any issues or questions that you may come across too.
Links:

*

*http://www.moonsharp.org

*https://github.com/xanathar/moonsharp/
I have started to write some extensions which have units test which show further usage in one of my repos (See links below)
Links:

*

*https://github.com/dibley1973/MoonsharpExtensions


text:
Q: How to authorize logged in users using Google Auth JWT? (Picture) I currently have a backend running on AWS Lambda and I'm using DynamoDB as a database. In Dynamo, there is a list of users and each user has specific permissions as to what routes they have access to through the API. There is no issue here.
I have not built the front end yet, but I will be logging in users using Google Auth, more specifically with the react-google-login component.
My question is: Once a user is logged in to the site, should I trust the JWT from Google (after verifying its legitimacy
here with the Google API) which returns the user information (Name, Email), lookup the user item inside of Dynamo to retrieve their permissions, and then serve their request?
This seems like the logical thing to do but I was looking for some confirmation. My one worry is that someone could use a supervisors name & email to authorize a request but if the lambda must accept a JWT created by Google as entry, I believe this problem is solved correct?
I have API Keys as well for every user for some external functionality, but I have that covered since it's just a Dynamo call away. My only concern is with the front end requests to Lambda since I do not want to roll my own auth/jwt.
Here is what I was envisioning.
Thank you!

A: Normally you should use access tokens for that purpose. The ID token should be meant only to authenticate the user, and the access token should be used to authorize access.
The best scenario would be to have a separate Authorization Server which could issue access tokens, and there are some open source solutions out there which you can use.
If you really don't want to setup your own AS then you could follow the scenario you outlined - the part with verifying JWT from Google and checking permissions in the DynamoDB is what the Authorization Server would normally do to issue an access token.
Just remember to thoroughly validate the incoming JWT - not only the signature with Google, but also check if that is a token created for your client / audience, etc. Otherwise someone could take a Google ID token JWT from their client and gain access to your API. This article lists best security practices when working with JWTs.
Also remember that ID tokens might have short expiration times and there are no means of automatically refreshing them (like you can do it with a refresh token in case of an access token), so you might end up having to reauthenticate quite often.


text:
Q: tileLayers grouped in layerGroup not displaying I am trying to combine 3 tileLayers (Esri map services for imagery, boundaries, roads) into one layerGroup so that it can be chosen via the layers control.
This jsfiddle shows the three tileLayers initially loaded individually ok.  But the layerGroup doesn't work (the map is gray) when 'Grouped' is chosen via the L.control.layers.

A: you just need to add the layerGroup combo to the layers option, otherwise it is not added to the map. This is just a convenience. You can also add each layer individually, for example combo.addTo(map)
var map = L.map('map', {
    center: [39.73, -104.99],
    zoom: 10,
    layers: [img, bnd, transport, combo]
});

updated fiddle


text:
Q: Tableau extracts update I would like to know if there's a way to automatically update my extracts?
I have a live connection with redshift and use tableau desktop and publish some workbooks on tableau online.
I like to share some reports using extracts and tableau reader and I really need a way to update the extracts everyday

A: if I understand your question correctly, you should be able to refresh your Tableau Data Extracts by setting up "Refresh Schedules" on Tableau Online. Tableau Online supports variety of Data Sources to set up Extracts instead of using Live Connection.
Check this link on setting up refresh schedules.
Hope this helps!

A: Yes, you can do set refresh schedule that will help you to update your extract automatically without any manual effort but there are some terms & conditions you have to follow:

*

*For this you have to set your dashboards/workbooks/project in "Extract" mode & not in LIVE.

*I personally recommend "extracts" instead of LIVE until the person who is looking for this need REAL TIME updates

*Also, you need to set this schedule from Admin's ID (Publisher access) which you use to publish your work from Desktop to Online

*Note: You only can choose from lot of options already available
enter image description here


text:
Q: What is best practise to migrate On-premises SQL Server to Azure VM - Dynamic SQL Agent Jobs in AlwaysOn offering I am trying to migrate On-premises SQL Server to Azure VM.
I am writing in reference to below link
https://azure.microsoft.com/en-in/documentation/articles/virtual-machines-migrate-onpremises-database/#azure-vm-deployment-wizard-tutorial
I am having multiple applications in which few are hosted in Azure and few are On-premises.
All these applications contact on-premise SQL Server for data manipulations.
In some scenario these applications creates dynamic SQL Agent Jobs!
Now my requirement is to move on-premise SQL Server to Azure cloud. I would like to know how can I manage these dynamic SQL Agents in Azure?
In short, My question is: how can I migrate below items?

*

*SSIS packages associated with these databases

*SQL Agent Jobs scheduled in server (created dynamically)

*File Stream associated with server databases

Also I am planning to use SQL Server "AlwaysOn" offering.  So how to synch these SQL Agent Jobs in these shared Virtual Machines?
I was referring https://azure.microsoft.com/en-us/documentation/articles/sql-database-general-limitations/ and it says as follow

Microsoft Azure SQL Database does not support SQL Server Agent or
  jobs. You can, however, run SQL Server Agent on your on-premises SQL
  Server and connect to Microsoft Azure SQL Database.

SQL Agents can be dynamically created as shown here https://www.mssqltips.com/sqlservertip/3052/simple-way-to-create-a-sql-server-job-using-tsql/  My question is, will these stored procedures run in azure cloud?
Update
It's challenge but can be done. We need to setup new Job, which constantly monitors and pull the current role of the replica, based on PRIMARY role, we run the job needs to do if it is the primary.
Below link gives me hint
https://dba.stackexchange.com/questions/45137/sql-server-agent-jobs-and-availability-groups but I am looking for step by step blog/article to achieve this.


text:
Q: ModemManager behavior on SIM card switch Hey I am building an embedded linux device using Yocto, that will transmit some data via GSM network. It will work in a rough conditions, poor GSM range, so it will switch SIM cards often to find the best network.
My question is - does the modem manager rewrites the current APN during each sim card switch? Or does it use already saved?
I am asking this, beacause I witnessed GSM modems' flash being killed after like 3 months, because of APN being rewrited on each network switch.
Thanks!


text:
Q: Issue with weighted data in lmer() and model averaging using glmulti() I am having hard time while performing Linear Mixed Models (LMM) on data with weights (I mean the weight of the different groups differs). Furthermore, it seems that weights are not kept while using glmulti(). Below is a reproducible example:
require(lme4)
require (glmulti)
data(cake)
cake$wght <- as.numeric(cake$replicate)
fm1 <- lmer(angle ~ recipe + temperature + (1|replicate), cake, REML= FALSE)
print(VarCorr(fm1),comp=c("Variance","Std.Dev."))

In this case residual variance of the random effect equals 22.36.
fm2 <- lmer(angle ~ recipe + temperature + (1|replicate), cake, weights=wght,REML= FALSE)
print(VarCorr(fm2),comp=c("Variance","Std.Dev."))

And here,residual variance of the random effect is now 155.
For linear models, residual variance remains unchanged whatever the weights, while it seems not to be the case here.
The second issue occurs when performing a model averaging with weighted data. It seems that glmulti() does not account for specified weights in the following examples:
wlmer.glmulti <- function (formula, data, random = "", weights ,...) {
lmer(paste(deparse(formula), random), data = data, weights)}
#(watch out doesn't converge!!)
LMM <- glmulti(angle ~ recipe + temperature  , data=cake,  random="+ (1|replicate)", fitfunc =      wlmer.glmulti, weights=cake$wght,report=T, level = 1,crit="aic",method="g")
summary(LMM@objects[[1]])  # is similar to fm1

Any suggestion is most welcome. Thanks

A: A short answer to my own post above.
1/ Dealing with weights in Linear Mixed Models:
To avoid large inflation of residual variances of the RE due to weight, once can "simply" ensure that the sum of all weights equal 1.
2/ Integrating weights into model averaging procedure (glmulti)
Directly insert the weights into the wrapper (thanks to Vincent Calcagno for the tip).
From previous example:
wlmer.glmulti <- function (formula, data, random = "", weights ,...) {
lmer(paste(deparse(formula), random), data = data, weights)}

Updated working alternative
wlmer.glmulti <- function (formula, data, random = "", weights ,...) {
lmer(paste(deparse(formula), random), data = data, data$wght)}

Hope this will be useful at some point ;)


text:
Q: DDD - What is a complex domain? It is often said that DDD (Domain-driven Design) is better suited for complex domains instead of simpler ones.
What characterizes a complex domain? (please be more specific than "it has complex business rules");
Which are examples of complex domains?
How can I classify a domain as complex (i.e. suitable for DDD) or not?

A: From my experience 3 most important thing that makes your domain complex:
Size
Big domains tends to increase complexity. Handling and coordinate a lot of things is always hard.
Rules and invariants
Domains (even domains with just a couple of bounded context) might have a lot of domain rules and invariants and/or a lot of nuances in its use cases and process. This increase complexity. Rules that spam a lot of changes in a entity  or inter-domains events are often the complex business rules.
Context
Context complexity is hard to explain wihtout a example. Let's put in the table a context complexity related to a entity named Product.
Depending of context; a entity could means different things in your domain. A Product entity doesn't means the same for Factory context, Marketing context, Sales context, PostSales support context, etc.
If the data, user cases, process, behaviour, etc related to Product entity, in every context, are very different the complexity increase a lot even when you just have a handful of context and entities. This usually means that you have many Product entities (one in every context) even if all of them are supported by the same persistence store (in case of ER store, the same table/s).

A: There is no unique definition of complexity, but there is a useful description in Vaughn Vernon book (Implementing Domain Driven Design) : Table 1.1 The DDD Scorecard.
He describes the project with different criteria, for example : a complex project is going to change often (new features and it will be hardly to anticipate), you don't fully understand the domain (or there is a lot of ambiguity that you need to discuss with business expert), the size as @jlvaquero said (number of feature/rules/richness of the language...).

A: In my opinion, one sign of complex domains is degree of hardness of creating and maintaining Ubiquitous Language.
As the vocabulary, phrase, and terminology become more diverse, creation of UL become more difficult. This confirms the complexity of the domain.


text:
Q: Windows network shares still visible (and accessible) with "file and printer sharing" deactivated I just migrated a windows server VPS to a new one (Windows Server 2012 R2) and realized that even though "Turn off file and printer sharing" is selected for all available network profiles (Public/Guest, Private) within the "Network and Sharing Center", it is still possible to externally access the server's shares.
The windows firewall is enabled (and in use) for all network adapters on the system (there is just the one), the default inbound action is to block, and I ensured that all relevant inbound firewall rules are actually disabled ("File and Printer Sharing..." for ports 137, 138 UDP and 139, 445 TCP).
"Password protected sharing" is selected as well.
Any idea why it is still possible to see and access the shares?
As a workaround, I am now explicitly blocking the ports, which works as expected, but this should be unnecessary in the first place.

A: Alright, so this guy's troubleshooting basically provided the solution:
Why is file sharing over internet still working, despite all firewall exceptions for filesharing being disabled?
He states:

It's the "built-in" rules for Terminal Services that was the problem. Can you believe port 445 (File Sharing Port) has to be wide open to the internet to use Terminal Services Licensing?)

So in my case, it wasn't anything terminal service related, but the following two rules, that were allowing traffic through port 445 TCP:

*

*Remote Access Management (NP-In)

*File Server Remote Management (SMB-In)

Disabling those two firewall rules finally made all shares invisible and inaccessible.
Though in the end, I am going to stick with my explicit blocking rules after all, since it is obvious now that a lot of different services are using this ports functionality. And I don't want to have to remember to recheck the accessibility of the shares every time I reconfigure something somewhere in the system.


text:
Q: How to add a linked source folder from a remote machine in Android Studio? Trying to follow this post How to add a linked source folder in Android Studio?,
I tried
sourceSets {
    main.java.srcDirs += 'src/main/\\\\10.11.12.13\\me\\workspace\\myapp\\src'
}

However it does not display the source folder.
If I do
sourceSets {
    main.java.srcDirs += '\\\\10.11.12.13\\me\\workspace\\myapp\\src'
}

Then the sources are visible but outside my project app tree. How to get them inside?

A: this worked for me:
in app/main/build.gradle
android {
...
    sourceSets {
        main.java.srcDirs += '\\\\\\10.11.12.13\\me\\workspace\\myapp\\src'
    }
}


text:
Q: Xdebug 3 docker mac PhpStorm broken pipe I see There was a problem sending 179 bytes on socket 11: Broken pipe. in the xdebug.log and cannot see why. Have gone around in circles for days trying all sorts of stuff. What am I doing wrong?

*

*Xdebug 3.0.3,

*PhpStorm 2020.3.3,

*Mac OS X latest,

*Safari browser

[17] Log opened at 2021-03-24 02:49:43.184877
[17] [Step Debug] INFO: Checking remote connect back address.
[17] [Step Debug] INFO: Checking header 'HTTP_X_FORWARDED_FOR'.
[17] [Step Debug] INFO: Checking header 'REMOTE_ADDR'.
[17] [Step Debug] INFO: Client host discovered through HTTP header, connecting to 172.18.0.1:9003.
[17] [Step Debug] INFO: Connected to debugging client: 172.18.0.1:9003 (from REMOTE_ADDR HTTP header). :-)
[17] [Step Debug] -> <init xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" fileuri="file:///var/www/manawatech/public/index.php" language="PHP" xdebug:language_version="8.0.3" protocol_version="1.0" appid="17" idekey="19213"><engine version="3.0.3"><![CDATA[Xdebug]]></engine><author><![CDATA[Derick Rethans]]></author><url><![CDATA[https://xdebug.org]]></url><copyright><![CDATA[Copyright (c) 2002-2021 by Derick Rethans]]></copyright></init>

[17] [Step Debug] -> <response xmlns="urn:debugger_protocol_v1" xmlns:xdebug="https://xdebug.org/dbgp/xdebug" status="stopping" reason="ok"></response>

[17] [Step Debug] WARN: 2021-03-24 02:49:43.851075: There was a problem sending 179 bytes on socket 11: Broken pipe.
[17] Log closed at 2021-03-24 02:49:43.851495

docker-compose.yml
version: "3.8"
services:
  web:
    container_name: web
    build:
      context: .
      dockerfile: docker/php/Dockerfile
    ports:
      - "80:80"
      - "443:443"
      - "9003:9003"
    volumes:
      - .:/var/www/manawatech
    extra_hosts: # <-- this is required for ray
      - "host.docker.internal:host-gateway" # <-- this is required for ray
  db:
    container_name: db
    image: mysql
    command: --default-authentication-plugin=mysql_native_password
    volumes:
      - ./var/mysql:/var/lib/mysql
    ports:
      - "3306:3306"
    environment:
      MYSQL_RANDOM_ROOT_PASSWORD: "yes"
      MYSQL_DATABASE: "${MYSQL_DATABASE}"
      MYSQL_USER: "${MYSQL_USER}"
      MYSQL_PASSWORD: "${MYSQL_PASSWORD}"

docker/php/Dockerfile
FROM php:8-apache-buster
RUN apt update \
    && apt install -y geoip-bin geoip-database libgeoip-dev libpng-dev libzip-dev
RUN pecl channel-update pecl.php.net \
    && pecl install redis apcu xdebug \
    && docker-php-ext-install pdo pdo_mysql gd zip \
    && docker-php-ext-enable redis apcu xdebug pdo pdo_mysql gd zip
# from https://github.com/nezhar/php-docker-ssl/blob/master/Dockerfile
RUN openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/ssl-cert-snakeoil.key -out /etc/ssl/certs/ssl-cert-snakeoil.pem -subj "/C=AT/ST=Vienna/L=Vienna/O=Security/OU=Development/CN=manawatech.local"
RUN a2dissite 000-default.conf \
    && a2enmod rewrite ssl expires headers
COPY docker/php/apache.conf /etc/apache2/sites-enabled/
COPY docker/php/98-production.ini /usr/local/etc/php/conf.d/
COPY docker/php/99-development.ini /usr/local/etc/php/conf.d/
RUN mv "$PHP_INI_DIR/php.ini-production" "$PHP_INI_DIR/php.ini"
EXPOSE 80
EXPOSE 443
EXPOSE 9003

/usr/local/etc/php/conf.d/99-development.ini
[xdebug]
xdebug.mode=debug
xdebug.discover_client_host=true
xdebug.client_host=host.docker.internal
xdebug.start_with_request=trigger
xdebug.force_display_errors=1
xdebug.log=/tmp/xdebug.log


text:
Q: Google place API pricing and queries uplift request Regarding the usage of Google Place API, Google allows 1000 queries per 24 hour for this Place API, and 100,000 queries per 24 hour if the account is verified with a credit card. Exceeding 100,000 queries per 24 hour, we can write to Google to request for an uplift.
Does anyone have any experience with lifting the limits for the queries of Place API?
And if you didn't get approved, what is the Google's pricing model for exceeding usage of the queries?
Thanks

A: There is currently no pricing model for Places API as it is a free service. If you exceed your usage you will simply receive "status": "OVER_QUERY_LIMIT" in response to any subsequent Places API requests. Even if billing is enabled, you will not be charged for the use of the Places API.
If you apply for a Places API Quota Uplift, as long as your application meets the Google Maps Terms of Service and Places API Requirements, you should receive an uplift in quota.


text:
Q: Changing color of Ball Type in swift 2 I am trying to fill my ball in my swift game with two colors> I want them to be half white and half blue. I have tried changed the ball to a SKSpriteNode but it ruins the whole project and all of the physics. Is there anyway to make a Ball type two colors or place an image over the ball? thanks

A: Instead of use SKSpriteNode, try to use SKShapeNode:
let textureBall : SKTexture! = SKTexture(imageNamed:"ball.png")
let ballSize: CGSize = textureBall.size
ball = SKShapeNode.init(circleOfRadius: ballSize.width/2)
ball.fillTexture = textureBall
ball.strokeColor = UIColor.clearColor()
ball.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMidY(self.frame))
ball.name = "ball"
ball.zPosition = 1
ball.fillColor = UIColor.redColor() // use the color you want
self.addChild(ball)


text:
Q: Xcode 4.5.2 no more link to the crash when I click on the backtrace on Thread, no symbolicated On Xcode 4.5.2 when my application Crashes I didn't have the crash's line on my code.
The crash is not symbolicated.
I just put this line to test my crash handler:
NSMutableArray *arr = [NSMutableArray array];
[arr objectAtIndex:2];

I got this message when my application crashes:
libobjc.A.dylib`_cache_getImp:
0x204c048:  movl   8(%esp), %ecx
0x204c04c:  movl   4(%esp), %edx
0x204c050:  pushl  %edi
0x204c051:  movl   8(%edx), %edi
0x204c054:  pushl  %esi
0x204c055:  movl   (%edi), %esi
0x204c057:  movl   %ecx, %edx
0x204c059:  shrl   $2, %edx
0x204c05c:  andl   %esi, %edx
0x204c05e:  movl   8(%edi,%edx,4), %eax
0x204c062:  testl  %eax, %eax
0x204c064:  je     0x204c06f                 ; _cache_getImp + 39
0x204c066:  cmpl   (%eax), %ecx
0x204c068:  je     0x204c080                 ; _cache_getImp + 56
0x204c06a:  addl   $1, %edx
0x204c06d:  jmp    0x204c05c                 ; _cache_getImp + 20
0x204c06f:  popl   %esi
0x204c070:  popl   %edi
0x204c071:  jmp    0x204c086                 ; _cache_getImp + 62
0x204c073:  nopw   %cs:(%eax,%eax)
0x204c080:  popl   %esi
0x204c081:  popl   %edi
0x204c082:  movl   8(%eax), %eax
0x204c085:  ret
0x204c086:  xorl   %eax, %eax
0x204c088:  ret
0x204c089:  nopl   (%eax)

No more link to the crash's line.
Thanks.

A: I fixed this by Unchecking this option:
Product > Debug Workflow > Show disassembly when debugging
And done!


text:
Q: Visual Studio 2003 can't navigate to the definition of "IIdentity" or "StringTable" I have the following code:
using System;
using System.Collections;
using System.Security;
using System.Security.Principal;

public class SystemPrincipal : IPrincipal {

    private IIdentity       _identity;
    private StringTable     _roles;

    public SystemPrincipal(IIdentity id, StringTable roles) {

        _identity = id;
        _roles = roles;;
    }

    public IIdentity Identity {

        get { return _identity; }
    }

    public bool IsInRole(String role) {

        bool result = false;

        if (null != _roles) {
            result = _roles.Contains(role);
        }
        return result;
    }
}

I want to see the definition of IIdentity or StringTable so I right click and choose
goto definition but I get "cannot naviate to" IIdentity or StiringTable.
Based on a google soultion I rebuilt the project but that did not solve the issue.


text:
Q: Field not found: pixelToWorld (com.uwsoft.editor.renderer.data.ProjectInfoVO) I got this error when compile desktop application:
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.SerializationException: Field not found: pixelToWorld (com.uwsoft.editor.renderer.data.ProjectInfoVO)
at com.badlogic.gdx.utils.Json.readFields(Json.java:776)
at com.badlogic.gdx.utils.Json.readValue(Json.java:902)
at com.badlogic.gdx.utils.Json.fromJson(Json.java:714)
at com.uwsoft.editor.renderer.resources.ResourceManager.loadProjectVO(ResourceManager.java:334)
at com.uwsoft.editor.renderer.resources.ResourceManager.initAllResources(ResourceManager.java:86)
at com.uwsoft.editor.renderer.Overlap2DStage.initSceneLoader(Overlap2DStage.java:92)
at com.mygdx.Test.GameStage.<init>(GameStage.java:9)
at com.mygdx.Test.TestGame.create(TestGame.java:15)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:143)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)

I have check my project.dt and I found field 'pixelToWorld'. Why is this happen?
Here to view my project.dt: http://pastebin.com/FqnVkw8p

UPDATE:
I follow this tutorial: making-physics-based-side-scroller-project-setup-part-1
I only have 2 class in my core project. GameStage.java and TestGame.java
GameStage.java
package com.mygdx.Test;

import com.uwsoft.editor.renderer.Overlap2DStage;

public class GameStage extends Overlap2DStage{
    public GameStage() {

        // This will create SceneLoader instance and configure all things like default resource manager, physics e.t.c
        initSceneLoader();

        // This will load MainScene data from json and make Actors from it
        sceneLoader.loadScene("MainScene");

        // Get the root actor and add it to stage
        addActor(sceneLoader.getRoot());
    }
}

TestGame.java
package com.mygdx.Test;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class TestGame extends ApplicationAdapter {

    private GameStage stage;

    @Override
    public void create () {
        stage = new GameStage();
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(0.8f, 0.8f, 0.8f, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        stage.act();
        stage.draw();
    }
}

A: I've been looking into sources you can find here and what I've found is that the sceneLoader.loadScene() method returns the object with Scene that is being kept in HashMap with .dt (I guess it is something like .json) file name.
The thing is that method loadScene() is looking for a pixelToWorld field but there is no pixelToWorld in MainScene.dt
I guess you should call sceneLoader.loadScene("project"); or you have done something wrong with MainScene.dt and this is why there is no pixelToWorld

A: I think the problem is that you are using the latest version of the Overlap IDE, but a too early version of the runtime.
Try upgrading your runtime to 1.1 and try again, although you will probably have to use sceneloader


text:
Q: Chrome version must be between 71 and 75 error after updating to ChromeDriver 2.46 After update of chromedriver to version 2.46 my tasts fail to initialize.
I got message like this:
Starting ChromeDriver 2.46.628402 (536cd7adbad73a3783fdc2cab92ab2ba7ec361e1) on port 44269
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
Failed to invoke configuration method com.personal.CustomTest.initTests not created: Chrome version must be between 71 and 75
  (Driver info: chromedriver=2.46.628402,platform=Windows NT 10.0.16299 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 1.58 seconds
Build info: version: '2.53.1'

It is clearly saying that my browser version is not valid. But I am using Chrome 72.0.3626.119 so it is between 71 and 75.
Selenium version is 2.53.1.
And I am running test through console command with the help of testNG.
Any idea? Every ideas that I found was about changing selenium version but I cant do it.

A: This error message...
Starting ChromeDriver 2.46.628402 (536cd7adbad73a3783fdc2cab92ab2ba7ec361e1) on port 44269
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
Failed to invoke configuration method com.personal.CustomTest.initTests not created: Chrome version must be between 71 and 75

...implies that the ChromeDriver v2.46 is not compatible with the Chrome Browser version which is being accessed by your program/webdriver.
Your main issue is the incompatibility between the version of the binaries you are using as follows:

*

*You are using chromedriver=2.46

*Release Notes of chromedriver=2.46 clearly mentions the following :

Supports Chrome v71-73

*

*Though you mentioned you are using Chrome 72.0.3626.119 possibly there are multiple instances of Chrome Browser installed within your system and your program by default is accessing the Chrome Browser whose version is not between v71.x and v75.x

*You are using chrome=67.0

*Release Notes of ChromeDriver v2.38 clearly mentions the following :

Supports Chrome v65-67

Solution

*

*Keep JDK upgraded to  recent levels JDK 8u201.

*Uninstall all the instances of Chrome Browser (you can opt to use Revo Uninstaller).

*Upgrade ChromeDriver to  current ChromeDriver v2.46 level.

*Keep Chrome version between Chrome v71-73 levels. (as per ChromeDriver v2.46 release notes)

A: For me to resolve this problem :
On Windows
cd C:\Users\[myname]\AppData\Roaming\npm\node_modules\protractor
npm i webdriver-manager@latest
webdriver-manager update
webdriver-manager start &

On Cent-OS (I used Cent-OS 7.4.* and it worked fine.)
cd /usr/lib/node_modules/protractor/
sudo npm i webdriver-manager@latest
sudo webdriver-manager update
sudo webdriver-manager start &

I hope this helps you in any way.

A: For me, I had to update my chrome driver in my project to match the version of Chrome on my local machine.
yarn add chromedriver@76.0.0 -D
https://www.npmjs.com/package/chromedriver

A: In my case I was getting the same error after my chrome was updated to version 76. Which was happening when chimp tries to use chromedriver to execute the selenium test.
DevTools listening on ws://127.0.0.1:49220/devtools/browser/e88586cb-ed67-44fc-a742-43b767e2b8f9
    [chimp][helper] setupBrowserAndDDP had error
    { Error: session not created: Chrome version must be between 71 and 75
        at Object.wait (C:\ACPMS\ELS_AT\node_modules\fibers\future.js:449:15)
        at Object.<anonymous> (C:\ACPMS\ELS_AT\node_modules\wdio-sync\build\index.js:344:27)
        at Object.<anonymous> (C:\ACPMS\ELS_AT\node_modules\chimp\dist\lib\session-manager.js:145:21)
        at initBrowser (C:\ACPMS\ELS_AT\node_modules\chimp\dist\lib\chimp-helper.js:189:43)
        at Object.setupBrowserAndDDP (C:\ACPMS\ELS_AT\node_modules\chimp\dist\lib\chimp-helper.js:264:7)
        at Context.<anonymous> (C:\ACPMS\ELS_AT\node_modules\chimp\dist\lib\mocha\mocha-helper.js:13:15)
        at C:\ACPMS\ELS_AT\node_modules\chimp\dist\lib\utils\fiberize.js:29:22
        (Driver info: chromedriver=2.46.628402 (536cd7adbad73a3783fdc2cab92ab2ba7ec361e1),platform=Windows NT 10.0.17134 x86_64)
        at new RuntimeError (C:\ACPMS\ELS_AT\node_modules\webdriverio\build\lib\utils\ErrorHandler.js:143:12)
        at Request._callback (C:\ACPMS\ELS_AT\node_modules\webdriverio\build\lib\utils\RequestHandler.js:318:39)
        at Request.self.callback (C:\ACPMS\ELS_AT\node_modules\request\request.js:185:22)
        at emitTwo (events.js:106:13)
        at Request.emit (events.js:191:7)
        at Request.<anonymous> (C:\ACPMS\ELS_AT\node_modules\request\request.js:1161:10)
        at emitOne (events.js:96:13)
        at Request.emit (events.js:188:7)
        at IncomingMessage.<anonymous>

For me it didn't work when I updated the chrome driver by npm (both globally and locally) and then I followed these steps to resolve the issue, which might give some idea on where to check in this kind a issue:

*

*Because exception was thrown in node_modules\chimp\dist\lib\utils\fiberize.js i navigated to that file and found one level above this file node_modules\chimp\dist\lib\chromedriver.js which has the code to start chromedriver.

*I added a console.log to chromedriverPath which can be seen below and re-executed the tests to get the chromedriver path in console logs.

    Chromedriver.prototype.start = function(callback) {
          var self = this;
          var port = self.options.port;

          if (this.child) {
            callback();
            return;
          }

          var chromedriverPath = chromedriver.path;

          //this was added my me the see that chrome drive path
          console.log("[chimp] " + chromedriverPath);

          if (fs.existsSync(chromedriverPath)) {
            this.child = processHelper.start(
              {
                bin: chromedriverPath,
                prefix: "chromedriver",
                args: ["--port=" + port, "--url-base=wd/hub"],
                waitForMessage: /Starting ChromeDriver/,
                errorMessage: /Error/
              },
              callback
            );
          } else {
            callback("[chimp][chromedriver] Chromedriver executable not found.");
          }
        };

*When i got the path of the chromedriver which is used to execute the tests, i just navigated to that folder and replaced chromedriver executable with the most recent version.

I hope this helps.

A: Try this: Download the compatible ChromeDriver.exe file for the updated version of Chrome browser and replace it. It works for me.


text:
Q: Point exists in boundaries of line As a human, it's relatively easy to see a load of points and find an obvious pattern.
e.g turning

into

What I'm trying to do is to find out whether point x, would sit on the black line on image 2, if I've only got the points of image 1, preferably using .net, but I should be able to convert other languages (whether coding / general math formulas) whether by using a plugin or not. I'm not overly fussed it being an "image", just done for visualisation.
I realise the title and tags aren't the best, but not sure on the right description and how to categorise the question. :-)

A: I made some experiments with your 1st image in Corel Paint Shop and applied these operations: Erode, Erode, Median filter 5, Dilate. The result resembles your second image. The way to go is to do such experiments and then to implement it by using an image processing library.

"Erode" adds a dark border around dark pixels, i.e., it erodes the bright parts. The end effect after applying it twice is that the inner and outer dotted lines merge together and form a very thick line. The Median filter makes smoother lines and closes small wholes. "Dilate" expands the bright pixels, i.e., it makes the very thick line thinner.
You can improve the result by applying some blur at the beginning (this makes rounder shapes) and then reduce the number of colors to 2 at the end to get a sharp image.


text:
Q: Populate/insert values in query I'm new with C, i'm trying to make simple program with sqlite3 db.
I have query like this:
sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS) "  \
     "VALUES (1, 'Paul', 32, 'California' ); " \

I have values in char* variables, is it possible to use %s like on printf for example:
sql = somefunction("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS) "  \
     "VALUES (%d, '%s', %d, '%s');", 1, 'Paul', 32, 'California');

If that is not possible what is the best way to do this?
Thanks!

A: sprintf() looks appropriate for your problem (introduced in C89).
Now simply do something like this:
sprintf(sql, "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS) "
"VALUES (%d, '%s', %d, '%s');", 1, "Paul", 32, "California");

To prevent a buffer overflow, use snprintf() (introduced in C99).

A:
     Create a buffer and fill it with the string using sprintf.
     Here's a very generic example:

     int main ()
     {
       char buffer [50];
       int n, a=5, b=3;
       n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
       printf ("[%s] is a string %d chars long\n",buffer,n);
       return 0;
     }

     Output:
     [5 plus 3 is 8] is a string 13 chars long


text:
Q: Wordpress PHP FIle not running I have a custom search form on my website with this code:

<form action="orderstatus.php" method="POST">

  <input type="text" name="OrderLineNumber" value="">

  <input type="submit" value="Submit">
</form>

And although I call orderstatus.php to action . When I press the submit button I get this Url : blablabla.de/action_page.php?OrderLineNumber=+23563623
This means instead of running orderstatus.php it's running action_page.php
My orderstatus.php is trying to print One Select Row from database like this :
<!DOCTYPE html>

<?php
$servername = "*******";
$username = "*******";
$password = "*******";
$dbname = "********";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM OrderStatus";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc() & fetch_assoc() = $_POST["name"] ) {
        echo "
 Order Line Number: ". $row["OrderLineNumber"]. " - Date Started: ". $row["Date Started"]. " " . $row["Status"] . "
";
    }
} else {
    echo "0 results";
}

$conn->close();
?>


text:
Q: Flutter Project: Errors All updated information here: Flutter Project : Errors (mostly with Android Manifest and Main Activity files)
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="polacoenchile.world_time_app2">
   <application
        android:label="world_time_app2"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

This is how look my file, I never touch there nothing so I have no idea what is wrong. On the picture i am showing all errors. I make analyze because on emulator all is working good. I made .apk file to install on my phone, i made it but applicacion is not showing nothng, just grey background.
Anyone know what is wrong?
my app project errors
android project
android project errors
mainactivity file
MainActivity file
package polacoenchile.world_time_app2

import io.flutter.embedding.android.FlutterActivity

class MainActivity: FlutterActivity() {
}

FLutter doctor found few problems after downgrade flutter to stable version. But i am sure i add plugins to my android studio : Flutter , Dart
C:\Users\wdowk>flutter doctor -v
[√] Flutter (Channel stable, 1.22.6, on Microsoft Windows [Version 10.0.18363.1379], locale pl-PL)
    • Flutter version 1.22.6 at C:\src\flutter
    • Framework revision 9b2d32b605 (5 weeks ago), 2021-01-22 14:36:39 -0800
    • Engine revision 2f0af37152
    • Dart version 2.10.5

[√] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at C:\Users\wdowk\AppData\Local\Android\Sdk
    • Platform android-30, build-tools 30.0.3
    • Java binary at: F:\Program Files\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)
    • All Android licenses accepted.

[!] Android Studio (version 4.1.0)
    • Android Studio at F:\Program Files\Android Studio
    X Flutter plugin not installed; this adds Flutter specific functionality.
    X Dart plugin not installed; this adds Dart specific functionality.
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b01)

[!] Connected device
    ! No devices available

! Doctor found issues in 2 categories.

A: You Commented on the part where you shouldn't commented out , If you fix this line all will be working
   <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />


text:
Q: Recieving POST data and converting to base64 produces qualityloss Im sending in data through post and get a png back in the response. Convert it to base64 so i dont have to save the file. The image is a qr code and it seems to suffer from some quality loss since iPhones cant seem to scan it, androids are fine.
Ive tried setting some encoding settings but that didnt do anything.
The data seems to be read correctly but im guessing that the center logo is to choppy to be read by the iphones.
Any ideas?
Public Sub updateSwish()

    Dim getPrice As Integer = 100

    Try
        Dim data As String = "{'format':'png','size':300,'message':{'value':'test','editable':false},'amount':{'value':" + Total.ToString + ",'editable':false},'payee':{'value':'123456789','editable':false}}"
        Dim json As JObject = JObject.Parse(data)

        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
        Dim s As HttpWebRequest = HttpWebRequest.Create("https://mpc.getswish.net/qrg-swish/api/v1/prefilled")
        Dim enc As UTF8Encoding
        Dim postdata As String
        Dim postdatabytes As Byte()
        enc = New System.Text.UTF8Encoding()
        postdata = json.ToString
        postdatabytes = enc.GetBytes(postdata)
        s.Method = "POST"
        s.ContentType = "application/json"
        s.ContentLength = postdatabytes.Length

        Dim myresponse As HttpWebResponse
        Dim returnval As System.Drawing.Image

        Using stream = s.GetRequestStream()
            stream.Write(postdatabytes, 0, postdatabytes.Length)
        End Using

        Using mStream As New MemoryStream()
            Dim imgByte As Byte()

            myresponse = CType(s.GetResponse(), HttpWebResponse)
            returnval = Image.FromStream(myresponse.GetResponseStream(), True, True)

            returnval.Save(mStream, returnval.RawFormat)
            imgByte = mStream.ToArray()

            Dim base64String As String = Convert.ToBase64String(imgByte, 0, imgByte.Length)
            imgSwish.Src = "data:image/png;base64," & base64String

        End Using

    Catch ex As Exception
        Me.Page.ClientScript.RegisterStartupScript(Me.GetType(), "ex", "alert('" + ex.Message + "');", True)
    End Try

End Sub

EDIT:
Turns out that the provider had a v2 coming out due to problems from iphones. The code was fine all along, and the base64 conversion worked as it should. I tried doing the same project i PHP and got the same result.

A: The problem should not the base64 encoding in here. Encodings do not change the data itself, it just represents it in an other format. Like a substitution cipher called ROT13 you can change the representation of your plaintext of

EXAMPLE

to

RKNZCYR

You can play with this behaviour with a lot of online tool like this one. Therefore BASE64 must not be the problem here. (You can also test your generated image before the encode and decode, this will be problematic as well for some products to be read.)
The line where you specify the data
Dim data As String = "{'format':'png','size':300,'message':{'value':'test','editable':false},'amount':{'value':" + Total.ToString + ",'editable':false},'payee':{'value':'123456789','editable':false}}"

seems suspicious. This is quite a lot of characters to be encoded in a QR code if the size variable refers to the pixel size. The minimum size I can read with that size of data is at least 400px*400px sized. What I see from your code it should work if you can increase the size to generate somethig like this image:

TL.DR.: increase the resolution of your QR code for your large data, to allow every platform to read the QR code in a reliable manner or simply change the generator.


text:
Q: How to return Completable from void methods I've got the following piece of code and it works perfectly when my inner data structure of the writerObj is CopyOnWriteArrayList (concurrent one) and it crashes when I use ArrayList.
Here're my questions:

*

*But there's only one thread in RxJava by default, isn't it?

*Will the lines (between player { ... }) execute in sync way?

My code looks as follows:
.flatMapCompletable { player -> {
    writerObj.write(player); // void write(Player player) adds player to inner data structure using ds.add()
    return Completable.complete();
    }
}

A: Depends on how the rest of your chain is coded.
Have a look at the following:
List<String> writerObj = new ArrayList<>();

Observable.range(0, 1000)
        .map(i -> Observable.just("hello world"))
        .flatMap(obs -> obs
                .flatMapCompletable(elem -> {
                        writerObj.add(elem);
                        System.out.println(Thread.currentThread().getName()  + " executing");
                        return Completable.complete();
                })
                .toObservable()
                .subscribeOn(Schedulers.io())
        )
        .blockingSubscribe();
//Size of the list is not always 1000
System.out.println("The size of the list is : " + writerObj.size());

If you execute the code above, you might notice that the size of the List at the end is not always 1000. If you change the Implementation of List to CopyOnWriteArrayList, we get the desired result.
If you want the code in the flatMap to execute sequentially and by one thread at a time, change the flatMap to concatMap.
List<String> writerObj = new ArrayList<>();

Observable.range(0, 1000)
    .map(i -> Observable.just("hello world"))
    .concatMap(obs -> obs
            .flatMapCompletable(elem -> {
                    writerObj.add(elem);
                    System.out.println(Thread.currentThread().getName()  + " executing");
                    return Completable.complete();
            })
            .toObservable()
            .subscribeOn(Schedulers.io())
    )
    .blockingSubscribe();
// Size is always 1000
System.out.println("The size of the list is : " + writerObj.size());

Hope it helps!


text:
Q: Conversion of C# datetime to sql server datetime is throwing an error In C# a DateTime property with value {27-01-2017 12.00.00 AM} is being passed in a data table to a procedure with an UTT parameter. UTT also has the same datatype datetime. I am using the generic method provided below. I cannot explicitly convert data type.

Error : The conversion of a nvarchar data type to a datetime data type
  resulted in an out-of-range value. The data for table-valued parameter
  @UttParameter doesn't conform to the table type of the parameter.
  SQL Server error is: 242, state: 3
  The statement has been terminated.

public static DataTable ToDataTable<T>(IList<T> items, bool usePropertyMappingName = false)
    {
        DataTable dataTable = null;

        if (items != null)
        {
            using (dataTable = new DataTable(typeof(T).Name))
            {
                dataTable.Locale = System.Globalization.CultureInfo.InvariantCulture;

                // Get all the properties.
                PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

                foreach (PropertyInfo prop in props)
                {
                    string columnName = prop.Name;

                    if (usePropertyMappingName)
                    {
                        var mappingAttribute = prop.GetCustomAttributes(typeof(PropertyMappingAttribute), true).FirstOrDefault() as PropertyMappingAttribute;

                        if (mappingAttribute != null && !string.IsNullOrEmpty(mappingAttribute.Name))
                        {
                            columnName = mappingAttribute.Name;
                        }
                    }

                    // Setting column names as Property names.
                    dataTable.Columns.Add(columnName, prop.PropertyType);
                }

                foreach (T item in items)
                {
                    var values = new object[props.Length];
                    for (int i = 0; i < props.Length; i++)
                    {
                        // Inserting property values to data table rows.
                        values[i] = props[i].GetValue(item, null);
                    }

                    dataTable.Rows.Add(values);
                }
            }
        }

        return dataTable;
    }

A: Remove the quotation marks

"@UttParameter"

@UttParameter

A: You are using InvariantCulture as DataTable locale. Invariant culture expects Date to be in yyyy-MM-dd format.

A: Your code - as it is now - will transfer any value on string level. This is a really bad approach. The implicit conversions taking place are highly depending on your system's settings (language and culture). The worst part is: This might work all great on your machine while you are testing it, but on a customer's system it breaks with strange messages. Happy Debugging :-(
Change your code like this
foreach (PropertyInfo prop in props) {
    // Setting column names as Property names.
    if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
        dataTable.Columns.Add(prop.Name, prop.PropertyType.GetGenericArguments()[0]);
    else
        dataTable.Columns.Add(prop.Name, prop.PropertyType);
}

This will add the column - even if this is a nullable type - with the correct data type.
credits: This answer helped me
UPDATE Even simpler
(thx to Yves M. in a comment below the linked answer)
foreach (PropertyInfo prop in props) {
    // Setting column names as Property names.
        dataTable.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}


text:
Q: How to make the div be edge to edge with sides of the viewport? [Edit] I'm building a basic survey form for a Freecodecamp exercise and would like the top div container to reach the edge of the viewport on both sides, but there is a gap on the left-hand side. I would like to eliminate this gap.

Here's my code:

html,
body {
  overflow-x: hidden;
  background-color: #ffffff;
  background-image: url(https://images.pexels.com/photos/1103970/pexels-photo-1103970.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2);
  background-attachment: fixed;
  background-repeat: no-repeat;
}

.heading {
  text-align: center;
}

#title {
  width: 500%;
  margin-left: -200%;
  background-color: rgba(255, 255, 255, 0.3);
  font-family: Calibri, Tahoma, Arial;
  font-size: 35px;
  font-weight: 500;
  color: #272a2b;
  border-radius: 5px;
  padding: 10px 0px 10px 0px;
}
<!DOCtype html>

<link rel="stylesheet" href="styles.css">

  <metacharset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Registration Form</title>

Registration Form

Tell us about yourself

  <form id="survey-form">

        Name
        <input type="text" id="name" name="name" placeholder="Enter Your Name Here" required>

        Email
        <input type="email" id="email" name="email" placeholder="Enter Your Email Here" required>

        Age
        <input type="number" id="number" name="age" min="13" max="110" placeholder="Enter Your Age">

            Which option is your ideal role?
        <select name="dropdown" id="dropdown">
          <option value="" disabled selected hidden>Select your ideal role</option>
          <option name="ideal-role" value="software-engineer">
            Software Engineer
          </option>
          <option name="ideal-role" value="software-developer">
            Software Developer
          </option>
          <option name="ideal-role" value="data-analyst">
            Data Analyst
          </option>
          <option name="ideal-role" value="web-developer">
            Web Developer
          </option>
          <option name="ideal-role" value="mobile-app-developer">
            Mobile App Developer
          </option>
        </select>

        How many hours per day can you study?

        <input type="radio" name="study-hours" id="1-hour" value="1-hour">
        1 Hour

        <input type="radio" name="study-hours" id="2-hours" value="2-hours">
        2 Hours

        <input type="radio" name="study-hours" id="3-hours" value="3-hours">
        3 Hours

        <input type="radio" name="study-hours" id="4-hours" value="4-hours">
        4 Hours

        Check which activities you enjoy:

        <input type="checkbox" name="checkbox" id="problem-solving" value="problem-solving">
        Problem Solving

        <input type="checkbox" name="checkbox" id="mathematics" value="mathematics">
        Mathematics

        <input type="checkbox" name="checkbox" id="data-analysis" value="data-analysis">
        Data Analysis

        <input type="checkbox" name="checkbox" id="graphic-design" value="graphic-design">
        Graphic Design

        Add any other comments here:
        <textarea name="comments" id="comments" placeholder="Type your comments here..." rows="8"></textarea>

        <input type="submit" id="submit" value="Submit">

  </form>

I have tried following this tip, but it only makes the right side stretch off the screen, not the left.

A: Inspecting the page, your problem is caused by the default margin present on the  tag, you can remove them by adding a margin: 0, see the corrected code :

html, body {
  margin: 0; /* Removed body margin that created the gaps */
  overflow-x: hidden;
  background-color: #ffffff;
  background-image: url(https://images.pexels.com/photos/1103970/pexels-photo-1103970.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2);
  background-attachment: fixed;
  background-repeat: no-repeat;
}

.heading {
  text-align: center;
  }

#title {
  /* Edited out, you don't actually need this to achieve what you want */
  /* width: 500%;
  margin-left: -200%; */
  background-color: rgba(255,255,255,0.3);
  font-family: Calibri, Tahoma, Arial;
  font-size:35px;
  font-weight: 500;
  color: #272a2b;
  border-radius: 5px;
  padding: 10px 0px 10px 0px;
}
<!DOCtype html>

    <link rel="stylesheet" href="styles.css">

      <metacharset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>Registration Form</title>

Registration Form

Tell us about yourself

      <form id="survey-form">

          Name
          <input type="text" id="name" name="name" placeholder="Enter Your Name Here" required>

          Email
          <input type="email" id="email" name="email" placeholder="Enter Your Email Here" required>

          Age
          <input type="number" id="number" name="age" min="13" max="110" placeholder="Enter Your Age">

            Which option is your ideal role?
            <select name="dropdown" id="dropdown">
              <option value="" disabled selected hidden>Select your ideal role</option>
              <option name="ideal-role" value="software-engineer">
                Software Engineer
              </option>
              <option name="ideal-role"  value="software-developer">
                Software Developer
              </option>
              <option name="ideal-role"  value="data-analyst">
                Data Analyst
              </option>
              <option name="ideal-role"  value="web-developer">
                Web Developer
              </option>
              <option name="ideal-role"  value="mobile-app-developer">
                Mobile App Developer
              </option>
            </select>

           How many hours per day can you study?

          <input type="radio"  name="study-hours" id="1-hour" value="1-hour">
          1 Hour

          <input type="radio"  name="study-hours" id="2-hours" value="2-hours">
          2 Hours

          <input type="radio" name="study-hours" id="3-hours" value="3-hours">
          3 Hours

          <input type="radio" name="study-hours" id="4-hours" value="4-hours">
          4 Hours

          Check which activities you enjoy:

            <input type="checkbox" name="checkbox" id="problem-solving" value="problem-solving">
            Problem Solving

            <input type="checkbox" name="checkbox" id="mathematics" value="mathematics">
            Mathematics

            <input type="checkbox" name="checkbox" id="data-analysis" value="data-analysis">
            Data Analysis

            <input type="checkbox" name="checkbox" id="graphic-design" value="graphic-design">
            Graphic Design

            Add any other comments here:
            <textarea name="comments" id="comments" placeholder="Type your comments here..." rows="8"></textarea>

          <input type="submit" id="submit" value="Submit">

       </form>

A: What you are after is called "full bleed".  There are various approaches to this.