text:
Q: Method does not exist or incorrect signature I am probably missing something very basic but I can't spot it.
I get this error when I try to upload a change set to production:

CaseCommentHandler: Method does not exist or incorrect signature: CaseTriggerHandler.createRecordTypeIdHelper(String)
          Stack Trace: null

CaseCommentHandler
    public class CaseCommentHandler extends TriggerHandler {
       private void caseCommentMethod() {
           ...
           id security = CaseTriggerHandler.createRecordTypeIdHelper('Security'); //This is where the deployment fails
           ...
       }
    }

CaseTriggerHandler:
public class CaseTriggerHandler extends TriggerHandler {
    public static Id createRecordTypeIdHelper (String input){
        Id tempId = Schema.SObjectType.Case.getRecordTypeInfosByName().get(input).getRecordTypeId();
        return tempId;
    }
}

The class is working fine on Sandbox and also, when I deployed a cloned version of this change set to another sandbox  which was refreshed a few days ago (I run all the local tests), it deployed successfully.


text:
Q: node.js Use a variable inside the res.writeHeads() function Heyo out there. I have the following problem:
I use this
res.writeHead(200, {
    "Content-Length": template["stylecss"].length,
    "Connection": "Close",
    "X-XSS-Protection": "1; mode=block",
    "Server": servername,
    "Content-Type": "text/css"
});

to write the response headers to a client.
But now, i want to change the above code to serve predefined headers. Something like this:
var defresheads = { "X-Frame-Options": "deny", "X-Powered-By": servername };
res.writeHead(200, {
    defresheads,
    "Content-Length": template["stylecss"].length,
    "Connection": "Close",
    "X-XSS-Protection": "1; mode=block",
    "Server": servername,
    "Content-Type": "text/css"
});

Now, when i run the script, it says the following:
/home/dontrm/dontrm.js:47
            defresheads,
                       ^
SyntaxError: Unexpected token ,

Is there another way to do this?

A: Use a helper function to concat your header objects, like
function jsonConcat(o1, o2) {
    for (var key in o2) {
        o1[key] = o2[key];
    }
    return o1;
}

And then you can use this as follows:
var defresheads = { "X-Frame-Options": "deny", "X-Powered-By": servername };
res.writeHead(200, jsonConcat(defresheads, {
    "Content-Length": template["stylecss"].length,
    "Connection": "Close",
    "X-XSS-Protection": "1; mode=block",
    "Server": servername,
    "Content-Type": "text/css"
}));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Having output from UnitTest in the "Out" folder in TestResults' deploymentFolder, with MSTest in Visual Studio I am quite new to visual studio. I am having visual studio community 2015.
What I would like to do is when outputting specific data in my unittest with MSTest, I would like to save the output into a file.
I have seen that at each running test, a folder is generated automatically in TestResuls/Deploy_username date hour/out. I am looking for a way to save the tests output in that folder.
Is this possible or is there other ways to copy the files or report my data?
I have looked at these following links:
https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.deploymentitemattribute.aspx
https://msdn.microsoft.com/en-us/library/ee256991.aspx
DeploymentItem not deploying files
Generating Unit Test Reports in Visual Studio 2013
None of these links helped me in achieving what I wanted.
Thank you in advance for your help.

A: I will not explain how File Output is handled in .Net, I presume you have this Knowledge.
If you have a TestClass declared with Attribute [TestClass] you can add a public Property TestContext of Type TestContext (see MSDN), which will get set by MSTest while executing the Test.
There you have the Properties TestResultsDirectory (which typically leads to the "IN" Folder) and TestDeploymentDir (which typically leads to the "OUT" Folder) .
e.g.: TestContext.TestResultsDirectory would lead to "D:\Visual Studio 2015\Projects\UnitTestProject1\TestResults\Deploy_user 2017-02-23 07_37_49\In"
If you need the TestContext earlier then in the [TestMethod] you need to use a public static void TestInit(TestContext testContext) Method in your TestClass, so you get the Instance of the TestContext when your Class got created.
There are also Properties like TestLogsDir, TestDir which are deprecated, you can read in the MSDN docs about it.


text:
Q: How to ignore nullability annotations from java? I am using a library that is written and java with @Nonnull and @Nullable annotations on all of the return values and parameters.  Unfortunately, the annotations are incorrect in a few places.  There is an interface with this method:
interface Expiry<K, V> {
  long expireAfterCreate(@NonNull K key, @NonNull V value, long currentTime);
}

Unfortunately in my case, @NonNull V value can actually be null (since it is a generic type).  How can I get Kotlin compiler to ignore the java annotation and allow me to override the method with the proper type:
object Foo : Expiry<String, Bar?> {
  override fun expireAfterCreate(key: String, value: Bar?, currentTime: Long): Long {
    TODO()
  }
}


text:
Q: GroupLatch doesn't work with Shift for some keys using xkb I am using custom keyboard layout with two groups for German and for Cyrillic. CAPS is used as a group latch in two ways. Either one "CAPS followed by the key" or "CAPS+Key" gives keysym for the key in the group other then the current one.
Everything works perfectly well, except for four keys:
"<"=94, "x"=53, "s"=39 and "w"=25. Pressing CAPS+SHIFT+OneOfTheseKeys produces no keysym's. CAPS followed by SHIFT+Key works as intended with all keys.
I wonder whether this is hardware related (these are neighboring keys on my keyboard) or there is some intricacy I am not seeing?
Here are the relevant pieces from xkb_keymap
including symbols for "s" (latching with shift doesn't work) and for "d"=40 (latching works):
xkb_keymap {
    //...
xkb_types "complete(slava)" {
    type "FOUR_LEVEL" {
        modifiers= Shift+LevelThree;
        map[Shift]= Level2;
        map[LevelThree]= Level3;
        map[Shift+LevelThree]= Level4;
        level_name[Level1]= "Base";
        level_name[Level2]= "Shift";
        level_name[Level3]= "Level3";
        level_name[Level4]= "Shift Level3";
    };
    // two levels: 1=base and 2=AnyOf(Control,Alt,LevelThree,Mod4).
    // I use it for caps without mod to latch group,
    // with any mod to switch groups
    type "CUSTOM_FOR_CAPS" {
        modifiers= Control+Alt+LevelThree+Mod4;
        map[Control]= Level2;
        map[Alt]= Level2;
        map[LevelThree]= Level2;
        map[Mod4]= Level2;
        level_name[Level1]= "Base";
        level_name[Level2]= "Control Alt LevelThree Mod4";
    };
    //...
};

xkb_compatibility "capslock(grouplatch)" {
    //...
    interpret Caps_Lock+AnyOfOrNone(all) {
        action= LatchGroup(group=+1);
    };
    indicator "Caps Lock" {
        !allowExplicit;
        groups= Group2;
    };
    //...
}

xkb_symbols "pc+de(de-slava)+de(ru-slava):2+capslock(grouplatch)" {
    name[group1]="German (slava)";
    name[group2]="Russian (Germany, phonetic-slava)";

    key <CAPS> {
        type= "CUSTOM_FOR_CAPS",
        symbols[Group1]= [ Caps_Lock, ISO_Next_Group ],
        symbols[Group2]= [ Caps_Lock, ISO_Prev_Group ]
    };
    key <AC02> {
        type[group1]= "FOUR_LEVEL",
        type[group2]= "FOUR_LEVEL",
        symbols[Group1]= [           s,           S, dollar, dollar ],
        symbols[Group2]= [ Cyrillic_es, Cyrillic_ES, dollar, dollar ]
    };
    key <AC03> {
        type[group1]= "FOUR_LEVEL",
        type[group2]= "FOUR_LEVEL",
        symbols[Group1]= [           d,           D,    eth,    ETH ],
        symbols[Group2]= [ Cyrillic_de, Cyrillic_DE,    eth,    ETH ]
    };
    //...
};
};


text:
Q: Why is my bitmap sort not infintely faster than my mergesort? I'm working through Programming Peals, and the first essay deals with sorting numbers within a known range. As a smart solution, they offer implementing a bitmap, setting all numbers in the input file to one in the bitmap, and then simply iterating over it to print the result. The assumption is that this should be a lot faster than a more traditional sorting algorithm like quicksort or mergesort.
To test this out, I wrote the bitmap sort myself, in Java. I was not too surprised when I found out that the Unix sort command, which uses merge sort, is still a lot faster. I attributed this to the fact that it is written in C, and probably highly optimized by some very smart folks.
So, then I wrote my own merge sort, also in Java. To my surprise, my BitmapSort was faster, but only marginally. With a very large input file (+-800000 integers), bitmapsort is only about 30% faster.
Here is my bitmap sort and bitmap implementation:
import java.util.Scanner;
import java.io.FileReader;
import java.io.File;

class BitmapSort {
    Scanner sc;

    BitmapSort() throws Exception {
        sc = new Scanner(new File("numbers.txt"));
    }

    void start() {
        BitMap map = new BitMap(3000000);
        while (sc.hasNextInt()) {
            map.set(sc.nextInt());
        }
        for (int i = 0; i < 3000000; i++) {
            if (map.isSet(i)) {
                System.out.println(i);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        new BitmapSort().start();
    }
}

class BitMap {

    byte[] bits;
    int size;

    BitMap(int n) {
        size = n;
        bits = new byte[(int) Math.ceil((double) n / (double) Byte.SIZE)];
        for (Byte b : bits) {
            b = 0;
        }
    }

    private String toBinary(byte b) {
        return String.format(Integer.toBinaryString(b & 0xFF)).replace(' ', '0');
    }

    void set(int i) {
        int index = i / Byte.SIZE;
        bits[index] = (byte) ((bits[index] | (byte) (1 << (Byte.SIZE - 1 - (i % Byte.SIZE)))));
    }

    void unset(int i) {
        int index = i / Byte.SIZE;
        bits[index] = (byte) ((bits[index] ^ (byte) (1 << (Byte.SIZE - 1 - (i % Byte.SIZE)))));
    }

    boolean isSet(int i) {
        int index = i / Byte.SIZE;
        byte mask = (byte) ((bits[index] & (byte) (1 << (Byte.SIZE - 1 - (i % Byte.SIZE)))));
        return (bits[index] & mask) != 0;
    }

}

and here is my mergesort:
import java.util.Scanner;
import java.io.FileReader;
import java.io.File;

class MergeSort {
    Scanner sc;
    static int times;

    MergeSort() throws Exception {
        sc = new Scanner(new File("numbers.txt"));
        times = 0;
    }

    int[] mergeSort(int[] input) {
        if (input.length <= 1) {
            return input;
        }

        int middle = input.length / 2;

        int[] left = new int[middle];
        int[] right;
        if (input.length % 2 == 0) {
            right = new int[middle];
        } else {
            right = new int[middle + 1];
        }

        for (int i = 0; i < middle; i++) {
            left[i] = input[i];
        }
        for (int i = middle; i < input.length; i++) {
            right[i - middle] = input[i];
        }
        left = mergeSort(left);
        right = mergeSort(right);
        return merge(left, right);
    }

    int[] merge(int[] left, int[] right) {
        times++;
        int[] result = new int[left.length + right.length];
        int left_size = 0;
        int right_size = 0;
        int result_size = 0;
        while (left_size < left.length || right_size < right.length) {
            if (left_size < left.length && right_size < right.length) {
                if (left[left_size] <= right[right_size]) {
                    result[result_size] = left[left_size];
                    left_size++;
                    result_size++;
                } else {
                    result[result_size] = right[right_size];
                    right_size++;
                    result_size++;
                }
            } else if (left_size < left.length) {
                result[result_size] = left[left_size];
                left_size++;
                result_size++;
            } else if (right_size < right.length) {
                result[result_size] = right[right_size];
                right_size++;
                result_size++;
            }
        }
        return result;
    }

    void start() {
        int[] input = new int[838662];
        int i = 0;
        while (sc.hasNextInt()) {
            input[i] = sc.nextInt();
            i++;
        }

        int[] result = mergeSort(input);
        for (int j : result) {
            System.out.printf("%d\n", j);
        }
    }

    public static void main(String[] args) throws Exception {
        new MergeSort().start();
    }
}

The input file contains integers between 0 and 3000000, and contains 838661 numbers.
Please forgive the ugly coding style, this was just meant as a quick comparison.
Thanks in advance!
Regards,
Linus

A: For one thing, the Programming Pearls articles were written before the impact of memory hierarchy became as severe as it is today.  A map of 800K bytes adds lots of random access memory traffic very likely to cause cache misses.  Mergesorts tend to have good local memory performance.


text:
Q: GraphDB geof:distance between two points returns empty fields - geosparql I am using GraphDB and want to calculate the geof:distance between two points by using geosparql. The ?point and ?point2 are geometries and are structured like this "POINT(-77.050125 38.892086)"^^<http://www.opengis.net/ont/geosparql#wktLiteral> . But the field dist in query remains empty for some reason. Why is that I cannot understand. I have enabled geosparql already.
My code follows:
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    PREFIX : <http://www.semanticweb.org/evangelos/ontologies/2019/2/untitled-ontology-2#>
    prefix geo: <http://www.opengis.net/ont/geosparql#>
    prefix geof: <http://www.opengis.net/def/function/geosparql/>
    prefix unit: <http://qudt.org/vocab/unit#>
    prefix sf: <http://www.opengis.net/ont/sf#>
    prefix test24: <http://www.semanticweb.org/evangelos/ontologies/2019/2/untitled-ontology-2#>

SELECT ?point2 (geof:distance(?point, ?point2, unit:Kilometer) as ?dist)

    WHERE
    {
        :MouseioMetaksisSoufliou :hasGPSCoordinates ?geom2.
        ?geom2 geo:asWKT ?point.
        ?geom3 geo:asWKT ?point2.
        FILTER (?geom2 != ?geom3).
    }

It kind worked with this. I think might the unit# ontology caused the problem
here is my working code
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX : <http://www.semanticweb.org/evangelos/ontologies/2019/2/untitled-ontology-2#>
prefix geo: <http://www.opengis.net/ont/geosparql#>
prefix geof: <http://www.opengis.net/def/function/geosparql/>
PREFIX uom: <http://www.opengis.net/def/uom/OGC/1.0/>
prefix sf: <http://www.opengis.net/ont/sf#>
prefix test24: <http://www.semanticweb.org/evangelos/ontologies/2019/2/untitled-ontology-2#>

SELECT ?point10 ((geof:distance(?point10, ?point11, uom:metre) < 2000) as ?dist)
WHERE
{
    :MouseioMetaksisSoufliou :hasGPSCoordinates ?geom2.
    ?geom2 geo:asWKT ?point.
    ?geom3 geo:asWKT ?point2.
    FILTER(!sameTerm(?geom2, ?geom3)).
    BIND(CONCAT("<http://www.opengis.net/def/crs/OGC/1.3/CRS84> ", STR(?point))    as ?point5)
    BIND(CONCAT(STR(?point5), "^^geo:wktLiteral") as ?point10)
    BIND(CONCAT("<http://www.opengis.net/def/crs/OGC/1.3/CRS84> ", STR(?point2))    as ?point6)
    BIND(CONCAT(STR(?point6), "^^geo:wktLiteral") as ?point11)

}


text:
Q: Square aspect ratio in 2D plots for static export I want to create 2D scatter plots in plotly.py and export them as static .svg-files with a square aspect ratio. More specifically, I want to make the axis square in screen units (similar to this matplotlib question: Matplotlib scale axis lengths to be equal).
Is there any way of achieving something similar using plotly? (Note that my x and y data are on a different scale)
I already tried to simply set the figure width and height to equal values, which works more or less fine if I have only one trace and no legend.
import numpy as np
import plotly.graph_objects as go

np.random.seed(42)

fig = go.Figure()

fig.add_trace(go.Scatter(
    x=np.random.uniform(0, 1, 50),
    y=np.random.randint(1, 100, 50),
    mode='markers',
    ))

fig.update_layout(width=500, height=500)

# NOTE: Static image generation in plotly requires Kaleido (pip install -U kaleido)
fig.write_image("example.svg")

Output: example plot with one trace and fixed width and height
However, if I have mutliple traces and add a legend, I end up with a distorted plot:
import numpy as np
import plotly.graph_objects as go

np.random.seed(42)

fig = go.Figure()

fig.add_trace(go.Scatter(
    x=np.random.uniform(0, 1, 50),
    y=np.random.randint(1, 100, 50),
    mode='markers',
    name="SomeLongTraceLabel1"
    ))

fig.add_trace(go.Scatter(
    x=np.random.uniform(0, 1, 50),
    y=np.random.randint(1, 100, 50),
    mode='markers',
    name="SomeLongTraceLabel2"
    ))

fig.update_layout(width=500, height=500)

# NOTE: Static image generation requires Kaleido (pip install -U kaleido)
fig.write_image("example.svg")

Output: example plot with two traces and a legend
I think it is possible to achieve this for 3D plots via the layout.scene.aspectmode="cubic" setting, but I could find a similar setting for 2D plots.
Is there any way to make my plots automatically look like this: Desired Output without readjusting the figure width/height everytime with regard to the length of my legend items ?


text:
Q: Why is number of real characters mod $q$ a multiplicative function? Let $R(q)$ be the number of real characters mod $q$. A character $\chi \mod q$ is called real if $\chi(a)\in\mathbb{R}$ for every $a\in \mathbb{Z}$, which means $\chi(a)\in\{-1,1\}$ for every $a\in\mathbb{Z}$ with gcd$(a,q)=1$.
I want to show that this $R$ is multiplicative, so $R(ab)=R(a)R(b)$ for $a,b\in\mathbb{Z}$ with gcd$(a,b)=1$. I'm trying to prove this with induced characters, but I'm not getting it completely. Can someone help me to understand it? Thanks!


text:
Q: Blazor InputNumber decimal format Ideally I would like to apply Math.Round() method to my Blazor's InputNumber in order to remove the .xx from a decimal value.
 <InputNumber class="someClass" @bind-Value="@DcValue"></InputNumber>

Please note the model's DcValue is decimal and will have to stay decimal.
Is there any way of doing this?

A: I ended up creating a custom control to manage that requirement. More details here.


text:
Q: Fancybox not working properly on Ruby on Rails I have trouble using Fancybox 3 with rails 5. My goal is to embed a  responsive Iframe but after hours of tests, I didn't manage to make it work.
According to the documentation, if I want to insert an Iframe, I should write this :

Webpage

With this code, when I click on the link, nothing happens. I'm pretty sure here that there is a problem with ruby and rails structure because when I put some javascript above in my view, the fancybox launches BUT returns me this error into the box : "The requested content cannot be loaded. Please try again later."
Here's my almost working code with javascript and HTML in my view :


text:
Q: How to avoid defining two extra tables for an object that can have only 3 possible values and is part of a many-to-many relationship? I tried to search this online but found this question quite difficult to formulate in a concise & intelligible way.
I am developing an application which enables users to choose from 3 types of authentications: Password, Finger Print & Face Recognition. Each user may opt for multiple types of these 3 and I need to store their picks in a relational database. So theoretically, there exists a many-to-many relationship between users and authentication_types.
I know this seems quite trivial and probably I am overanalysing things, but which would be the optimal way to model this at a relational database level? What I am trying to avoid but seems to be the only reasonable solution in a relational DB setting, is to create a table for login types (say LoginTypes) in which to store the 3 login types mentioned above and create an intermediary table for the many-to-many relationship (say UsersLoginTypes).
What's frustrating a little for me is that for only 3 types of login, I need to create one table to store them and another one for the many-to-many relationship. And any time I want to get the login types chosen by a user, I cannot simply select the user and extract the login types from the user's object, but I need to make a query that involves two another tables (LoginTypes & UsersLoginTypes). Do I miss a simpler solution here?
I thought of maybe assigning each login type a digit (eg. Password - 1, Fingerprint - 2, Face Recognition - 3) and have a field in the User's model for the login types, where to store a string containing the digits corresponding to what the user chose. And eventually, this is perhaps what I would go for if no better solution exists.
PS. I am using Ruby on Rails with ActiveRecord, if this changes something.

A: In 1997, I once normalised a relational database model to death. It worked, was extremely flexible, but it invariably ground to a halt whenever you wanted to formulate an unforeseen query. It was already very tedious to formulate the query in the first place. (of course, that was at times when you always wrote your SQL manually - BI tools were a thing of the future).
So: a (master) table users , a (lookup) table login_types and a (child/intermediate) table active_users_authentications as your first shot is the correct way of modelling it relationally.
But if you want the system to be efficient/performant (and you don't need any further details for the authentication configurations - which you would store in active_users_authentications, of course), I for one would find it absolutely legitimate to have 3 Booleans (Yes/No) columns in the users table and call them: has_pwd_auth, has_fgnpr_auth, and has_facerec_auth .


text:
Q: A clean, lightweight alternative to Python's twisted? A (long) while ago I wrote a web-spider that I multithreaded to enable concurrent requests to occur at the same time.  That was in my Python youth, in the days before I knew about the GIL and the associated woes it creates for multithreaded code (IE, most of the time stuff just ends up serialized!)...
I'd like to rework this code to make it more robust and perform better.  There are basically two ways I could do this: I could use the new multiprocessing module in 2.6+ or I could go for a reactor / event-based model of some sort.  I would rather do the later since it's far simpler and less error-prone.
So the question relates to what framework would be best suited to my needs.  The following is a list of the options I know about so far:

*

*Twisted: The granddaddy of Python reactor frameworks: seems complex and a bit bloated however.  Steep learning curve for a small task.

*Eventlet: From the guys at lindenlab.  Greenlet based framework that's geared towards these kinds of tasks. I had a look at the code though and it's not too pretty: non-pep8 compliant, scattered with prints (why do people do this in a framework!?), API seems a little inconsistent.

*PyEv: Immature, doesn't seem to be anyone using it right now though it is based on libevent so it's got a solid backend.

*asyncore: From the stdlib: über low-level, seems like a lot of legwork involved just to get something off the ground.

*tornado: Though this is a server oriented product designed to server dynamic websites it does feature an async HTTP client and a simple ioloop.  Looks like it could get the job done but not what it was intended for.
[edit: doesn't run on Windows unfortunately, which counts it out for me - its a requirement for me to support this lame platform]

Is there anything I have missed at all?  Surely there must be a library out there that fits the sweet-spot of a simplified async networking library!
[edit: big thanks to intgr for his pointer to this page.  If you scroll to the bottom you will see there is a really nice list of projects that aim to tackle this task in one way or another.  It seems actually that things have indeed moved on since the inception of Twisted: people now seem to favour a co-routine based solution rather than a traditional reactor / callback oriented one.  The benefits of this approach are clearer more direct code: I've certainly found in the past, especially when working with boost.asio in C++ that callback based code can lead to designs that can be hard-to-follow and are relatively obscure to the untrained eye.  Using co-routines allows you to write code that looks a little more synchronous at least.  I guess now my task is to work out which one of these many libraries I like the look of and give it a go!  Glad I asked now...]
[edit: perhaps of interest to anyone who followed or stumbled on this this question or cares about this topic in any sense: I found a really great writeup of the current state of the available tools for this job]

A: Kamaelia hasn't been mentioned yet. Its concurrency model is based on wiring together components with message passing between inboxes and outboxes. Here's a brief overview.

A: I've started to use twisted for some things.  The beauty of it almost is because it's "bloated."  There are connectors for just about any of the main protocols out there.  You can have a jabber bot that will take commands and post to an irc server, email them to someone, run a command, read from an NNTP server, and monitor a web page for changes.  The bad news is it can do all of that and can make things overly complex for simple tasks like the OP explained.  The advantage of python though is you only include what you need.  So while the download may be 20mb, you may only include 2mb of libraries (which is still a lot).  My biggest complaint with twisted is although they include examples, anything beyond a basic tcp server you're on your own.
While not a python solution, I've seen node.js gain a lot more traction as of late.  In fact I've considered looking into it for smaller projects but I just cringe when I hear javascript :)

A: gevent is eventlet cleaned up.
API-wise it follows the same conventions as the standard library (in particular, threading and multiprocessing modules) where it makes sense. So you have familiar things like Queue and Event to work with.
It only supports libevent (update: libev since 1.0) as reactor implementation but takes full advantage of it, featuring a fast WSGI server based on libevent-http and resolving DNS queries through libevent-dns as opposed to using a thread pool like most other libraries do. (update: since 1.0 c-ares is used to make async DNS queries; threadpool is also an option.)
Like eventlet, it makes the callbacks and Deferreds unnecessary by using greenlets.
Check out the examples: concurrent download of multiple urls, long polling webchat.

A: There is a good book on the subject: "Twisted Network Programming Essentials", by Abe Fettig.  The examples show how to write very Pythonic code, and to me personally, do not strike me as  based on a bloated framework.  Look at the solutions in the book, if they aren't clean, then I don't know what clean means.
My only enigma is the same I have with other frameworks, like Ruby. I worry, does it scale up?  I would hate to commit a client to  a framework that is going to have scalability problems.

A: Whizzer is a tiny asynchronous socket framework that uses pyev. Its very fast, primarily because of pyev. It attempts to provide a similiar interface as twisted with some slight changes.

A: Also try Syncless. It's coroutine-based (so it's similar to Concurrence, Eventlet and gevent). It implements drop-in non-blocking replacements for socket.socket, socket.gethostbyname (etc.), ssl.SSLSocket, time.sleep and select.select. It's fast. It needs Stackless Python and libevent. It contains a mandatory Python extension written in C (Pyrex/Cython).

A: I Confirm the goodness of syncless. It can use libev (the newer, cleaner and better performance version of libevent). A while ago it didn't have as much support as libevent, but now the development process is more advanced and syncless very useful.

A: I liked the concurrence Python module which relies on either Stackless Python microthreads or Greenlets for light-weight threading. All blocking network I/O is transparently made asynchronous through a single libevent loop, so it should be nearly as efficient as an real asynchronous server.
I suppose it's similar to Eventlet in this way.
The downside is that its API is quite different from Python's sockets/threading modules; you need to rewrite a fair bit of your application (or write a compatibility shim layer)
Edit: It seems that there's also cogen, which is similar, but uses Python 2.5's enhanced generators for its coroutines, instead of Greenlets. This makes it more portable than concurrence and other alternatives. Network I/O is done directly with epoll/kqueue/iocp.

A: A really interesting comparison of such frameworks was compiled by Nicholas Piël on his blog: it's well worth a read!

A: If you just want a Simplified, lightweight HTTP Request Library then I find Unirest really good

A: None of these solutions will avoid that fact that the GIL prevents CPU parallelism - they are just better ways of getting IO parallelism that you already have with threads.  If you think you can do better IO, by all means pursue one of these, but if your bottleneck is in processing the results nothing here will help except for the multiprocessing module.

A: I wouldn't go as far as to call Twisted bloated, but it is difficult to wrap your head around. I avoided really settling in an learn for quite a while as I always wanted something a little easier for 'small tasks'.
However, now that I have worked with it some more I have to say having all the batteries included is VERY nice.
All the other async libraries I've worked with end being way less mature than they even appear. Twisted's event loop is solid.
I'm not quite sure how to solve the steep Twisted learning curve. It might help if someone would fork it and clean a few things up, like removing all the backwards compatability cruft and the dead projects. But that's the nature of mature software I guess.

A: Twisted is complex, you're right about that. Twisted is not bloated.
If you take a look here: http://twistedmatrix.com/trac/browser/trunk/twisted you'll find an organized, comprehensive, and very well tested suite of many protocols of the internet, as well as helper code to write and deploy very sophisticated network applications. I wouldn't confuse bloat with comprehensiveness.
It's well known that the Twisted documentation isn't the most user-friendly from first glance, and I believe this turns away an unfortunate number of people. But Twisted is amazing (IMHO) if you put in the time.  I did and it proved to be worth it, and I'd recommend to others to try the same.

A: You are welcome to have a look at PyWorks, which takes a quite different approach. It lets object instances run in their own thread and makes function call's to that object async.
Just let a class inherit from Task instead of object and it is async, all methods calls are Proxies. Return values (if you need them) are Future proxies.
res = obj.method( args )
# code continues here without waiting for method to finish
do_something_else( )
print "Result = %d" % res # Code will block here, if res not calculated yet

PyWorks can be found on http://bitbucket.org/raindog/pyworks


text:
Q: application: didReceiveLocalNotification Runs Every Launch After 1st Local Notification I am working on an application that uses iOS's UILocalNotifications to alert the user that action needs to be completed on their part. I am able to create my notifications and have them fire properly. However, when returning to the app I am having an issue. After the first time a notification fired my 'application: didRecieveLocalNotification' runs every time, with the 1st notifications data. I can log out all the notifications in the queue, and even if the queue is empty it will still run the notification block. Has anyone else ran into this problem or know how to fix it. I have included my didRecieveLocalNotification code below.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    if (notification) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
        [(UITabBarController *)self.window.rootViewController setSelectedIndex:1];
        UINavigationController *nav = [[(UITabBarController *)self.window.rootViewController viewControllers] objectAtIndex:1];
        IMTUpdateRewardViewController *rvc = [storyboard instantiateViewControllerWithIdentifier:@"updateReward"];
        [rvc loadPushNotification:notification];
        [nav pushViewController:rvc animated:NO];
    }
}

A: I have ran into a similar problem. Eventually the culprit was a bug on my part, which was related to generating reminders to events. And if upon return from background, there were events which have already began, then a local notification was generated, and fired immediately. In short, when you encounter something like this, put a small debug printout at your UILocalNotification generating methods


text:
Q: Google Drive: What combination of scopes lets an app read existing files but not have edit/delete privileges? I've found that with https://www.googleapis.com/auth/drive scope, my app can read all existing files (and their contents) in a Google Drive, but when I auth the app, it says that this scope can also delete files in the drive and I don't want to grant that.
I know that by itself https://www.googleapis.com/auth/drive.file only allows the app to read files created by the app itself or especially granted access.
I've tried other combinations, but can't find one where the the app can read the contents of any file I can see, but can't delete anything. This is the closest I've come:

*

*https://www.googleapis.com/auth/drive.metadata

*https://www.googleapis.com/auth/drive.file

*https://www.googleapis.com/auth/drive.activity

*https://www.googleapis.com/auth/documents
Is there a combination that will achieve my goal?

A: There isn't one if you have access to read and write to a file then you will also have access to delete that file.
Its how they have permissions setup.

If you don't want to upload and only download try drive readonly.
scopes#drive

A: Based on your needs, you should be eyeing https://www.googleapis.com/auth/drive.readonly. This enables you to read the file metadata and content.

Allows read-only access to file metadata and file content.

Resource:

*

*Scopes

A: If you're not intending to create any files or save any data to Drive, then you have the https://www.googleapis.com/auth/drive.readonly scope.
Note that this is a restricted scope that will grant your app with read-only access to the user's entire Drive, but it will also prevent your app from creating any new files or editing existing ones.
If you want your application to be able to access the entire Drive, and you're planning to release your app to the public, you should submit your application to a restricted scope verification and security assessment; otherwise your app will be limited to 100 users, and users will see a warning while your app is unverified.

Here's more information:

*

*OAuth 2.0 Scopes for Google APIs - Drive API, v3

*Additional Requirements for Specific API Scopes section in the Google API Services User Data Policy

*OAuth API verification FAQs


text:
Q: Android Sqlite Database Formation In my application I take entry from user as :-
Name:- -------------------------
Favorite Fruit:-  a)
                  b)
                  c)
                     --------- Add More ----------

Then I want to save it into a Sqlite database. Now I provide user to type in edittext search like this:-
Search Fruit:- Apple,Banana

And then I want to query my database and Print the name of those who like atleast Apple and Banana.
Now my issue is how do I make my database columns to achieve results faster.
Should I make two columns Name and FruitsLiked or something else. Because if I make only two colums then how do I search into database.
Thanks

A: Create one table n two columns. First column is for name , second one comma separated list of fruits.
Then as db query use like keyword based query


text:
Q: Identity simplification How do you express $\dfrac{\sin A\sec A\cot A}{\tan A}$ in terms of sine and cosine?
I have simplified using $\sec(A)$ as $\cos^{-1}(A)$ and also $\cot(A)$ as $\dfrac{\cos(A)}{\sin(A)}$, and appear to end up with $\dfrac{\sin(A)}{\cos(A)}$, which is simply $\tan(A)$.

A: $$\sin(A)\frac{\sec(A)}{\tan{A}}\cot{A}=\frac{\sin(A)}{\cos(A)}\frac{1}{\tan(A)}\cot(A)=\cot(A)=\frac{\cos(A)}{\sin(A)}$$

A: $$
\frac{\sin A\sec A\cot A}{\tan A} = \frac{\sin A\cdot\dfrac 1 {\cos A}\cdot \dfrac {\cos A} {\sin A}}{\dfrac{\sin A}{\cos A}}
$$
That expresses it in terms of sine and cosine. After that, you can do some simplifying.  Dividing by $\sin A/\cos A$ is the same as multiplying by $\cos A/\sin A$, so you get
$$
\sin A\cdot\dfrac 1 {\cos A}\cdot \dfrac {\cos A} {\sin A} \cdot \frac{\cos A}{\sin A}.
$$
Then, doing a couple of cancelations of factors common to the numerator and the denominator, you get
$$
\frac{\cos A}{\sin A}.
$$
That expresses it in terms of the sine and the cosine of $A$.
You can also write it as $\cot A$.


text:
Q: Can't Get Divs to render Side By Side Here's the fiddle: http://jsfiddle.net/vhcFw/
Here's the code:

Essentially, I cannot get the divs to render side- by side (especially when using inline styling). I realise this is a simple mistake, but I cannot figure out how to fix it. Thanks in advance.

A: Simple syntax error.
Use display:inline-block not display:block-inline
Updated jsFiddle here
See MDN - display properties.

Alternatively, you could also float the elements.
jsFiddle here

A: simply add float:left.to your style

A: You have a few options here to consider. The best choice would be to use a flex container to surround the the elements which will by default render them side by side.

Without a container you can just leave them to their default display which would be as block elements and float them left using float: left;.

You can also change their display to be inline-block which have properties of both inline and block elements. MDN has exhaustive documentation about the display property.


text:
Q: WPF AvalonEdit does not display bound TextDocument from ViewModel I have no Binding errors in my output window.
I want to bind text from a file(s) to one/many avalonEdit controls via MVVM.
How can I do that, because its not working the way I tried?!
VIEW
        >
    <Window.Resources>
        <DataTemplate x:Key="NormalTemplate">
            <Expander Margin="0" Header="{Binding FileName}">
                <!--<TextBox TextWrapping="Wrap" AcceptsReturn="True"  IsReadOnly="True" Text="{Binding Content}"  Margin="0"/>-->
                <avalonEdit:TextEditor Document="{Binding Document, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></avalonEdit:TextEditor>
            </Expander>
        </DataTemplate>
    </Window.Resources>

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="40px"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <Grid Background="Orange">
            <StackPanel Orientation="Horizontal">
                <Button>Run</Button>
                <Button Command="{Binding SaveCommand}">Save</Button>
            </StackPanel>
        </Grid>
        <Grid Grid.Row="1">
            <ScrollViewer ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
                <ItemsControl ItemsSource="{Binding ErrorLogs}" HorizontalContentAlignment="Stretch" ItemTemplate="{DynamicResource NormalTemplate}" />
            </ScrollViewer>
        </Grid>
    </Grid>
</Window>

VIEWMODEL
public class ErrorLogViewModel : BaseViewModel
    {
        public string FileName { get; set; }
        public string Content { get; set; }

        private TextDocument _document = null;
        public TextDocument Document
        {
            get { return this._document; }
            set
            {
                if (this._document != value)
                {
                    this._document = value;
                    RaisePropertyChanged("Document");
                }
            }
        }
    }

public class MainViewModel : BaseViewModel
    {
        public MainViewModel()
        {
            GetErrorLogs();

            SaveCommand = new RelayCommand(Save);
        }

        public RelayCommand SaveCommand { get; private set; }

        private void Save()
        {
            var text = ErrorLogs[0].Document.Text;
            // I get at least the Original loaded text
        }

        private void GetErrorLogs()
        {
            for (int i = 0; i < 30; i++)
            {
                using (FileStream fs = new FileStream("text.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using (StreamReader reader = FileReader.OpenStream(fs, Encoding.UTF8))
                    {
                        var doc = new TextDocument(reader.ReadToEnd());
                        var e = new ErrorLogViewModel { FileName = "ErrorLog " + i, Document = doc };
                        ErrorLogs.Add(e);
                    }
                }
            }
        }

        private ObservableCollection<ErrorLogViewModel> _errorLogs = new ObservableCollection<ErrorLogViewModel>();
        public ObservableCollection<ErrorLogViewModel> ErrorLogs
        {
            get { return _errorLogs; }
            set
            {
                _errorLogs = value;
                this.RaisePropertyChanged("ErrorLogs");
            }
        }
    }

I have looked at that sample were MVVM is introduced:
http://www.codeproject.com/Articles/570313/AvalonDock-Tutorial-Part-AvalonEdit-in-Avalo
I do the same binding actually when I load a text file but my text is just not shown :/
You can find here a repro visual studio solution:
http://www.file-upload.net/download-9067428/ExpanderTest.7z.html


text:
Q: Taking input from the user in PYTHON I've been trying to take the input in this format
Input:
POSITION 0,0,EAST

I want every input stored separately.
The code I've written is:
position,x,y,z = list(input().split(','))

Can someone help me to find me what is wrong with my input function?
I'm trying to store the input something like this
position = 'POSITION'
x = '0'
y = '0'
z = 'EAST'

A: You don't have a comma after "POSITION" and so your code doesn't execute as expected. If you use this as input POSITION,0,0,EAST, your code will execute as expected.
Alternatively, if you want to keep the format as your input, simply split on a comma or a space:
import re
position,x,y,z = list(re.split(r'[, ]',input()))

A: Because the input cannot be changed, the split(',') will keep the 'POSITION 0' as 1 value.
so you just need to split it again with a space between then with split(' ')
notice that data[0] = 'POSITION 0', data[1] = 0, data[2] = EAST.
data = list(input().split(','))
position = data[0].split(' ')[0]
x = data[0].split(' ')[1]
y = data[1]
z = data[2]
print(position + " " + x + " " + y + " " + z)

A: Your input function you are splitting with , as delimiter. If you can change input to POSITION,0,0,EAST then your code will work.
If you cannot change the input format then you can replace space with , and then split.
position,x,y,z=input().replace(" ",",").split(",")


text:
Q: Nextcord buttons pagination I'm trying to do a help command with buttons, I'm using nextcord-ext-menus. But, I can't find a way of switching between embeds without editing 2 embeds when one button is pressed.
I want one button to go to the previous page,one to stop the whole help command/embed & one that will go to the next page. (im new to buttons btw)
I can explain in more detail if you don't understand.
My code:
class MyButtonMenu(menus.ButtonMenu):
    def __init__(self):
        super().__init__(disable_buttons_after=True)

    async def send_initial_message(self, ctx, channel):
        return await channel.send(f'Hello {ctx.author}', view=self)

    @nextcord.ui.button(style=nextcord.ButtonStyle.blurple,emoji="<:left:968157460626047026>")
    async def on_thumbs_up(self, button, interaction):
        embe = nextcord.Embed(description=f"is it working? /1")
        await self.message.edit(embed=embe)

    @nextcord.ui.button(emoji="\N{THUMBS DOWN SIGN}")
    async def on_thumbs_down(self, button, interaction):
        emb = nextcord.Embed(description="WOAH TY !!!")
        await self.message.edit(embed=emb)

    @nextcord.ui.button(emoji="\N{BLACK SQUARE FOR STOP}\ufe0f")
    async def on_stop(self, button, interaction):
        self.stop()

@bot.command()
async def pages(ctx):
 await MyButtonMenu().start(ctx)


text:
Q: Paste into next empty column Please help optimize this code if possible to run quicker.
Currently program works as intended but I think their may be a better way to copy/paste data into next empty column besides this lengthy else if statement.
Sub compare()
Dim N
Dim mystr
Dim MyComp

LastRow = Cells(Rows.Count, 1).End(xlUp).Row

For i = 2 To LastRow
N = Range("A" & i)
mystr = Replace(N, Right(N, 8), "")

If Worksheets("Sheet1").Range("A2:A66000").Find(mystr) Is Nothing Then
    Else
    Set mystr = Worksheets("Sheet1").Range("A2:A66000").Find(mystr, LookAt:=xlWhole)
    cn = mystr.Address

'' Portion of code I wish to optimize
 If IsEmpty(Worksheets("Sheet1").Range(cn).Offset(0, 1)) = True Then
    Worksheets("Sheet2").Range("A" & i).Copy Worksheets("Sheet1").Range(cn).Offset(0, 1)
    ElseIf IsEmpty(Worksheets("Sheet1").Range(cn).Offset(0, 2)) = True Then
    Worksheets("Sheet2").Range("A" & i).Copy Worksheets("Sheet1").Range(cn).Offset(0, 2)
    ElseIf IsEmpty(Worksheets("Sheet1").Range(cn).Offset(0, 3)) = True Then
    Worksheets("Sheet2").Range("A" & i).Copy Worksheets("Sheet1").Range(cn).Offset(0, 3)
    ElseIf IsEmpty(Worksheets("Sheet1").Range(cn).Offset(0, 4)) = True Then
    Worksheets("Sheet2").Range("A" & i).Copy Worksheets("Sheet1").Range(cn).Offset(0, 4)
    ElseIf IsEmpty(Worksheets("Sheet1").Range(cn).Offset(0, 5)) = True Then
    Worksheets("Sheet2").Range("A" & i).Copy Worksheets("Sheet1").Range(cn).Offset(0, 5)
    ElseIf IsEmpty(Worksheets("Sheet1").Range(cn).Offset(0, 6)) = True Then
    Worksheets("Sheet2").Range("A" & i).Copy Worksheets("Sheet1").Range(cn).Offset(0, 6)
    ElseIf IsEmpty(Worksheets("Sheet1").Range(cn).Offset(0, 7)) = True Then
    Worksheets("Sheet2").Range("A" & i).Copy Worksheets("Sheet1").Range(cn).Offset(0, 7)
    ElseIf IsEmpty(Worksheets("Sheet1").Range(cn).Offset(0, 8)) = True Then
    Worksheets("Sheet2").Range("A" & i).Copy Worksheets("Sheet1").Range(cn).Offset(0, 8)
    ElseIf IsEmpty(Worksheets("Sheet1").Range(cn).Offset(0, 9)) = True Then
    Worksheets("Sheet2").Range("A" & i).Copy Worksheets("Sheet1").Range(cn).Offset(0, 9)
    Else
    Worksheets("Sheet2").Range("A" & i).Copy Worksheets("Sheet1").Range(cn).Offset(0, 10)
    End If

End If
Next i

End Sub

A: Use the Range.End method.
With Worksheets("Sheet1")
    .Cells(cn.Row,.Columns.Count).End(xlToLeft).Offset(,1).Value = _
        Worksheets("Sheet2").Range("A" & i).Value
End WIth


text:
Q: ¿Como verificar si un Array  esta vacio? Tengo un problema para verificar si un Array esta vacio, estoy intentando realizar una consulta en firebase para encontrar la coleccion correcta y cuando los datos enviados son los correctos, esta me devuelve el resultado en un Array:

Este es el resultado cuando la consulta es exitosa y en caso de que no lo sea devuelve:

El codigo utilizado es:
     obtenerUsuario(nombre): Observable<any> {
            console.log(usuario)
            return this.db.collection('usuario', ref => ref.where('nombre', '==', nombre)).valueChanges();
  }

Esta es la consulta que devuelve un Observable
datoArray: any[] = [];

this.logserv.obtenerUsuario(nombre).subscribe(res =>
          this.datoArray.push(res));

console.log(this.datoArray)

De esta forma obtengo los datos obtenidos para mostrarlos en la consola.
Lo que necesito es saber como diferenciar de cuando la consulta devuelve datos vacios y cuando no. Gracias

A: Siempre habrá un arreglo dentro de datoArray, que puede estar o no vacío así que se puede evaluar usando su propiedad length:
this.logserv.obtenerUsuario(nombre).subscribe((res) => {
  this.datoArray.push(res);
  // si la longitud del arreglo en la posición 0 es 0 entonces está vacío
  if (!this.datoArray[0].length) {
    // está vacío
  }
});

A: Hola compañero lo que puedes hacer es la siguiente validación
if (res.length == 0){
console.log("se encuentra vacío el arreglo")
}else {
console.log("no lo esta")
}

te aconsejo ponerle un tipo a la respuesta del servicio, en este caso le pones any para no tener problemas a la hora de la implementación
this.logserv.obtenerUsuario(nombre).subscribe((res:any) =>

así quedaría tu código
 datoArray: any[] = [];

    this.logserv.obtenerUsuario(nombre).subscribe((res:any) =>
if (res.length == 0){
    console.log("se encuentra vacío el arreglo")
    }else {
    this.datoArray.push(res));
console.log(this.datoArray);
    }


text:
Q: How do I make the slideshow buttons scroll through the images? I have been working on a project and while trying to create a slideshow I found somewhere, wanted to edit it so that instead of using the setTimeout to scroll through the images or the circles, I want to be able to use the buttons to go left and right but just cant seem to figure it out.
Here is the link to what it looks like:
https://codesandbox.io/s/throbbing-bash-ir9g0?fontsize=14&hidenavigation=1&theme=dark
Anyone able to point me in the right direction?

A: you can do that by handling the onClick event
here's the link of the code you could check this demo
import React from "react";

import "./slideshow.scss";

const colors = ["#0088fE", "#00C49F", "#FFBB28"];

function Slideshow() {
  const [index, setIndex] = React.useState(0);

const handleChange=()=>{
  setIndex((prevIndex) =>
  prevIndex === colors.length - 1 ? 0 : prevIndex + 1
 )
}
  React.useEffect(() => {

  }, [index]);
  return (

      <div
        className="slideshow-slider"
        style={{ transform: `translate3d(${-index * 100}%, 0, 0)` }}
      >
        {colors.map((backgroundColor, index) => (

        ))}

      <button className="left" onClick={()=>handleChange} >‹</button>
      <button className="right" onClick={()=>handleChange}>›</button>

        {colors.map((_, idx) => (
          <div
            key={idx}
            className={`slideshow-tab${index === idx ? " active" : ""}`}
            onClick={() => {
              setIndex(idx);
            }}
          >

        ))}

  );
}

export default Slideshow;

A: In order to achieve what you are looking for, we just need to add click handlers for left and right buttons.
Below are the respective functions in order to display the next/previous slide based on the current index.
//Handler to update the current index on click of right button
const onNextClick = () => {
  if(index !== colors.length - 1) {
    setIndex(idx => idx + 1);
  }
}

//Handler to update the current index on click of left button
const onPreviousClick = () => {
  if(index !== 0) {
    setIndex(idx => idx - 1);
  }
}

<button className="left" onClick={onPreviousClick}>‹</button>
<button className="right" onClick={onNextClick}>›</button>

Adding these functions to slideshow.js & updating the buttons as shown will help you in achieving the expected functionality.
Here is the demo

const colors = ["#0088fE", "#00C49F", "#FFBB28"];
const delay = 5000;

function Slideshow() {
  const [index, setIndex] = React.useState(0);
  const timeoutRef = React.useRef(null);

  function resetTimeout() {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }
  }

  React.useEffect(() => {
    resetTimeout();
    timeoutRef.current = setTimeout(
      () =>
        setIndex((prevIndex) =>
          prevIndex === colors.length - 1 ? 0 : prevIndex + 1
        ),
      delay
    );
    return () => {
      resetTimeout();
    };
  }, [index]);

//Handler to update the current index on click of right button
  const onNextClick = () => {
    if(index !== colors.length - 1) {
      setIndex(idx => idx + 1);
    }
  }

//Handler to update the current index on click of left button
  const onPreviousClick = () => {
    if(index !== 0) {
      setIndex(idx => idx - 1);
    }
  }

  return (

      <div
        className="slideshow-slider"
        style={{ transform: `translate3d(${-index * 100}%, 0, 0)` }}
      >
        {colors.map((backgroundColor, index) => (

        ))}

      <button className="left" onClick={onPreviousClick}>‹</button>
      <button className="right" onClick={onNextClick}>›</button>

        {colors.map((_, idx) => (
          <div
            key={idx}
            className={`slideshow-tab${index === idx ? " active" : ""}`}
            onClick={() => {
              setIndex(idx);
            }}
          >

        ))}

  );
}

ReactDOM.render(<Slideshow />, document.getElementById("react"));
.slideshow {
  margin: 0 auto;
  overflow: hidden;
  width: 30%;
  position: relative;
}

.slideshow-slider {
  white-space: nowrap;transition: ease 1000ms;
}

.slide {
  display: inline-block;
  height: 240px;
  width: 100%;
}

button {
  width: 25px;
  height: 240px;
  position: absolute;
  cursor: pointer;
}

.left {
  left: 0;
  top: 0;
}

.right {
  right: 0;
  top: 0;
}

.slideshow-tabs {
  text-align: center;
  position: relative;
  bottom: 50px;
}

.slideshow-tab {
  display: inline-block;
  height: 20px;
  width: 20px;
  border-radius: 50%;
  cursor: pointer;
  margin: 15px 7px 0px;
  background-color: #c4c4c4;
}

.active {
  background-color: #6a0dad;
}

-- Update --
As per you requirement, if you wish to go back to the beginning at the end of all the slides, you can make the changes to onNextClick like below
  const onNextClick = () => {
    setIndex(idx => idx !== colors.length - 1? idx + 1: 0);
  }


text:
Q: Omnipay Integration into Aimeos E-Commerce I want to have an integrated payment for purchasing with credit cards. and I want to use omnipay. my required composer.json array is as follows:
"require": {
    "php": "^7.2",
    "academe/omnipay-adyen": "^3.0",
    "aimeos/ai-payments": "~2019.10",
    "aimeos/aimeos-laravel": "~2019.10",
    "dilab/omnipay-2c2p": "~2.0",
    "fideloper/proxy": "^4.0",
    "laravel/framework": "^6.0",
    "laravel/tinker": "^1.0",
    "laravel/ui": "^1.2",
    "league/omnipay": "3",
    "omnipay/paypal": "^3.0"
},

I did try to use multiple providers with no luck of getting it to work. I've registered a new payment service and I've set the option type to ex: "Adyen" or "2c2p" but after I submit the payment form data it gives me an error class not found for example when I used adyen
Class '\Omnipay\adyen\Gateway' not found

I did implement the Gateway Class with the relevant Credentials in the Package src folder as follows:
class Gateway extends AbstractGateway
{
    use GatewayParameters;

    public function getDefaultParameters()
    {
        return [
            'merchantAccount' => 'null',
            'skinCode' => null,
            'secret' => null,
            'publicKeyToken' => null,
            'username' => null,
            'password' => null,
        ];
    }
}

How to setup the payment method?

A: "league/omnipay": "^3"

It is correct and it must work. Better if you can remove your vendor folder and install it again.
And here you can see, how to use it - https://github.com/academe/omnipay-adyen


text:
Q: Audio Player with Play All Capability I've been hunting around for a jQuery plugin that plays audio in the browser, and can automatically play the next audio file once the previous one is finished. Also, the ability to play only one audio file at a time; so if the user is playing one audio file, and clicks play on another, the first audio file should stop playing. In essence, I'm looking for something similar to how sounds are played on a page on SoundCloud. I've been looking at packages like SoundManager2 and jPlayer, but it doesn't look like they can do this.
So in bullet points:

*

*once one audio file is done, auto-start the next one

*only one audio file plays at a time; so, if an audio file is playing and the user clicks play on another, the first one should stop playing.

Any suggestions would be awesome, even if it's just pointing me in a general direction.

A: SoundManager2 can do everything you're asking for, see here.


text:
Q: Load environment variables from file just for the next script I have one of those .env files with several variables set, like:
VAR1=111
VAR2=222

I want to run a script (without changing it) that makes use of those variables.
I know I can source that file in the shell and export the variables from the file, like:
set -a
source myenvs.env   # this is my .env file
set +a
./myscript.sh  # this will use the variables

The problem with that is it loads all those variables in my shell, which I don't want (shell pollution.)
What I'm looking for is the equivalent of using env VAR1=111 VAR2=222 ./myscript.sh but getting those variables from the .env file instead.

A: Do that in a subshell and main shell's environment won't be altered. E.g:
(
  set -a
  source myenvs.env   # this is my .env file
  exec ./myscript.sh  # avoid unnecessary fork()
)

The truth is I need to keep that script flexible to run with different combinations of settings. Imagine I have several .env files like development.env, stagin.env, repro-bug-123.env, etc.

A function would be more useful in that case.
with_env() (
  set -a
  source "$1"
  shift
  exec "$@"
)

with_env myenvs.env ./myscript.sh

A: Declare vars that you don't want to change as read only
declare -r VAR3 VAR4

and source the rest
. ./myenvs.env


text:
Q: VBA to save progress to master I am trying to create a workbook of Part numbers that are being reviewed. Once reviewed, there is a macro button that will initialize and date the current workbook and save that over the master. The macro also refreshes the workbook to pull in any new initials and dates before it does the saving to ensure anyone else's progress is kept before overwriting.
The issue is it insists the master is open when I know for a fact it is not. I assume something about the refresh "opens" the file but I do not know of any work-arounds.
Worth noting the error is:

Run-time '1004' Excel Cannot Access

The folder is not restricted and any domain user can access it.
I thought creating a subfile that saves over the master would be the best way to allow multiple people to add their progress throughout the day but perhaps I am wrong.
Below is the code:
Sub Get_Initials()
     For Each objConnection In ThisWorkbook.Connections
        bBackground = objConnection.OLEDBConnection.BackgroundQuery
        objConnection.OLEDBConnection.BackgroundQuery = False
        objConnection.Refresh
        objConnection.OLEDBConnection.BackgroundQuery = bBackground
    Next

    Dim strUserName As String
    strUserName = Application.UserName
   ActiveCell = strUserName
   ActiveCell.Offset(ColumnOffset:=1).Activate
   ActiveCell = Now()
   Application.DisplayAlerts = False
   ThisWorkbook.SaveCopyAs Filename:="P:\Master\Part Number List Master.xlsm"
   Application.DisplayAlerts = True
End Sub

Thanks in advance


text:
Q: How to change RabbitMQ Heartbeat without restart There are several questions here in SO about RabbitMQ heartbeat but I haven't found one addressing how to actually change the default heartbeat value of 60 seconds (580 seconds in previous versions).
In the case when a consumer is running for longer than 60 seconds and is incapable of producing any traffic that would count as heartbeat (for example PHP consumers), RabbitMQ will close the connection considering the consumer is dead, but the consumer might continue to run, and when it tries to produce the ACK the connection is closed and you get an error message like:

Broken pipe or closed connection

One can set the heartbeat at the consumer side to a higher value, for example 1800 seconds, but if the broker configuration is not changed, then the lower value will be use, in case of the default value then 60 seconds. From RabbitMQ docs:

The broker and client will attempt to negotiate heartbeats by default.
  When both values are non-0, the lower of the requested values will be
  used. If one side uses a zero value (attempts to disable heartbeats)
  but the other does not, the non-zero value will be used.

To change the Heartbeat value one can add the following line in /etc/rabbitmq/rabbitmq.conf (using the new configuration format)
heartbeat = 1800

This requires a restart, so the question is: How to change the rabbitmq heartbeat value without a restart?

A: I'm answering my own question since it took me some time to find how to do this, the documentation on how to use eval was not very helpful.
It's possible to change RabbitMQ configuration values using eval:

Evaluate an arbitrary Erlang expression.

Using rabbitmqctl eval is then possible to change the heartbeat value without a restart like so:
# Set
rabbitmqctl eval 'application:set_env(rabbit, heartbeat, 1800).'

# Get
rabbitmqctl eval 'application:get_env(rabbit, heartbeat).'


text:
Q: Visual Studio 2015 ASP.Net MVC page becomes unresponsive after debugging for about a minute When I am running an MVC app in debug mode in vs 2015 community with Update 3, the page becomes unresponsive after about a minute even though debugging is still active. It's as if the page loses it's connection to the running vs instance.  When I attempt to refresh the page or navigate elsewhere in the app, it just sits there trying to load but never does. I always have to restart debugging.  This is really annoying as a developer to constantly have to restart the site - especially when only making javascript or html changes.
I believe this started approximately 6 weeks ago.  I don't recall any change or addition that preceded it.  At first I thought it was just with one solution or browser but have since confirmed it is with every solution and 3 different browsers.  During this time I installed the same setup on another computer only to have the same problem.
Is there a setting or something I don't know about that causes this?


text:
Q: How do I send selected value of dropdown list from one view to another? I am trying to set dropdown list value from one view to another. I am not getting it even though both view has the same model.
My First View is, from which I would like to send value
    @using (Html.BeginForm("ApplicantDetails", "Applicant", new { ReturnUrl = ViewBag.ReturnUrl },     FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
    {
        @Html.AntiForgeryToken()

Applicant Detail

            @Html.ValidationSummary(true)

                @Html.LabelFor(m => m.Salutation, new { @class = "control-label col-md-2" })

                    @Html.DropDownListFor(m => m.Salutation, Model.Salutation, new { @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.Salutation, null, new { @class = "text-warning" })

                @Html.LabelFor(model => model.FirstName, new { @class = "control-label col-md-2" })

                    @Html.TextBoxFor(model => model.FirstName, new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.FirstName,null,new {@class = "text-warning"})

                @Html.LabelFor(model => model.Surname, new { @class = "control-label col-md-2" })

                    @Html.TextBoxFor(model => model.Surname, new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.Surname, null, new { @class = "text-warning" })

                @Html.LabelFor(model => model.DOB, new { @class = "control-label col-md-2" })

                    @Html.TextBoxFor(model => model.DOB, new {Id = "datepicker", @class = "form-control calender" })
                    @Html.ValidationMessageFor(model => model.DOB, null, new { @class = "text-warning" })

                @Html.LabelFor(model => model.Email, new { @class = "control-label col-md-2" })

                    @Html.TextBoxFor(model => model.Email, new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.Email, null, new { @class = "text-warning" })

                @Html.LabelFor(model => model.CountryofResidence, new { @class = "control-label col-md-2" })

                    @Html.TextBoxFor(model => model.CountryofResidence, new { Id = "countryofresidence", @class = "form-control"})
                    @Html.ValidationMessageFor(model => model.CountryofResidence, null, new { @class = "text-warning" })

                @Html.LabelFor(model => model.CountryofNationality, new { @class = "control-label col-md-2" })

                    @Html.TextBoxFor(model => model.CountryofNationality, new { Id = "countryofnationality", @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.CountryofNationality, null, new { @class = "text-warning" })

                @Html.LabelFor(m => m.Currency, new { @class = "control-label col-md-2" })

                    @Html.DropDownListFor(m => m.Currency, Model.Currency, new { @class = "form-control" })
                    @Html.ValidationMessageFor(m => m.Currency, null, new { @class = "text-warning" })

                        <input type="submit" value="Go" class="btn btn-primary" />

    }

and my second view is in which I would like to display value and in the salutation TextBox I would like to get first view salutation selected value

    @using (Html.BeginForm("Compare", "Quote", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
    {
        @Html.AntiForgeryToken()

                            #
                            First Name
                            SurName
                            Date Of Birth
                            Email
                            Phone Number

                                1
                                @Html.TextBox("Salutation", new { @Value = "");

                                @Html.TextBoxFor(m => m.FirstName, new {@Value = Model.FirstName,  @class = "form-control" })
                                @Html.ValidationMessageFor(m => m.FirstName)

                                @Html.TextBoxFor(m => m.Surname, new {@Value = Model.Surname, @class = "form-control " })
                                @Html.ValidationMessageFor(m => m.Surname)

                                @Html.TextBoxFor(m => m.DOB, new {@Value = Model.DOB,  @class = "form-control" })
                                @Html.ValidationMessageFor(m => m.DOB)

                                @Html.TextBoxFor(m => m.Email, new {@Value = Model.Email,  @class = "form-control" })
                                @Html.ValidationMessageFor(m => m.Email)

                                @Html.DropDownListFor(m => m.Extensions, Model.Extensions, "Ext", new { @class = "form-control ext0" })
                                @Html.ValidationMessageFor(m => m.Extensions)

                                @Html.TextBoxFor(m => m.PhoneNumber, new { @class = "form-control phonenumber0" })
                                @Html.ValidationMessageFor(m => m.PhoneNumber)

                            Enter Dependent

                            <input type="text" name="numberofdependent" class="form-control numberofdepedentextbox " />

                            <input type="button" name="AddChild" value="Add Dependents" class="btn btn-primary btn-click" />

                            <input type="button" name="SaveDependent" value="Save Dependents" class="btn btn-primary" />

    }

Thanks in advance

A: This all handled in your post and get methods of your controller first post the view that will take in the model and than instead of posting the same view back or a successful view etc you can return it to the view you want passing the model in ... But I'm unsure exactly what you trying to do


text:
Q: "Undefined reference to" no idea why? Im working on a project for stm32f4 to my school. Im using CooCox IDE.
I wanted to add new files "przerwania.c" and "przerwania.h" to write some functions there - not in "main.c". But I have no idea why CooCox is showing me errors.
Earlier I wanted to move some of functions from main.c to pwm.c and them work! But I would like to make a new files couse i have more functions.
Errors in CooCox look like this:
[mkdir] Created dir: D:\CooCox\CoIDE\workspace\testowy2\testowy2\Debug\obj
   [cc] 12 total files to be compiled.
   [cc] arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb -Wall -ffunction-sections -g -O0 -c -DSTM32F407VG -DSTM32F4XX -DUSE_STDPERIPH_DRIVER -D__ASSEMBLY__ -ID:\CooCox\CoIDE\workspace\testowy2 -ID:\CooCox\CoIDE\workspace\testowy2\cmsis_boot -ID:\CooCox\CoIDE -ID:\CooCox\CoIDE\workspace\testowy2\cmsis_lib\include -ID:\CooCox\CoIDE\workspace\testowy2\cmsis -ID:\CooCox\CoIDE\workspace\testowy2\cmsis_lib -ID:\CooCox\CoIDE\workspace D:\CooCox\CoIDE\workspace\testowy2\cmsis_lib\source\stm32f4xx_syscfg.c D:\CooCox\CoIDE\workspace\testowy2\pwm.c D:\CooCox\CoIDE\workspace\testowy2\dupa.c D:\CooCox\CoIDE\workspace\testowy2\cmsis_boot\startup\startup_stm32f4xx.c D:\CooCox\CoIDE\workspace\testowy2\main.c D:\CooCox\CoIDE\workspace\testowy2\cmsis_lib\source\stm32f4xx_rcc.c D:\CooCox\CoIDE\workspace\testowy2\cmsis_lib\source\stm32f4xx_adc.c D:\CooCox\CoIDE\workspace\testowy2\cmsis_lib\source\stm32f4xx_gpio.c D:\CooCox\CoIDE\workspace\testowy2\cmsis_boot\system_stm32f4xx.c D:\CooCox\CoIDE\workspace\testowy2\cmsis_lib\source\stm32f4xx_exti.c D:\CooCox\CoIDE\workspace\testowy2\cmsis_lib\source\misc.c D:\CooCox\CoIDE\workspace\testowy2\cmsis_lib\source\stm32f4xx_tim.c
   [cc] Starting link
   [cc] arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb -g -nostartfiles -Wl,-Map=testowy2.map -O0 -Wl,--gc-sections -LD:\CooCox\CoIDE\configuration\ProgramData\testowy2 -Wl,-TD:\CooCox\CoIDE\configuration\ProgramData\testowy2/arm-gcc-link.ld -g -o testowy2.elf ..\obj\stm32f4xx_syscfg.o ..\obj\pwm.o ..\obj\dupa.o ..\obj\startup_stm32f4xx.o ..\obj\main.o ..\obj\stm32f4xx_rcc.o ..\obj\stm32f4xx_adc.o ..\obj\stm32f4xx_gpio.o ..\obj\system_stm32f4xx.o ..\obj\stm32f4xx_exti.o ..\obj\misc.o ..\obj\stm32f4xx_tim.o
   [cc] ..\obj\main.o: In function `main':
   [cc] D:\CooCox\CoIDE\workspace\testowy2/main.c:336: undefined reference to `Nowafunkcja'
   [cc] collect2.exe: error: ld returned 1 exit status

main.c is quite long becouse i have some definitions of few long functions there, so I paste here only a part
 #include "stm32f4xx.h"
 #include "misc.h"
 #include "stm32f4xx_syscfg.h"
 #include "stm32f4xx_adc.h"
 #include "stm32f4xx_exti.h"

 #include "przerwania.h"//here is the problem
 #include "pwm.h"

int main(void)
{

    SystemInit();
    //IniDiody();
    //TimConfig();
    //NVIC_Config();
    //IniDiodyPWM();

    LEDInit();
    EXTILine0_Config();

    PWM2();//wiwo
    GPIO();//wiwo

    Nowafunkcja();//PROBLEM

    RCC_Konfiguracja_Adc12();

    GPIO_Configuration_Adc1();
    ADC1_Configuration();
    GPIO_Configuration_Adc1();
    GPIO_Configuration_Adc2();
    ADC2_Configuration();

    IniDiody(GPIO_Pin_14);
    IniTimerPrzerwanie1();

    while(1)
    {
         ADC_SoftwareStartConv(ADC1);
         ADC_SoftwareStartConv(ADC2);
         while(ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET);
         wynikADC1 = (float)ADC_GetConversionValue(ADC1);
         while(ADC_GetFlagStatus(ADC2, ADC_FLAG_EOC) == RESET);
         wynikADC2 = (float)ADC_GetConversionValue(ADC2);
         wartosc = (int)(wynikADC2 * 15);
         //doPWM=(((float)ADCResult) / 41);
         //wartosc = (int) doPWM;
         //TIM2->CCR3 = (int) doPWM;

         TIM3->CCR2 = 65535;
         TIM3->CCR1 = wartosc;//(int)(wynikADC2 * 15);
         wartoscPrescalera=(int)SystemCoreClock;
    }

}

and files:
przerwania.h
#ifndef __przerwaniah
#define __przerwaniah

void Nowafunkcja(void);

#endif

przerwania.c
#include "przerwania.h"

void Nowafunkcja(void)
{
//nothing here - just for test
}

Do you have any idea what is the problem? I'm thinking about this since yesterday and its wird :/
I'll appreciate your help!

A: Take a look at the line under  [cc] 12 total files to be compiled.
When you added pwm.c, you also informed the compiler to include this file.  You'll see it listed there.  przerwania.c is not.
If you add przerwania the same way you added pwm, your IDE will take care of making sure it is included in the build.
I'm not sure what your current file/folder structure looks like:
http://www.coocox.org/CoIDE/Project_management_config.html can help you determine how to pull those new files into the build.
FWIW:
The (anthropomorphized) compiler step says: Is this valid code?  So it looks though your main.c, sees that you included przerwania.h, and comes to the conclusion that you correctly used the Nowafunkcja function (just matched the signature).  Even though at this point, it has NOT looked into przerwania.c to find out what it does.  The compiler goes on to do this for all of your files and keeps track of what functions are defined in each file.  Note that it never found the definition Nowafunkcja, because the compiler never compiled przerwania.c.  It did however find the declaration in the .h (because main.c told it exactly where to find the .h)
The linker then gets this stuff from the compiler, including what functions have been defined in all your .c files.  That's the first point where something tries to answer the question "Now what code do I actually need to run when he asked me to Nowafunkcja()?".  So that's the first point in the build when the tools realized, I never found code for Nowafunkcja in any of the .c files I was looking in.
So, I think that roughly answers "Why", but we need to know more about your project organization to give you a "fix" to make it work.


text:
Q: Here I have used functions and arrays to find out whether the matrix is symmetric or non- symmetric . Can anyone optimise my code using pointers? Here we are given a martix and we have to find out whether the matrix is symmetrix or not. I want to optimise it using array pointer or passsing by reference or you can suggest better approach , which uses multiple concepts, and please provide an explanation , it would be helpful.
I am learning arrays so, that why I am asking you to use multiple concepts , I want to see if there is a better approach
#include <stdio.h>
#include <stdlib.h>

void swap(int arr[3][3], int i, int j)
{
    int temp;
    temp = arr[i][j];
    arr[i][j] = arr[j][i];
    arr[j][i] = temp;
}

void check(int arr[3][3], int i, int j)
{
    static int count = 0;

    if (arr[i][j] == arr[j][i])
    {
           count++;
        if (count == 9)
        {
            printf("matrix is symmetric");
        }
    }
}
int main()
{

    int arr[3][3] = {1, 3, 3,
                     3, 1, 5,
                     3, 5, 5};

    int i, j;
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            printf("%d\t", arr[i][j]);
        }
        printf("\n");
    }

    for (int i = 0; i < 3; i++)
    {
        for (int j = i + 1; j < 3; j++)
        {
            swap(arr, i, j);
        }
        printf("\n");
    }

    printf("THE TRANSPOSE MATRIX IS \n");
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            printf("%d\t", arr[i][j]);
        }
        printf("\n");
    }

    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            check(arr, i, j);
            if (arr[i][j] != arr[j][i])
            {
                printf("matrix is non-symmetric");
                exit(0);
            }
        }
    }
}

A: To find symmetric matrix simply use the following code:
#include <stdio.h>
#define dim 4

int main()
{
    int i=0;
    int arr[dim][dim]= {1, 3, 2, 3,
                        3, 1, 5, 4,
                        2, 5, 5, 16,
                        3, 4, 16, 7};

    int isSymmetric = 1;
    while (isSymmetric && i<dim)
    {
        for (int j = i; j < dim; j++)
        {
            if(arr[i][j]!=arr[j][i]) {
                isSymmetric = 0;
                break;
            }
        }
        i++;
    }

    isSymmetric==1?printf("Symmetric"):printf("notSymmetric");
    return 0;
}

The complexity of this algorithm at most is O(N/2) when N is the number of elements.


text:
Q: Xcode -Certificate status says "Not in Keychain" but the Certificates are visible inside Keychain Access I got this computer in July. I had another computer before this and I successfully exported the signing certificate and it's private key and added them to this computer. Everything has been working fine. I successfully pushed 2 apps to AppStoreConnect last week.
On Monday I had a weird error (different from this question) and Revoked a certificate by mistake. Ever since then I keep getting the error:

Your account already has a signing certificate for this machine but it is not present in your
  keychain

When I go to Xcode > Accounts > Apple IDs > Team and click the plus sign it says

Not in Keychain // 2nd pic

At first when I tried to pull the missing Distribution Certificate into Keychain > login I kept getting this:

When I try it on the command line I get Segmentation fault: 11:
$ security import /Users/Home/Desktop/Certificates_Folder/my@email/Certificate.p12 -k ~/Library/Keychains/login.keychain

$ Segmentation fault: 11

Oddly it let me send every other certificate to login except that distribution one.
So instead I created a new keychain item named Brand_New_Keychain and added both the certificates in there. When I check in Brand_New_Keychain both certificates are present and they are both in System.
I unchecked Automatic, deleted the developer team using the minus sign then added it back, I closed Xcode, restarted the computer, opened Xcode, etc same problem persists.
As detailed in the photos below the Not in Keychain certificates are in Keychain Access. What is the problem here?
1- Signing Error

2- Not in Keychain Message

3- Expiration Date from the Development Certificate

4- Expiration Date from the Distribution Certificate

5- The new Keychain item I created Brand_New_Keychain > Certificates > both certificates with the same expiration dates from pics 3 & 4 that it's saying I don't have in Keychain

6- When I pushed one of my apps up to AppStoreConnect it said I didn't have a .p12 file for the app and created one for me. I downloaded it. This and it's private key is present in Brand_New_Keychain > My Certificates > the same expiration date as the missing Distribution Certificate from the 4th pic. The development certificate from the 3rd pic isn't here because I created it using the Revoke Certificate button from the 3rd pic. Afterwards I went to Apple and downloaded it but it never gave me a private key.

7- System > Certificates > both certificates with the same expiration dates from pics 3 & 4 that it's saying I don't have in Keychain

8- developer.apple.com > Certificates > both certificates with the same expiration dates from pics 3 & 4 that it's saying I don't have in Keychain. I downloaded both of these and the other 2, then clicked them all, dragged them into keychain, and even used security import /Users/Home/Downloads/Certificate.p12 -k ~/Library/Keychains/login.keychain to get each one in

*I went back to the old computer and successfully exported the original .p12 then imported in into Keychain so it's definitely there with it's private key.

*Every certificate with a private key I changed the Access Control to Allow all ...:

Update:
@matt suggested I create a new login in Keychain Access which I did. The same errors are still present however the 2nd pic when I go to Xcode > Accounts > Apple IDs > Team and click the plus sign has changed. Now it says:


text:
Q: Sharepoint Power PI Connection Requiring Input Of Credentials I have an excel workbook with 8 Power BI queries to a Sharepoint site. The queries work, but every day I have to clear the permissions on the data source. I then have to reconnect by re entering credentials. Is there a way to remove this step? Ultimately I want to automate this process.

A: Issue was caused by file sitting on a server that was being accessed by various users. Solution was to move to a local machine. This allowed the credentials to be stored correctly.


text:
Q: Uso de instanceof Criar uma classe abstrata Conta, e outras duas classes concretas ContaF e ContaJ que herdam da classe principal. Criar outra classe com um método que recebe uma lista de contaF e ContaJ e ArrayList<Conta> e calcule quantos elementos tem em ContaF e ContaJ
Estou quase finalizando:
public class InstanciaDe
{

public static void main( String[] args )
{

    ContaF Rafael = new ContaF();

    ContaJ Roberto = new ContaJ();

    ContaJ Carlos = new ContaJ();

    ArrayList<Conta> lista = new ArrayList<Conta>();

    lista.add(Rafael);
    lista.add(Roberto);
    lista.add(Carlos);

    for(int i=0 ; i < lista.size() ; i++){

        if (lista.get(i) instanceof ContaF) {

        }

        if (lista.get(i) instanceof ContaJ) {

        }
    }
}
}

Como posso guardar a quantidade pelo instanceof de cada e depois exibir?

A: É só criar um contador:
import java.util.*;

class InstanciaDe {
    public static void main( String[] args ) {
        int contaF = 0;
        int contaJ = 0;
        ContaF Rafael = new ContaF();
        ContaJ Roberto = new ContaJ();
        ContaJ Carlos = new ContaJ();
        ArrayList<Conta> lista = new ArrayList<Conta>();
        lista.add(Rafael);
        lista.add(Roberto);
        lista.add(Carlos);
        for(int i = 0 ; i < lista.size() ; i++) {
            if (lista.get(i) instanceof ContaF) {
                contaF++;
            }
            if (lista.get(i) instanceof ContaJ) {
                contaJ++;
            }
        }
        System.out.println(contaF);
        System.out.println(contaJ);
    }
}
class Conta {}
class ContaF extends Conta {}
class ContaJ extends Conta {}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.

A: import java.util.*;

class Conta {}
class ContaF extends Conta {}
class ContaJ extends Conta {}

class InstanciaDe {

    public static void main(String[] args) {
        ContaF Rafael = new ContaF();

        ContaJ Roberto = new ContaJ();

        ContaJ Carlos = new ContaJ();

        ArrayList<Conta> lista = new ArrayList<Conta>();

        lista.add(Rafael);
        lista.add(Roberto);
        lista.add(Carlos);

        System.out.println(getInstanceCount(contas, ContaF.class));
        System.out.println(getInstanceCount(contas, ContaJ.class));
    }

    public static int getInstanceCount(List<Conta> contas, Class<? extends Conta> class1) {
        int count = 0;

        for (Conta conta : contas) {
            if (conta.getClass().equals(class1)) {
                count++;
            }
        }

        return count;
    }
}


text:
Q: How to export database as sql in asp net core web api from client side I am using Asp.Net Core Web API and PostgreSQL for the database. How can the admins take the database backup as .sql file and can restore the data back whenever they want. I have nine tables.

A: You can use pg_dump. Your C# code may look like below:
var process = new Process();
var startInfo = new ProcessStartInfo();
startInfo.FileName = Path.Combine("PostgreSQL", "postgresql-backup.bat");
var host = "For Example:localhost";
var port = "For Example:5432";
var user = "For Example:postgres";
var database = "Your databaseName";
var outputPath = "Your localDatabasePath";

// use pg_dump, specifying the host, port, user, database to back up, and the output path.
// the host, port, user, and database must be an exact match with what's inside your pgpass.conf (Windows)
startInfo.Arguments = $@"{host} {port} {user} {database} ""{outputPath}""";
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
process.Close();

Restoring a database is similar, but using pg_restore.
For more details, you can refer to this GitHub.
Hope this can help you.


text:
Q: Cocos2d-android detecting randomly created sprites or rects I am developing an android game on Eclipse in which a sprite is jumping on several platforms to get to the top but I am having difficulties. Here is my case: I have the character sprite (I'll name this as Sprite1 in this case) that moves and I am creating another 3 sprites(the platforms) at random positions when my app starts. The platforms are successfully created when the app starts. But the collision between them and Sprite1 is not detected. I tried many solutions and I am stuck for a couple of days now. Any help or suggestion will be appreciated.
I tried making rects when the platforms are created then using the rects to detecting collisions but they still don't collide. I use Java language. :)
I use this to create the sprites and detect collisions:
Creating platform sprites (this is how i randomly spawn platforms, if there are mistakes here, i'm sure i just copied wrong because the creating or platform sprites works correctly.):
public void addRandomPlatform(){
    Random rand = new Random();
    randPlat = CCSprite.sprite("platform2.png");
    randPlat.setPosition(actualX, actualY);
        actualY -= (int)(randPlat.getContentSize().height*4);
        addChild(randPlat,2);
}

Then I just call this method when my app starts.
Detecting Collision:
playerRect = CGRect.make(player.getPosition().x - (player.getContentSize().width /   4.0f),//- (player.getContentSize().width / 2.0f),
                     player.getPosition().y - (player.getContentSize().height / 2.0f),
                 player.getContentSize().width/3.0f,
                 player.getContentSize().height/8.0f);

if(CGRect.intersects(playerRect, randPlat))
    {
       *my codes for stopping the jump*
}

I hope this is clear. Thanks in advance!

A: It looks like the randRect is a CCSprite, and not a CGRect. You should create a CGRect(of the random platform) the same way you created the playerRect.
Also, why do you divide the player's width/height by respectively 3 and 8? I don't think that's what you want, and it causes the playerRect to be only a thirth of the width, and 1/8 of the height of the actual sprite.

A:     @Override
    public boolean ccTouchesEnded(MotionEvent event) {
  CGPoint point =  ranSprite.getPosition();// THE POSITION MUST BE YOUR RANDOM SPRITES POSITIONS

        List<CCNode> childsList = this.getChildren();

        for(CCNode childSprite : childsList){

            if(childSprite.getTag() == Constants.PLAYER_TAG   && childSprite.getBoundingBox().contains(point.x, point.y)){

                // Do what ever you want

}
}


text:
Q: Cannot see console.log-s in React I can't remember when it started happening but basically as the title says I can't see console.log-s on my app but the states are getting updated because the app is working properly. And then if I update something in the code anything at all and the app recompiles I suddenly see everything that I logged before and after the second recompile. It happens across all of my app components.
Even the errors I receive just say where the error is and not what it is. I tried taking out component by component in hopes that the logs will start appearing but the problem persists.
console.log("something")

console.log("something")
console.log("something else")

Here is a purposely created error to simulate the problem

Hope someone can help.

A: You have the console filter set

A: You have an active filter, remove that and you should be good to go.
Current active filter

A: Check the console filters.
For some reason it happens like this...


text:
Q: Cannot find data in single MongoDB query using Node.js I need to find the collection data by an single MongoDB query using Node.js. I am providing the collection below.
f_user_login:
{
    "_id": {
        "$oid": "5981b48654d471000459208e"
    },
    "email": "subhrajyoti.pradhan@oditeksolutions.com",
    "password": "d0e49bcba946540cb3d5fc808870d16b",
    "dob": "02-08-2017",
    "created_date": "2017-08-02 11:16:21",
    "updated_date": "2017-08-02 11:16:21",
    "status": 1,
    "token": "b85ff4c47093217587f8c7f2fff7ff86b1bcbf6a7321705871435929ee38",
    "verification_id": ""
}

{
    "_id": {
        "$oid": "598aa189e5f78d00042f48ae"
    },
    "email": "subhrajyotipradhan@gmail.com",
    "password": "d0e49bcba946540cb3d5fc808870d16b",
    "dob": "1986-04-10",
    "created_date": "2017-08-09 05:45:44",
    "updated_date": "2017-08-09 05:45:44",
    "status": 0,
    "token": "",
    "verification_id": "7ffbe3f9be82b2af84491d3e8dff4fa1a65f973d"
}

I am providing my code below.
exports.userSignin=function(req,res){
    var email=req.body.email;//subhrajyotipradhan@gmail.com
    var password=req.body.password;//d0e49bcba946540cb3d5fc808870d16b
    var pass=mden(password);
    if (email !='' && password !='') {
        db.f_user_login.count({email:email,password:pass,status:1},function(err,docs){
            if(docs > 0){
                token=crypto.randomBytes(30).toString('hex');
                db.f_user_login.update({email:email},{$set:{token:token}},function(err,doc){
                    db.f_user_login.find({email:email},function(error,docu){
                        var edata=[{"email": docu[0].email,"dob": docu[0].dob,"created_date":docu[0].created_date ,"id": docu[0]._id,"updated_date":docu[0].updated_date,"token_id":token}];
                        var data={"statusCode": 200,"data":edata,"message": "The user logged successfully."};
                        res.send(data);
                    })
                })
            }else{
                console.log(email,password);
                db.f_user_login.find({$or:[{email:email},{password:pass},{status:1}]},function(err,getdocs){
                    if (!err) {
                        var uemail=getdocs[0].email;
                        var upass=getdocs[0].password;
                        var ustatus=getdocs[0].status;
                        console.log('email,pass,status',uemail,upass,ustatus);
                        if (uemail != email) {
                            var data={"statusCode": 401,"error": "Unauthorized","message": "Invalid email id .Please provide a valid email id"};
                        }
                        if (upass != pass) {
                            var data={"statusCode": 401,"error": "Unauthorized","message": "Invalid Password .Please provide a valid Password"};
                        }
                        if (ustatus == 0) {
                            var data={"statusCode": 401,"error": "Unauthorized","message": "you have not verified your account using the link sent to your email."};
                        }
                        res.send(data);
                    }
                })
            }
        })
    }
}

Here my input email and password is right and I need to check the status and get this you have not verified your account using the link sent to your email. message. But unfortunately both document has same password its always checking the first document but originally I need to check the second document for validation.
It is possible using 3 three different query but here I want to operate a single query. Is this possible?

A: You can use below code for the entire process:
Note: Some typos or code may need to be changed. But you can use the basic idea.
 if (email !='' && password !='') {
   console.log(email,password);
   db.f_user_login.find({$and:[{email:email},{password:pass}]},function(err,getdocs){
    if (!err && /*check if the getdocs is not empty*/) {
        var uemail=getdocs[0].email;
        var upass=getdocs[0].password;
        var ustatus=getdocs[0].status;
        // update your collection from here with ID
        // Remember update is work fine with id
        console.log('email,pass,status',uemail,upass,ustatus);
        if (ustatus === 0) {
            var data={"statusCode": 401,"error": "Unauthorized","message": "you have not verified your account using the link sent to your email."};
        }else if(ustatus === 1){
            var data={"statusCode": 200,"data":edata,"message": "The user logged successfully."};
        }
        res.send(data);
    }
  })
}


text:
Q: Function prototyping in C language Why can't my code run when I am using a function name "div". But when I change it to any name like " divi",it runs.Can someone explained it? Im 1st yr.
 #include <stdio.h>
 #include <math.h>
 #include <stdlib.h>

 double div(int, int);

 int main(void)
 {
    int num1, num2;
    printf("Enter the numbers: \n");
    scanf("%d", &num1);
    printf("Enter the numbers: \n");
    scanf("%d", &num2);
    printf("The answer is %.2f", div(num1,num2));
 }

 double div(int x, int y)
 {
    double quot;
    quot=((double) x/y);
    return quot;
 }

A: The standard library already defines a function called div, so you can't use that name for your own function.


text:
Q: What is the difference btw BehaviorSubject.add and BehaviorSubject.sink.add? In Google I/O 2018 video (the code), it uses BehaviorSubject.add.
But in Flutter official recommended article's code, it uses BehaviorSubject.sink.add.
Why and What is the difference? and Which one should I use? Or are they the same?
Thanks.