looking for some solutions? You are welcome.

New Commnt: ★★Re: Google Camera HDR+ Port Updated with Zero Shutter Lag, More Xiaomi Device Support, and Major Bug Fixes ★★

Doesn't work on Xiaomi Redmi 4X with official Resurrection Remix, will try with MIUI 9



from XDA-Developers - Latest Comments by ElPirer97
Read More
Share:

New Commnt: ★★Re: Sony Announces Which Devices They’re Updating to Android Oreo ★★

Offtopic....



from XDA-Developers - Latest Comments by Caitlin550
Read More
Share:

SOLVED: I have been asked to keep a secret about a surprise that I believe will end poorly – interpersonal.stackexchange.com

Beofett: My parents have been divorced for roughly 40 years. The separation was unpleasant, as divorces frequently are, but so were the following decades. They have not spoken to each other outside of a ...

Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Is Jon Snow immune to fire? – scifi.stackexchange.com

King of NES: We've seen his aunt survive all fire and I even remember she almost enjoyed the scalding bath. Jon was resurrected by the fire god. Is John now immune to fire, and just doesn't know it?

Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: ASP.NET Core Model Binding Error Messages Localization in ASP.NET CORE 2.0

Fritz:

In ASP.NET CORE 1.1 it was possible to localize model binding error messages using a resource file and configure its options to set message accessors for ModelBindingMessageProvider in the Startup.cs like

services.AddMvc(options =>
{
    var F = services.BuildServiceProvider().GetService<IStringLocalizerFactory>();
    var L = F.Create("ModelBindingMessages", null);
    options.ModelBindingMessageProvider.ValueIsInvalidAccessor =
        (x) => L["The value '{0}' is invalid."];

as shown here: ASP.NET Core Model Binding Error Messages Localization and here: http://ift.tt/2pYcUmn

In ASP.NET CORE 2.0 I receive an error message on all of the ModelBindingMessageProvider's properties

options.ModelBindingMessageProvider.ValueIsInvalidAccessor 

is readonly

How can these messages be localized in ASP.NET CORE 2.0

EDIT:

The changed and working Code:

      services.AddMvc(options =>
        {
            var F = services.BuildServiceProvider().GetService<IStringLocalizerFactory>();
            var L = F.Create("ModelBindingMessages", "NAME_OF_YOUR_PROJECT");
            options.ModelBindingMessageProvider.SetValueIsInvalidAccessor ((x) => L["The value '{0}' is invalid."]);



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

New Commnt: ★★Re: How to Hide the “App is Running in the Background” Persistent Notification on Android Oreo ★★

Thanks , adding the 3 minute timeout and a 15 second wait to the front end made it happen!



from XDA-Developers - Latest Comments by David Smith
Read More
Share:

SOLVED: How to say if I want to select a few largest sizes of apples? – ell.stackexchange.com

user5802211: I want to say, for example, I have many apples, I want to select some apples according to the descending order of size, but I don't want to explicitly mention how many apples I select, I just select ...

Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

There’s an Easy Fix for the Essential Phone’s Camera Quality – Google’s Camera App ★★ XDA DEVLOPERS FORUM ★★

The company behind the Essential Phone, while selling a nice looking phone with some pretty high end specifications, have made some pretty questionable decisions. We wrote an article detailing our problems with the device and the company behind it. What’s more, not even a day after we published that article Essential seemingly messed up again, leaving a small number of customers in a potentially dangerous position. In an attempt to regain goodwill from users, those who received the disturbing email will receive a free phone and a year of LifeLock service.

And those are only problems relating to the company.

The phone itself seems pretty decent, especially software wise thanks to its nearly stock Android. Not fantastic, not “essential”, just good. But one of the biggest issues with the device has been the camera experience. Nearly universally, reviewers and early users of the phone have stated that the camera experience just isn’t on par with other flagship phones in its category. The phone provides a slow, laggy picture taking experience with poor quality photos and a lot left to desire.


The Essential Phone’s Camera Potential is Held Back by Software

Thankfully, a review over on TheNextWeb.com points out that the Google Camera HDR+ port we covered works very well on the device. The difference is absolutely night and day, and shows that the Essential Phone’s camera can be saved. The sensor certainly has potential as showcased by the images below, taken on an Essential PH-1 by reviewer Napier Lopez.

Before I show the other images, I just need to point out how amazing the Google Camera HDR+ is against the stock camera. There is substantially less noise and an impressive amount of detail in comparison. These photo comparisons were enough to sway me – the Essential Phone actually has a good camera, but it is held back by the stock camera software.

Left is stock, right is Google Camera HDR+ Port. Credits: Napier Lopez \\ TheNextWeb

Left is stock, right is Google Camera HDR+ Port. Credits: Napier Lopez \\ TheNextWeb

If you still aren’t convinced, TheNextWeb tells us they will have a more detailed comparison between HDR+ on the Google Camera app versus the stock camera app, so be sure to check that out.

As for the pictures we’ve seen so far, they are of a much better quality with nicer colors and greater detail when taken on the Google Camera app. This shows the phone’s camera woes actually come from the camera processing software, and not the camera sensor itself. If the device has potential for photos like those shown above and can consistently do as good of a job as these, keep an eye out on future software updates from Essential – the camera quality still has room to grow.



from xda-developers By Adam Conway

READ FULL ARTICLE

Share:

SOLVED: Cannot send POST data to Lambda

Kern Elliott:

I am trying to send data to my lambda function however the function is not getting my data, the event variable is empty. I am not getting any errors and when I test the function in my API Gateway it works fine. So I am not sure what is happening. My code for sending data to Lambda is below.

var options = { 
    method: 'POST', 
    url: 'correct api url', 
    contentType: "application/json",
    dataType: "json",
    data: s
}

for data: s within my console looks like this data: '{"article_url":"a url here"}'

Any idea what the problem is?



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: How to update uniforms in Three.js

Eben Cowley:

I'm in the process of learning Three.js. Right now I'm adapting a shader that I made in Shader Toy to go on my own web page. It's a procedural terrain shader where the user can move around with the WASD keys. Currently, everything is working except for the movement. The position is declared in javascript as follows:

var pos = new THREE.Vector2(0, 0);

I update the value of pos with an event listener:

window.addEventListener("keydown", function(event){
switch (event.keycode) {
    case 65: pos.x -= 0.25;
      break;
    case 68: pos.x += 0.25;
      break;
    case 83: pos.y -= 0.25;
      break;
    case 87: pos.y += 0.25;
      break;
    default: return;
}
});

The value is initially passed to the frag shader in the declaration of the shader material:

var shader = new THREE.ShaderMaterial({
    vertexShader: document.getElementById('vs').textContent,
    fragmentShader: document.getElementById('fs').textContent,
    depthWrite: false,
    depthTest: false,
    uniforms: {
        res: {type: "v3", value: resolution},
        time: {type: "f", value: 0.0},
        deltaTime: {type: "f", value: 0.0},
        frame: {type: "i", value: 0},
        mouse: {type: "v4", value: mouse},
        pos: {type: "v2", value: pos},
    }
});

and the updated value is passed to the shader in the second-to-last line of the render function:

function render() {
    requestAnimationFrame(render);
    if (canvas.width !== canvas.clientWidth || canvas.height !== canvas.clientHeight) {
        renderer.setSize(canvas.clientWidth, canvas.clientHeight, false);
        camera.aspect = canvas.clientWidth/canvas.clientHeight;
        camera.updateProjectionMatrix();
        resolution = new THREE.Vector3(canvas.clientWidth, canvas.clientHeight, 1.0);
    }
    shader.uniforms['res'].value = resolution;
    shader.uniforms['time'].value = clock.getElapsedTime();
    shader.uniforms['deltaTime'].value = clock.getDelta();
    shader.uniforms['frame'].value = 0;
    shader.uniforms['mouse'].value = mouse;
    shader.uniforms['pos'].value = pos;
    renderer.render(scene, camera);
}

I don't know what could be going wrong here but I expect that it has something to do with the event listener since it's existence the only difference from the nature of all the other uniforms. Hopefully I haven't made a silly mistake, like I said, I've just begun learning these libraries.

UPDATE:

I tried instead taking input the same way I am with the mouse. i.e. adding a function to the js:

function readkeys(event){
    switch (event.keycode) {
        case 65: pos.x -= 0.25;
            break;
        case 68: pos.x += 0.25;
            break;
        case 83: pos.y -= 0.25;
            break;
        case 87: pos.y += 0.25;
            break;
        default: return;
    }
}

and then in the html:

<canvas id="canvas" onmousemove="readmouse(event)" keydown="readkeys(event)/>

The shader was still unresponsive to keyboard input.



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Why don't certain commands work when connected to a server using FTP? – unix.stackexchange.com

Emile: I'm logged into a linux server and use ftp placeftp.thing.com to connect to a different server. I receive the message below and now I can transfer files to that server, however a basic unix command ...

Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

New Commnt: ★★Re: Andy Rubin Apologizes for Customer Service Issues, Offers Affected Customers a Free Phone and More ★★

Gimme a free one now and I will think about buying the next one.



from XDA-Developers - Latest Comments by ✓ᵛᵉʳᶦᶠᶦᵉᵈ
Read More
Share:

New Commnt: ★★Re: Here is a Crazy Thought: Google Should Buy HTC’s Crumbling Mobile Division ★★

They will be losing more money than when they bought Motorola, without any real gain.



from XDA-Developers - Latest Comments by ✓ᵛᵉʳᶦᶠᶦᵉᵈ
Read More
Share:

New Commnt: ★★Re: Motorola Launches the Mid-Range Moto X4 for €399, Europe Release in September, US in the Fall ★★

Weird.



from XDA-Developers - Latest Comments by inkmars
Read More
Share:

SOLVED: How can I multiply a binary representation by 10 using logic gates? – cs.stackexchange.com

user76675: So I’m currently working on something and I have converted all decimal digits 0-9 into binary. But now I want to take say 6 in binary and increase its order of magnitude by base 10 (turning 6 into 60) ...

Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Go away! No-1's Here! – codegolf.stackexchange.com

geokavel: I was playing around with some numbers and found a sequence that, of course, is on OEIS. It is A005823: Numbers whose ternary expansion contains no 1's. It goes: a(2n) = 3*a(n)+2 a(2n+1) = ...

Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Libraries in dotnet core 2.0 get FileNotFound exception

twreynol:

We have a system that relies heavily on "Adapters" that implement a simple interface for doing unique processing. Normally, we dynamically load these by assembly name, but in this case we simply want to load them as "Libraries" from within our solution. In dotnet Core 2.0, this seems to be broken. I am including a small sample that exhibits this problem. Perhaps my design is flawed, or something has changed. This same pattern is working well for us in dotnet Framework (prior to Core).

I am including an example and a screen shot of what my sample project looks like, but this is the jist of it.

Solution Folder Layout

I have a dotnet core 2.0 "library" called ExternalAdapter.

public class TheAdapter : TestExternalInterface.Interfaces.ISomeExternalAdapter
{
    public string GetSomeValue(string valueType)
    {
        switch (valueType)
        {
            case "Red":
            case "red":
                return "Your color is red";
            case "Blue":
            case "blue":
                return "Your color is blue";

            default:
                return "Unknown Value Type";
        }
    }

    public List<string> GetSomeValues(string valueType)
    {
        switch (valueType)
        {
            case "Color":
            case "color":
                return new List<string> { "Red", "Blue" };
            case "Flavor":
            case "flavor":
                return new List<string> { "Sweet", "Savory" };

            default:
                return new List<string> { "Color", "Flavor" };
        }
    }
}

It has a class in it named TheAdapter that implements the ISomeExternalAdapter interface.

I have a dotnet core 2.0 "console app" that instantiates a new ExternalAdapter.TheAdapter() as the ISomeExternalAdapter interface.

class Program
{
    static void Main(string[] args)
    {
        try
        {
            Console.WriteLine("About to load external adapter...Press <ENTER> to continue.");
            Console.ReadLine();
            LoadAndTestExternalAdapter();            
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
        Console.ReadLine();
    }

    private static void LoadAndTestExternalAdapter()
    {
        Interfaces.ISomeExternalAdapter adapter = new ExternalAdapter.TheAdapter() as Interfaces.ISomeExternalAdapter;
        Console.WriteLine(adapter.GetSomeValue("red"));
        Console.WriteLine(adapter.GetSomeValues("flavor"));
    }
}

This fails with a System.IO.FileNotFoundException:

Could not load file or assembly 'ExternalAdapter, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.

Yet when I look in my \bin\Debug\netcoreapp2.0 folder of the main program, the ExternalAdapter.dll is found.

If I do a clean / rebuild, it dutifully puts it there as well, so I am pretty sure the file should be found.

Is this a bug in 2.0? or do we need to load "Interfaced" adapters a different way?

Our eventual project has dozens of "adapters" that will be loaded via their interface depending on the type of processing we need to do at our server, but this small example points out the problem we are having in our main app. Any and all help is appreciated.



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Mapping a function on a generator in JavaScript

damd:

I have a generator called generateNumbers in JavaScript and another generator generateLargerNumbers which takes each value generated by generateNumbers and applies a function addOne to it, as such:

function addOne(value) {
  return value + 1
}

function* generateNumbers() {
  yield 1
  yield 2
  yield 3
}

function* generateLargerNumbers() {
  for (const number of generateNumbers()) {
    yield addOne(number)
  }
}

Is there any terser way to do this without building an array out of the generated values? I'm thinking something like:

function* generateLargerNumbers() {
  yield* generateNumbers().map(addOne) // obviously doesn't work
}



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: C - Two child process with same parent and calling function server()

mdelclaro:

EDIT ---- After running several times, and many inputs, I noticed that the child processes are indeed changing between each other. Also, thank for the tips.

I have this program that "simulates" a parking lot. I have been searching a lot and I couldn't find anything that really fits on my problem. But if you know a similar question that could answer mine, send me the link! :)

This is my main, with the second child process already created (I don't think I need to put comments here, it's only doing a fork(), then inside the parent it does a second fork(), creating another child with the same parent. Right?):

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char spots[25];

main()
{
 int    descritor, descritor2, //gets the fork's pid
 pipe1[2],  // comunicacao pai -> filho
 pipe2[2];  // comunicacao filho -> pai
 char msg[10] = "";


if (pipe(pipe1)<0 || pipe(pipe2) <0)
{ 
    printf("Erro na chamada PIPE");
    exit(0);
}


if ((descritor = fork()) <0)
{ 
    printf("Erro na chamada FORK");
    exit(0);
}

else if (descritor > 0)  
{   
    descritor2 = fork(); 

    if(descritor2 == 0)
    {
        strcpy(msg,"CHILD 2");
        fprintf(stdout, msg);

        close(pipe1[1]); 
        close(pipe2[0]);  

        server(pipe1[0], pipe2[1]); 

        close(pipe1[0]); 
        close(pipe2[1]);  
        exit(0);
    }

    else if (descritor2 > 0) 
    {           
        close(pipe1[0]);
        close(pipe2[1]);  

        client(pipe2[0], pipe1[1]); 

        close(pipe1[1]); 
        close(pipe2[0]);  
        exit(0);
    }

    else if (descritor2 < 0)
    {
        printf("Erro na chamada FORK");
        exit(0);
    }

} 

else 
{   
    strcpy(msg,"CHILD 1");
    fprintf(stdout, msg);

    close(pipe1[1]); 
    close(pipe2[0]);  

    server(pipe1[0], pipe2[1]);  

    close(pipe1[0]);
    close(pipe2[1]);  
    exit(0);

 } 
}  

I have the parent process which is calling the client function below:

client (int readfd, int writefd)

//    readfd, leitura do pipe2[0]
//    writefd; escrita no pipe1[1]

{
 char buff[2];
 int i, pos = 0;

 system("clear");

 populating(); //this is a function I call only this time to populate my global char array with the spots 1-25
 printing(pos); //this one I use to update and to print the spots

 while(1)
 {
    printf("\nDigite sua vaga -> "); //type the spot
    gets(buff);
    write(writefd, buff, 10); //sends to server (child)

    read(readfd,buff,10); //reads from server (child)
    pos = atoi(buff); //parses to int, because I think I can't write() read() int data, and I need to use this data (pos) to update my spots

    if(spots[pos] == 0) //check if it's occupied
    {
        sleep(1); 
        system("clear");
        printing(0); //passes the value 0 to update spots[0] which contains nothing
        printf("\nEsta vaga esta ocupada!\n");
    }
    else
    {
        printf("Vaga %s reservada.\n",buff);

        sleep(1); 
        system("clear");
        printing(pos); //the function printing is only a loop that gets the value typed earlir and do spots[pos] = 0. then print the spots updated
    }       
 }

}

Then I have my server function:

server(int readfd, int writefd)
// readfd, leitura do pipe1[0]
//   writefd; escrita no pipe2[1]

{
 char buff[2];
 int n, fd, pos;


while(1)    
{
    read(readfd,buff,10); //read the spot
    pos = atoi(buff);

 if(pos > 25 || pos < 1)//checks if it's in range
 {          
    while(pos > 25 || pos < 1)
    {
        printf("\nVaga indisponivel. Digite novamente\n");
        printf("-> ");      
        gets(buff); 
        pos = atoi(buff);
    }
}

 write(writefd, buff, 10); //sends the spot back to the parent
}


}

So, based on this, I have a few questions and would appreciate if someone could help with them.

I want to make the two child process "fight" for the cpu, but I noticed that I'm getting stuck with only one child. Is that because of the "while(1)"? If so, how could I do a loop to keep the program running then? Or the problem is that I'm using two pipes for 3 processes? (pipe1 I read from one side and write from the other, and vice-versa).

I also noticed that the messages "CHILD 1" or "CHILD 2" only prints when I type an invalid spot... Why is that?

So, summing all this up, I want to keep the two child processes running and getting the spot typed on father "concurrently", running one child process a few times, then the other, and so on. And seeing if it's on range. I would also want to see if the spot == 0, but this doesn't work on the child process, I don't know why, so I left this on the parent.

It's working with no errors at all, but the problem is that I think there's only one child running per execution... I want to make both of them run.

If you need additional information in order to understand my situation or something else, ask me!



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Could people in a post-apocalyptic setting work around the fact that fuel expires? – worldbuilding.stackexchange.com

T. C.: Typically, gasoline has a short shelf life (some months, maybe a year). This is handwaved in some post-apocalyptic settings where the writer wanted vehicles to play a major role (such as Mad Max — ...

Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

New Commnt: ★★Re: Exclusive: Android Oreo Will Receive Rootless, System-Wide Theme Support Within 1 Week ★★

So like its 7 days later...I know its pushing it but I'm really looking forwarded to hearing this is released so I can get it installed...Any update on the release date?



from XDA-Developers - Latest Comments by JCB
Read More
Share:

New Commnt: ★★Re: Mod to Customize the UI of your Google Pixel running Android Oreo ★★

Didn't they say a week last week?



from XDA-Developers - Latest Comments by Aaron
Read More
Share:

SOLVED: Is it OK to decline a review request after a resubmission? – academia.stackexchange.com

Pedro Mediano: I have served as a reviewer for a few journals multiple times, and I typically take the task very seriously and aim to provide informative and constructive reviews. However, there's this one case that ...

Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

New Commnt: ★★Re: Mod to Customize the UI of your Google Pixel running Android Oreo ★★

Or just wait a week for substratum



from XDA-Developers - Latest Comments by GarnetSunset
Read More
Share:

New Commnt: ★★Re: Here is a Crazy Thought: Google Should Buy HTC’s Crumbling Mobile Division ★★

Google should have bought HTC ages ago and keeping up the Nexus-line alive. Just think of it: HTC 10 as Nexus. This would have been so great and awaited by many people. But sadly, Google went fully *ssh*le and brought a locked down, unbeloved, ugly phone with - to be honest - pretty good specs and quality of photos.
@Google: How about to get your lazy *ss up again, buy HTC and bring us back what we loved? Never gonna happen, I know. You looked up to Apple and thought: "Wow... they sell pretty standard phones, get rid of important things for customers and even then, they're willing to pay thousands of dollars, just to get something from them! We wanna too!"
But this never got happen to you too, did it? Nah. Because you sold your soul. Remember? You wanted to be the "Good guys". Rotten & forgotten, it seems.

Well... "Google buying HTC"... ages ago I would have said: This is great! Go for it!
And now: Kinda meh. Do whatever you want. I simply don't care anymore.



from XDA-Developers - Latest Comments by MickyFoley@XDA
Read More
Share:

New Commnt: ★★Re: Andy Rubin Apologizes for Customer Service Issues, Offers Affected Customers a Free Phone and More ★★

ESSENTIALly a bad reputation for this startup no matter what their efforts are, customers still may feel this company is worth a 50/50 trust.



from XDA-Developers - Latest Comments by enzo_cz
Read More
Share:

New Commnt: ★★Re: Here is a Crazy Thought: Google Should Buy HTC’s Crumbling Mobile Division ★★

I don't think Google should buy any Android OEM again. Even if Google is selling Nexus and Pixel branded devices, they are still made by 3rd party manufacturer so the tension between Google and it's partners are staying minimum.

But if Google start making devices themselves then it's a different story. Even if on outside the relation between OEM's and Google looks fine but the tension between them is rising day by day. More OEM are pushing Google alternative services day by day even Motorola is now pushing Alexa in their new Moto X4.

If Google becomes a full OEM once again the situation will be worse than before.



from XDA-Developers - Latest Comments by Kawshik Ahmed
Read More
Share:

Add a Quick Settings Display Mode Tile to the Samsung Galaxy S8/S8+ ★★ XDA DEVLOPERS FORUM ★★

Samsung’s OEM ROM software comes with hundreds of additional features on top of stock Android, and there are a ton of of quick settings tiles for some of them. However, those of you on the Samsung Galaxy S8 or Galaxy S8+ may have noticed that a display mode quick settings tile is missing, so there’s no easy way to change between Adaptive Display/AMOLED Photo/AMOLED Cinema/Basic.

For that reason, XDA Assistant Forum Admin the_scotsman has put together a guide to create a quick settings tile to switch between these modes yourself. This method does require root as you will be writing to a kernel preference file to change the display mode. You will also need to have Tasker installed to create the custom quick setting tile, but the guide itself is quite easy to follow and walks you through the entire process of getting this working.


Guide to Add Quick Setting Display Mode Tile



from xda-developers By Doug Lynch

READ FULL ARTICLE

Share:

New Commnt: ★★Re: Sony Announces Which Devices They’re Updating to Android Oreo ★★

And what about L1 ? ......



from XDA-Developers - Latest Comments by DunoCZ
Read More
Share:

SOLVED: using profile that assume role in aws-sdk (AWS JavaScript SDK)

Anders Lundsgard:

Using AWS SDK for JavaScript I want to use the default profile that assumes the a role. It works perfect with native AWS Cli but using node.js with aws-sdk do not assume the role but only uses credentials to the AWS account where the access key belong to. I've found this documentation but it does not deal with assuming role: http://ift.tt/2wlVRxN

Any tip?

This is my config file:

[default]
role_arn = arn:aws:iam::123456789:role/Developer
source_profile = default
output = json
region = us-east-1



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Stack switching in linux process

zzz777:

To do unit tests for multi-process/mutli-thread interactions I am looking for an example of a stack switching (or small non-preemptive multi-tasking os) inside Linux process. Say two pseudo-tasks: taks A runs until it calls 'switch' primitive then pesudo-task B is continued until it calls 'switch'



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Xcode wkwebview html select menu open in popup

amit kumar:

I am using wkwebview and want to avoid opening default safari/wkwebview select menu drop opener that shows at the bottom when user clicks on any HTML drop downs in my webpage.

Instead, i want to open the drop down in the native UIpopup, is there a way I can do this?



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: ViewPager returning empty array

A Parham:

When i start my app I want my customSwipeAdapter.java to wait until my savedImages ArrayList has received and been populated with the data from firebase but instead my class is being ran and my whole page is empty because getCount() method is returning savedImages.size() as 0 because my arraylist hasn't been populated in time. Any help on maybe running my class when my array list is populated. Not sure what to do here :)

customSwipeAdapter.java

    public class customSwipeAdapter extends PagerAdapter {

            private Firebase mRef;

            private Context ctx;
            private LayoutInflater layoutInflator;
            public customSwipeAdapter(Context ctx) {
                this.ctx = ctx;
            }

            private int[] frontImages = {R.drawable.amen_parham, R.drawable.janel_parham, R.drawable.kevin_parham};

            // Populate ArrayList with firebase data
            List<String> savedImages = new ArrayList<String>();

            @Override
            public int getCount() {
                return savedImages.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object o) {
                return (view == o);
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {

                getSavedImages_FromDB();

                layoutInflator = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                final View item_view = layoutInflator.inflate(R.layout.swipe_layout, container, false);

                final EasyFlipView mYourFlipView = (EasyFlipView) item_view.findViewById(R.id.flipView);

                ImageView imageView_Front = (ImageView) item_view.findViewById(R.id.imageView_Front);
                imageView_Front.setImageResource(frontImages[position]);

                container.addView(item_view);

                System.out.println(savedImages);

                return item_view;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView((RelativeLayout)object);
            }

            public void getSavedImages_FromDB() {
                mRef = new Firebase("");

                if (goingToCallOnce == false) {
                   goingToCallOnce = true;
                mRef.child("Q6i3fI6lNdYYS0z5Jty4WUYE9g13").child("SavedImages").addChildEventListener(new ChildEventListener() {

                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                    String savedImage = (String) dataSnapshot.child("Image").getValue();

                        savedImages.add(0, savedImage);

                }

                @Override
                public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onChildRemoved(DataSnapshot dataSnapshot) {

                }

                @Override
                public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onCancelled(FirebaseError firebaseError) {

                }
            });
        }

        mRef.addListenerForSingleValueEvent(new ValueEventListener() {

            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                finishedLoadingData = true;
                System.out.println("finishedLoadingData");
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {

            }
        });
    }
}

savedCardsViewController.java

public class savedCardsViewController extends AppCompatActivity {

    private Swipe swipe;
    ViewPager viewPager;
    customSwipeAdapter adapter;

    private Firebase mRef;

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

        viewPager = (ViewPager) findViewById(R.id.view_pager);
        adapter = new customSwipeAdapter(this);
        viewPager.setAdapter(adapter);
        viewPager.setPageTransformer(false, new DefaultTransformer());

    }
}



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: jQuery click() not working on Google +1 Button

Kane:

This page (http://buttonspace.com) is using the Google +1 button at the top.

Documentation: http://ift.tt/12h91Wf

It was working fine until about 2 months ago, when I'm assuming Google updated the code for their button.

Any ideas why this jQuery click() code isn't firing?

<script>
    $("#g-plusone").click(function(){
        console.log("Clicked!");
        alert("Clicked!");              
    });
</script> 



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Exiting a loop without having a window active and sleep in C++

JAR:

I am searching for a method to exit a loop while I don't have a window active (I can't use command window functions like getchar and so on).

Also, the loop has sleep involved. How can I get out of the loop at any time by pressing a key? I have tried Getkeystate, but it won't work because of the sleep. Or is there at least a way of getting the keypress in some sort of buff, that the loop stops as soon as it reaches the start again?



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: How to change background color when changing orientation in Andriod?

Matsson:

I'm kind of new to Android Studio and appmaking. I wonder how to change the background color when a user shift his device from portrait mode, to landscape?

Example: White background color in portrait mode, Green background color in landscape mode,



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Custom Taxonomy Template won't show any menus

pandabrand:

This is how I can start describing this, it's a very strange error that maybe something else but this is the first symptom I have.
I have a custom template[taxonomy-location_types.php] that shows, a custom post type [locations] by it's custom taxonomy[location-types].

If you visit the home page you will see a menu editorial, travel, etc.
Now if you look here on this taxonomy page
The menu is gone, there are other queries that aren't firing but I'm focussing on this as a primary issue.

I have generated output from nav-menu-template.php like so:

    if ( $menu && !is_wp_error($menu) && !isset($menu_items) )
{
    write_log($menu);
    $menu_items = wp_get_nav_menu_items( $menu->term_id, array( 'update_post_term_cache' => false ) );
    write_log($menu_items);
}

and I get this:

[31-Aug-2017 15:27:52 UTC] WP_Term Object
(
    [term_id] => 2
    [name] => Header Menu
    [slug] => header-menu
    [term_group] => 0
    [term_taxonomy_id] => 2
    [taxonomy] => nav_menu
    [description] => 
    [parent] => 0
    [count] => 6
    [filter] => raw
)

[31-Aug-2017 15:27:52 UTC] Array
(
)

[31-Aug-2017 15:27:52 UTC] WP_Term Object
(
    [term_id] => 3
    [name] => Footer One
    [slug] => footer-one
    [term_group] => 0
    [term_taxonomy_id] => 3
    [taxonomy] => nav_menu
    [description] => 
    [parent] => 0
    [count] => 5
    [filter] => raw
)

[31-Aug-2017 15:27:52 UTC] Array
(
)

So it sees the menu but for some reason return no items in either menu.
I have turned off all plugins and still get the same result, I have also eliminated all other queries on this page to see if there was conflict and this still this happens.

Any insight on this one would be great not sure where to look next for issues.



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Reversing an array without 'reverse' or duplicating an array

user7496931:

I'm trying to solve the following exercise:

Reverse an array without using the reverse method, without using a second array, and without duplicating any of the values.

I've thought about making the array an object and then updating the array from the end to the beginning but I figured you can just update it as well.

Tried something simple like:

function reverseArray(array) {
  for (var i = 0; i < array.length; i++) {
    // var elem = array.shift();
    var elem = array.shift()
    array.push(elem)
  }
  return array
}

array = ['a', 'b','c','d','e'];

reverseArray(array);

But that doesn't really change it. Any advice or explanation on how to do this?



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Setting focus to a DataGridView row

anonymous:

The following source code is intended to set focus to the immediately previous row of a deleted row.

enter image description here

I have two concerns:

  1. How can I increase the efficiency of this code? I.e. can I reduce the number of loops?
  2. Suppose I want to delete an unwanted word dddddddd from the database. When I press the Delete button, I want the word cynosure to be focused and placed at the top of the DataGridView which is not the case right now.

enter image description here

Right now, it is displayed at the bottom.

enter image description here

Source Code

    void SetFocusToWord(Word concernedWord)
    {
        if (concernedWord != null)
        {
            int index = 0;
            foreach (DataGridViewRow r in dataGridView1.Rows)
            {
                Word item = r.Tag as Word;

                if (concernedWord.Name == item.Name)
                {
                    dataGridView1.Focus();
                    dataGridView1.CurrentCell = dataGridView1.Rows[index].Cells[0];

                    break;
                }

                index++;
            }
        }
    } 

private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView1.SelectedRows.Count > 0)
                {
                    int selectionIndex = dataGridView1.SelectedRows[0].Index;

                    foreach (DataGridViewRow r in dataGridView1.SelectedRows)
                    {
                        Word c = r.Tag as Word;

                        if (c != null)
                        {
                            _wordDatabase.Delete(c);
                        }
                    }

                    LoadToDataGridView();

                    if(selectionIndex > 0)
                    {
                        selectionIndex = selectionIndex - 1;
                    }

                    Word item = dataGridView1.Rows[selectionIndex].Tag as Word;

                    SetFocusToWord(item);
                }
                else
                {
                    throw new Exception(SelectionErrorMessages.GetErrorMessageFor(typeof(Word)));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        } 

    void LoadToDataGridView()
    {
        dataGridView1.Rows.Clear();

        List<Word> items = (List<Word>)_wordDatabase.Get();

        if (items != null)
        {
            if (items.Count > 0)
            {
                int i = 0;
                foreach (Word c in items)
                {
                    dataGridView1.Rows.Add(c.Name, c.Hint);
                    dataGridView1.Rows[i].Tag = c;
                    ++i;
                }
            }
        }
    } 



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: How to access a member of a class "statically" in kotlin?

the_new_mr:

In Java and Android, we can do this:

public static MyApplication extends Application {
   private static Context appContext;

   public static Context getAppContext() {
      return appContext;
   }
}

so that, somewhere else, we can do this:

appContext = MyApplication.getAppContext();

How do we do this in Kotlin? I've been going round in circles for the past hour or so.

Thanks in advance.



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Regex Character Class [-/] works but [/-] does not

Anand Rayudu:
  1. Please explain as to why the first character class is working, but not the second one

This does work :

p = re.compile("\d\d[.-/ ]\d\d[.-/ ]\d\d\d\d")`

This does not work :

p = re.compile("\d\d[./- ]\d\d[./- ]\d\d\d\d")

Traceback (most recent call last):

  File "C:/pyprg/prac01.py", line 2, in <module>
        p = re.compile("\d\d[./- ]\d\d[./- ]\d\d\d\d")   File "C:\Python361\lib\re.py", line 233, in compile
        return _compile(pattern, flags)   File "C:\Python361\lib\re.py", line 301, in _compile
        p = sre_compile.compile(pattern, flags)   File "C:\Python361\lib\sre_compile.py", line 562, in compile
        p = sre_parse.parse(p, flags)   File "C:\Python361\lib\sre_parse.py", line 856, in parse
        p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, False)   File "C:\Python361\lib\sre_parse.py", line 415, in _parse_sub
        itemsappend(_parse(source, state, verbose))   File "C:\Python361\lib\sre_parse.py", line 552, in _parse
        raise source.error(msg, len(this) + 1 + len(that)) sre_constants.error: bad character range /-  at position 6



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Detect when user locks/unlocks screen in Windows 7 with Delphi [duplicate]

Alisson:

This question already has an answer here:

How to detect when the user locks/unlocks the screen in Windows 7?

I found this question which has an answer for C#, but I'd like to use it in Delphi 2009. I'd guess there is some windows message (like these) which could do the work. This is the code I tried, but it didn't work:

const
  NOTIFY_FOR_ALL_SESSIONS = 1;
  {$EXTERNALSYM NOTIFY_FOR_ALL_SESSIONS}
  NOTIFY_FOR_THIS_SESSION = 0;
  {$EXTERNALSYM NOTIFY_FOR_THIS_SESSION}

type

TfrmAlisson = class(TForm)
  lbl2: TLabel;
  procedure FormCreate(Sender: TObject);
  procedure FormDestroy(Sender: TObject);
public
  FLockedCount: Integer;
  procedure WndProc(var Message: TMessage); override;
  function WTSRegisterSessionNotification(hWnd: HWND; dwFlags: DWORD): bool; stdcall;
  function WTSUnRegisterSessionNotification(hWND: HWND): bool; stdcall;
end;

implementation

uses
  // my impl uses here

procedure TfrmAlisson.FormCreate(Sender: TObject);
begin
  if (WTSRegisterSessionNotification(Handle, NOTIFY_FOR_THIS_SESSION)) then
    ShowMessage('Nice')
  else
  begin
    lastError := GetLastError;
    ShowMessage(SysErrorMessage(lastError));
  end;
end;

procedure TfrmAlisson.FormDestroy(Sender: TObject);
begin
  WTSUnRegisterSessionNotification(Handle);
end;

procedure TfrmAlisson.WndProc(var Message: TMessage);
begin
  case Message.Msg of
    WM_WTSSESSION_CHANGE:
      begin
        if Message.wParam = WTS_SESSION_LOCK then
        begin
          Inc(FLockedCount);
        end;
        if Message.wParam = WTS_SESSION_UNLOCK then
        begin
          lbl2.Caption := 'Session was locked ' +
          IntToStr(FLockedCount) + ' times.';
        end;
      end;
  end;
  inherited;
end;

function TfrmAlisson.WTSRegisterSessionNotification(hWnd: HWND; dwFlags: DWORD): bool;
  external 'wtsapi32.dll' Name 'WTSRegisterSessionNotification';

function TfrmAlisson.WTSUnRegisterSessionNotification(hWND: HWND): bool;
  external 'wtsapi32.dll' Name 'WTSUnRegisterSessionNotification';

When FormCreate executes, WTSRegisterSessionNotification returns false and the last OS error returns Invalid Parameter.



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Outlook - Open Reply All window when specific email is received

Evan:

I am trying to create a script to open the Reply All window automatically when a specific email is received. Also for it to include specific text in the body. I don't want the email to send i just want the window to open.

I have tried the following:

Option Explicit
Sub ReplyMSG()
Dim olItem As Outlook.MailItem
Dim olReply As MailItem ' Reply

For Each olItem In Application.ActiveExplorer.Selection
Set olReply = olItem.ReplyAll
        olReply.HTMLBody = "TEXT " & vbCrLf & olReply.HTMLBody
    olReply.Display

    'olReply.Send
Next olItem
End Sub

This will Open the email that is selected in the inbox rather than the email that was just received.

Thanks in Advance!

Evan



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Change component properties using SetPropValue() and RTTI with Delphi Tokyo

Anderson:

I am using the code below to set the properties using RTTI with Delphi 10.2 Tokyo in components created at runtime, everything works correctly because the property of the example is the TypeLine, because I can access it directly.

Componente_cc Is a variable that can be instantiated with any class, be it TLabel, TButton, TEdit... or any other. In the case below I'm instantiating it as being a TLine.

Var 
    Componente_cc: TControl;

    procedure TfrmPrincipal.AlteraPropriedades;
    begin
        if IsPublishedProp(Componente_cc, 'LineType') then
          SetPropValue(Componente_cc, 'LineType', 'Diagonal');
    end; 

However, I did not understand how to do when there is a sub-property, such as Stroke, it has Kind, Color, Cap, Dash, among others. How to change the values of these properties by using the SetPropValue() function. I have simplified the example code for a better understanding, but in the general context of my system I will need to use RTTI, of course changing the properties directly by the code would be simple, but I do need RTTI.



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Matrix Rotation Around an Arbitrary Axis Bug

Travis Pettry:

I have been attempting to get matrix rotation around an arbitrary axis working, I think I'm close but I have a bug. I am relatively new to 3D rotations and have a basic understanding of what is going on.

public static Matrix4D Rotate(Vector3D u, Vector3D v)
{
    double angle = Acos(u.Dot(v));
    Vector3D axis = u.Cross(v);

    double c = Cos(angle);
    double s = Sin(angle);
    double t = 1 - c;

    return  new Matrix4D(new double [,]
    {
        { c + Pow(axis.X, 2) * t,  axis.X * axis.Y * t -axis.Z * s, axis.X * axis.Z * t + axis.Y * s, 0 },
        { axis.Y * axis.X * t + axis.Z * s, c + Pow(axis.Y, 2) * t, axis.Y * axis.Z * t - axis.X * s, 0 },
        { axis.Z * axis.X * t - axis.Y * s, axis.Z * axis.Y * t + axis.X * s, c + Pow(axis.Z, 2) * t, 0 },
        { 0, 0, 0, 1 }
    });
}

The above code is the algorithm for the matrix rotation. When I test the algorithm with unit vectors I get the following:

Matrix4D rotationMatrix = Matrix4D.Rotate(new Vector3D(1, 0, 0), new Vector3D(0, 0, 1));

Vector4D vectorToRotate = new Vector4D(1,0,0,0);

Vector4D result = rotationMatrix * vectorToRotate;

//Result
X = 0.0000000000000000612;
Y = 0;
Z = 1;
Length = 1;

With a 90 degree rotation I find it works almost perfectly. Now lets look at a 45 degree rotation:

Matrix4D rotationMatrix = Matrix4D.Rotate(new Vector3D(1, 0, 0), new Vector3D(1, 0, 1).Normalize());

Vector4D vectorToRotate = new Vector4D(1,0,0,0);

Vector4D result = rotationMatrix * vectorToRotate;

//Result
X = .70710678118654746;
Y = 0;
Z = .5;
Length = 0.8660254037844386;

When we take the atan(.5/.707) we find that we have a 35.28 degree rotation instead of a 45 degree rotation. Also the length of the vector is changing from 1 to .866. Does anyone have any tips on what I am doing wrong?



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Windows service calling WebGet method returns 400 error

kristech:

I have a service that runs a c# method to sync a database with active directory at a specified interval. This code has worked in a test environment and now putting it on a different server it is returning the following message:

The server encountered an error processing the request. Please see the service help page for constructing valid requests to the service.

The help page looks like this:

enter image description here

But the "SyncActiveDirectory" URI is giving me this error:

enter image description here

This is a new server. Maybe i am missing something that needs to be installed or a setting in IIS? Any help would be much appreciated.

EDIT: Here is the method that called the webget:

private void SyncActiveDirectoryServiceCall()
        {
            WriteIntoLogFile("Start _schedulerService.SyncActiveDirectoryServiceCall()");

            try
            {
                var reader = new AppSettingsReader();
                var serviceurl = reader.GetValue("ServiceUrl", typeof(string));
                var client = new RestSharp.RestClient(serviceurl.ToString());
                var request = new RestSharp.RestRequest("SyncActiveDirectory", RestSharp.Method.GET);
                var response = client.Execute(request);
                WriteIntoLogFile(response.Content);
            }
            catch (WebException ex)
            {
                using (WebResponse response = ex.Response)
                {
                    HttpWebResponse httpResponse = (HttpWebResponse)response;

                    WriteIntoLogFile("Error code: " + httpResponse.StatusCode);

                    using (Stream data = response.GetResponseStream())
                    using (var reader = new StreamReader(data))
                    {
                        string text = reader.ReadToEnd();
                        WriteIntoLogFile("STREAMED: " + text);
                    }
                }
                WriteIntoLogFile("TRY-CATCH: " + ex.ToString());
            }
            WriteIntoLogFile("End _schedulerService.SyncActiveDirectoryServiceCall()");

        }

And here is the method being called:

namespace SyncActiveDirectory
{
    public class SyncLocalWithLDAP : ISyncLocalWithLDAP
    {
        private List<GenericUser> users { get; set; }
        private List<GenericUser> roles { get; set; }
        [WebGet(UriTemplate = "SyncActiveDirectory")]
        public void SyncActiveDirectory()
        {
            string constr = GetConnectionStringValue("ProteusMMXCustomerDB");
            string usr = GetAppsettingValue("ldap_login_username");
            string pss = GetAppsettingValue("ldap_login_password");
            string filePath = string.Empty;
            ActiveDirectoryWrapper wrapper = new ActiveDirectoryWrapper();
            if (!Directory.Exists(WebConfigurationManager.AppSettings["LogFolderPath"] + "ServiceLog"))
            {
                Directory.CreateDirectory(WebConfigurationManager.AppSettings["LogFolderPath"] + "ServiceLog");
            }
            if (!File.Exists(WebConfigurationManager.AppSettings["LogFolderPath"] + "ServiceLog" + "/" + "SyncLog.txt"))
            {
                File.Create(WebConfigurationManager.AppSettings["LogFolderPath"] + "ServiceLog" + "/" + "SyncLog.txt").Dispose();
            }

            filePath = WebConfigurationManager.AppSettings["LogFolderPath"] + "ServiceLog" + @"\" + "SyncLog.txt";

            using (StreamWriter w = File.AppendText(filePath))
            {
                Log("Constr - " + constr + " , u - " + usr + " p - " + pss, w);
                try
                {
                    Log("Start sync outer", w);
                    SyncLocalWithLDAP_Users_Roles(constr, usr, pss, w);
                    Log("End sync outer", w);
                }
                catch (Exception ex)
                {
                    Log("Error: " + ex.Message, w);
                }
            }
        }

EDIT: Pic of htm file added to that directory from within browser. enter image description here



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Read string from one file, grep the first occurrence in another file

Nandu:

I'm reading a string from file, appliances_list.txt.

appliances_list.txt contains

fridge
dryer
ironbox
microwave 

The file I'm reading is myappliances.txt. Content is

I have a <Appliance>fridge</Appliance>
I have another <Appliance>fridge</Appliance>
I have a <Appliance>refridgerator</Appliance>
I have a <Appliance>microwave</Appliance>
I have <Appliance>ironbox</Appliance> at home
I have another <Appliance>microwave</Appliance>
I have a <Appliance>hairdryer</Appliance>

I'm using

grep -o -m1 -f appliances_list.txt myappliances.txt

Output is

fridge

My desired output is, first occurrence of each string (exact match)

fridge
microwave
ironbox

Can someone point me in the right direction?



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: R shiny matrix or table input

Jian:

I am trying to find a way to create a matrix or table as input for user to interact with in R shiny. For example, a matrix like this

sample name             number of tests
350292                  3
...                     ...

Ultimately, I want to automatically generate tabs in the mainPanel for user to input data for these different samples.

One way I find is through matrixInput in the package shinyIncubator, but this is an unofficial package and matrixInput function does not offer an option of column names.

I am wondering if there is any better way to realize this in R shiny?

Update!!! I tried the rhandsontable package, and used the following code.

library(shiny)
library(rhandsontable)

DF <- data.frame(name=c(350292, 360765), run=c(3,2))
colnames(DF) <- c("sample name", "number of tests")

ui <- fluidPage(
  headerPanel("test"),
  mainPanel(rHandsontableOutput("sample"))
)

server <- function(input, output) {
  output$sample <- renderRHandsontable({
    rhandsontable(DF, rowHeaders = NULL) %>%
     hot_col(c("sample name", "number of tests"), format = "0")
  })
}

shinyApp(ui = ui, server = server)

But how to call values in the reactive rhandsontable? Eventually I want to be able to create tabs based on sample name and test number. In this case, it would be 350292_1, 350292_2, 350292_3, 360765_1, 360765_2.



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: how can i add information to my databse in android?

Hossein Mobini:

i was writing a program about movies and i needed to create a database. so i did it . and after running the app when i wanted to add a movie to my list nothing happend . here is my code :

@Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_rigister_series);
    setTitle("Register series");
    Button btnsubmit;
    final EditText moviename,movieyear,moviegenre,directername;
    TextView textViewcount;
    final database_manager db = new database_manager(this);
    int result=db.getmoviecount();
    moviename=(EditText)findViewById(R.id.moviename);
    movieyear=(EditText)findViewById(R.id.movieyear);
    moviegenre=(EditText)findViewById(R.id.moviegenere);
    directername=(EditText)findViewById(R.id.directername);
    textViewcount=(TextView)findViewById(R.id.textViewcount);
    textViewcount.setText(Integer.toString(result));
    btnsubmit=(Button)findViewById(R.id.btnsubmit);
    btnsubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          String Name=moviename.getText().toString();
            String Genre=moviegenre.getText().toString();
            int Year = Integer.parseInt(movieyear.getText().toString());
            String Directername=directername.getText().toString();
            movies_item movieslist=new movies_item();
            movieslist.movie_name=Name;
            movieslist.movie_year=Year;
            movieslist.movie_genre=Genre;
            movieslist.directer_name=Directername;
            Boolean result= db.addmovie(movieslist);
            if(result){
                toastshow();
            }else


Toast.makeText(getApplicationContext(),"Failed!",Toast.LENGTH_SHORT).show();

        }
    });
}

 private void toastshow() {
    Context context= getApplicationContext();
    LayoutInflater layoutinfalter= getLayoutInflater();
    View view= layoutinfalter.inflate(R.layout.custom_toast,null);
    Toast toast = new Toast(context);
    toast.setView(view);
    toast.setGravity(Gravity.CENTER_HORIZONTAL,0,0);
    toast.setDuration(Toast.LENGTH_LONG);
    toast.show();

}

and also my database manager :

 public database_manager(Context context) {
    super(context,"mydb" , null,1);

}

@Override
public void onCreate(SQLiteDatabase db) {
    String query= " CREATE TABLE tbl_movies (" +
    "  id     INT    PRIMARY   KEY     AUTOINCREMENT   " +
                      "    NOT    NULL    " +
                      "   UNIQUE  ,  " +

    "  name              VARCHAR   NOT   NULL   " +
                       "   UNIQUE  ,  " +
    "  year               NUMERIC   ,   " +
    "  genre              VARCHAR   ,  "  +
    "  directer   VARCHAR    " +
    "  );  ";

          db.execSQL(query);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
     db.execSQL("DROP TABLE IF EXISTS tbl_movies");
    onCreate(db);
}

public List<movies_item> getmoviesitem(){

    List<movies_item> List_movies=new ArrayList<movies_item>();
    String query="SELECT
 movie_id,movie_name,directer_name,movie_year,movie_genre FROM tbl_Hesab";  
    SQLiteDatabase db=this.getReadableDatabase();
    Cursor cursor=db.rawQuery(query, null);
    while(cursor.moveToNext()==true){
        movies_item h= new movies_item();
        h.movie_id=cursor.getInt(0);
        h.movie_name=cursor.getString(1);
        h.movie_year=cursor.getInt(2);
        h.movie_genre=cursor.getString(3);
        h.directer_name=cursor.getString(4);

        List_movies.add(h);
    }
    return List_movies;
}


public boolean addmovie (String movie_name,int movie_year, String 
 movie_genre, String directer_name){
     boolean result;
    String query="INSERT INTO tbl_movies(name,year,genre,directer ) " +
            " VALUES   
 ('"+movie_name+"',"+movie_year+",'"+movie_genre+"','"+directer_name+"') ";
    try {

        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL(query);
        db.close();
        result=true;
    }
     catch (Exception ex){
         result=false;

     }
    return result;
}
public boolean updatemovie(movies_item moviesItem){
    boolean result;
    try {
        String query="UPDATE tbl_movies SET name='"+ movie_name+"',year="+  
 movie_year+",genre='"+ movie_genre+"',directer ='"+ directer_name+"'"+
                "where id="+ movie_id+"";
        SQLiteDatabase db=this.getWritableDatabase();
        db.execSQL(query);
        db.close();
        result=true;
    }
    catch (Exception ex){
        result=false;
    }
  return result;

}
public movies_item getmovie(int movie_id) {
movies_item movies_item= new movies_item();
    String query= "SELECT * FROM tbl_movies  WHERE id="+ movie_id;
    SQLiteDatabase db=this.getReadableDatabase();
    Cursor cursor=db.rawQuery(query,null);
    if (cursor.moveToFirst()==true){
        movie_name=cursor.getString(1);
        movie_year=cursor.getInt(2);
        movie_genre=cursor.getString(3);
        directer_name=cursor.getString(4);
    }
    return  movies_item;

}
public int getmoviecount (){
    int result=0;
    String query ="SELECT * FROM tbl_movies ";
    SQLiteDatabase db=this.getReadableDatabase();
    Cursor cursor = db.rawQuery(query,null);
    result=cursor.getCount();
    db.close();
    return  result;
}

 public boolean deletemovie(){
 boolean result;
 try {
    String query= "DELETE FROM tbl_movies WHERE id="+movie_id;
    SQLiteDatabase db= this.getWritableDatabase();
    db.execSQL(query);
    db.close();
    result=true;
}
catch (Exception ex){
    result=false;
}
 return  result;

}

public Boolean addmovie(movies_item moviesItem) {
    boolean result;
    try {
        String query = "INSERT INTO tbl_movies(name,year,genre,directer ) " +
                " VALUES ('" + movies_item.movie_name + "',"   
 +movies_item.movie_year + ",'" + movies_item.movie_genre + "','" 
 +movies_item.directer_name + "') ";
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL(query);
        db.close();
        result = true;
    } catch (Exception ex) {
        result = false;

    }
    return result;
  }
}

i just keep receving the failed message which means nothing happens. can anyone help me with that ?



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Add a return value to a closure

J.Doe:

I'm not very familiar with closure. I'm using this function to download a JSON file from a remote server

requestJson(){
    // Asynchronous Http call to your api url, using NSURLSession:
    NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: "http://ift.tt/2iLY40z")!, completionHandler: { (data, response, error) -> Void in
        // Check if data was received successfully
        if error == nil && data != nil {
            do {
                // Convert NSData to Dictionary where keys are of type String, and values are of any type
                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]
                // Access specific key with value of type String
                let str = json["key"] as! String
            } catch {
                // Something went wrong
            }
        }
    }).resume()
}

Is it possible to make the function requestJson() return the JSON file when its loaded? Or it's not possible because it's loaded asynchronously and could not be ready? Want I'm trying to do is something like following:

requestJson() -> **[String : AnyObject]**{
    // Asynchronous Http call to your api url, using NSURLSession:
    NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: "http://ift.tt/2iLY40z")!, completionHandler: { (data, response, error) -> Void in
        // Check if data was received successfully
        if error == nil && data != nil {
            do {
                // Convert NSData to Dictionary where keys are of type String, and values are of any type
                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! [String:AnyObject]
                // Access specific key with value of type String
                **return json**
            } catch {
                // Something went wrong
            }
        }
    }).resume()
}



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Using local json file to lookup key:value using javascript

user3294636:

I have a state-abbreviation json file from here. In my .js file, I have var=state that I want to look up the abbreviation for. So I need help in finding how to do that. For example lookup state (=Maine) in the json to get the "ME" value. Please help! Newbie in javascript so please please be as basic as possible in your answer. Thanks

Update So my json is fine. Here is a sample from it...

[{"Alabama": "AL","Alaska": "AK","American Samoa": "AS",.....})

In my .js file, I am 'trying' to get the json file and use it for lookup like so. Obviously this isn't working. I know there are many mistakes so please be nice when helping out. Remember I am a newbie. ;-)

$.getJSON("/files/json/states_hash.json", function(json){
var data = eval("(" + json.responseText +")");
var val=_.findValue(json, stateNameVar);
console.log(json);
});



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: How to read Json from URL

Vincent N.:

I'm trying to read json from this url

http://ift.tt/2iLY5BF

using the code snippet

     using (var httpClient = new HttpClient())
        {
            var json = await httpClient.GetStringAsync(apiurl);

        }

when the execution hits var json = await .... I get an exception

    System.Net.Http.HttpRequestException: 'Response status code does not
    indicate success: 403 (Forbidden).'

I suspect this may be because when I navigate to the url in my browser I have to first pass captcha to view the data.

Any Ideas on a workaround?



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Is there a way to actually write a fade-out to a wav file using NAudio?

Ahmed Abdelhameed:

I'm using NAudio to convert & trim some audio files, and I'm trying to add a fade-out to the last few seconds of each file.

I have checked this question, this, and this, but all the answers are talking about playing the wav file with fade, while I need to actually write that fade to an output file.

So, is there any way to do this using NAudio? If not, I'm open to other suggestions.


Edit: This is what I've tried:

private void PerformFadeOut(string inputPath, string outputPath)
{
    WaveFileReader waveSource = new WaveFileReader(inputPath);

    ISampleProvider sampleSource = waveSource.ToSampleProvider();

    OffsetSampleProvider fadeOutSource = new OffsetSampleProvider(sampleSource);
    // Assume the length of the audio file is 122 seconds.
    fadeOutSource.SkipOver = TimeSpan.FromSeconds(120);   // Hard-coded values for brevity

    // Two seconds fade
    var fadeOut = new FadeInOutSampleProvider(fadeOutSource);
    fadeOut.BeginFadeOut(2000);

    Player = new WaveOut();

    Player.Init(fadeOut);
    Player.Play();    
}

When I play the audio after applying the fade using Player.Play() -as shown in the method above-, it works perfectly as expected, and I can hear the fade. Now, I would like to export this result to an output WAV file.

I tried doing that by adding the following line:

WaveFileWriter.CreateWaveFile(outputPath, waveSource);

However, the output file doesn't have any fade applied to it. So, what am I missing here?



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

Sony Equips the Xperia XZ1 with 3D Scanning and Image Creation Software ★★ XDA DEVLOPERS FORUM ★★

Sony is in Berlin this week for the big IFA 2017 conference and they’re announcing a number of new devices there. We reported on their two new flagship devices earlier this month that were leaked before the unveiling, and they have also launched a new connected speaker with support for Google Assistant. Now that these two flagship smartphones are official, we get a look at some of their software features and one in particular that stands out is what they’re calling the Xperia XZ1 3D Creator.

Augmented reality is becoming more and more popular these days with companies such as Google working on them for years. Google’s previous work required special hardware for AR to work the way they wanted it, but even their new ARCore platform eliminates this requirement. It looks like Sony is jumping into this market as well with a piece of software called 3D Creator for their new Xperia XZ1 flagship smartphone. They’re even taking it a step further though and using this 3D capturing technology for more than just AR, though.

The process starts by launching the application and then using it to capture a full 360 degree scan of the object. If you want, you can do this with your head and then use it with one of their pre-built avatar figures. This can then be placed virtually in the room you’re in, or you can use it with popular chat applications (they used WhatsApp as an example) as a 3D Sticker. You can capture other 3D objects as well, such as a conch shell, and then put then virtually place that captured object anywhere else.

The 3D Creator software for the Xperia XZ1 even lets you use these objects for 3D printing as well. Sony says it should only take between 15 to 60 seconds to scan an object, and the software comes with four different modes including face, head, freeform and food.


Source: Sony Mobile



from xda-developers By Doug Lynch

READ FULL ARTICLE

Share:

Mod to Customize the UI of your Google Pixel running Android Oreo ★★ XDA DEVLOPERS FORUM ★★

With the Android Oreo OTA update rolling out to the Google Pixel phones, some are looking for ways to customize the user interface of their device. So XDA Senior Member Tulsadiver has put together a collection of mods that lets you pick and choose which mods you want to install through an Aroma installer.

Some of the included mods let you change things such as the navigation bar height, status bar icon colors, clock positions and more. The developer does note that not all of the mods have been tested, so you should create a backup ahead of time. To install this mod, your Google Pixel needs to have an unlocked bootloader and has to have a custom recovery such as TWRP installed.


Check out this UI mod in our Pixel forum



from xda-developers By Doug Lynch

READ FULL ARTICLE

Share:

New Commnt: ★★Re: Sony Announces Which Devices They’re Updating to Android Oreo ★★

Z3 & Z4 have reached their 2 year update lifecycle



from XDA-Developers - Latest Comments by Caitlin550
Read More
Share:

New Commnt: ★★Re: Andy Rubin Apologizes for Customer Service Issues, Offers Affected Customers a Free Phone and More ★★

Essential is getting more bad publicity than OnePlus got with the 5, and that was at least their marketing strategy...



from XDA-Developers - Latest Comments by Omar
Read More
Share:

New Commnt: ★★Re: LG V30 Announced at IFA 2017 – Snapdragon 835, 6.0 inch 2:1 QHD Display, 3,300mAh Battery and More! ★★

Ditto.
Honestly I'm scared for the future of custom ROMs. Gone are the days when you could buy almost any phone and KNOW it'll have custom ROM support. Look at the LG V10: wasted! (OEMs simply don't care much for us DIYs)
Now, choices are either remain stock or put up with buggy/handicapped ROMs.
So sad.



from XDA-Developers - Latest Comments by MaverickNextDoor
Read More
Share:

SOLVED: VSTS Role to change the backlog item status

John Bull:

Colleagues, Is there any way in VSTS I can only allow the project owner to change the backlog item status to "Approved" for instance? On the dashboard, I also implemented a custom step called "Resolved", assuming that once user story/feature is done, only QA can move it further to "Done" (after relevant testing). Is it possible to restrict the access to QA guy only (I mean the status change from "Resolved" to "Done")? Am I asking too much? :)



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Stop all Flow Servers

Quang Van:

Sometimes it seems like Flow isn't working right and flow stop; flow start seems to fix the problem. Is there a command to stop (or restart) all Flow servers? like flow stop --all

Thanks!



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: angular 2 formControlName directive

ankur ratra:

I have a scenario where i have a custom directive on the input element which listens on the focus event on that input and store that elementRef in one service.

<md-input-container>
        <textarea mdInput formControlName="content"
                  [readonly]="!editable" mdTextareaAutosize 
                  inniNativeInputFocusDirective> 
        </textarea>

Basically i want to track the last focused input element.

Now i have another sidebar showing the list of items. Now when i click on that item then the last focused input element value should be appended with the item value.

now in my component when i update the value like this.

this.renderer.setProperty(this.lastFocusedElementRef.nativeElement, 'value', newValue);

but with this the form model is not updated. formControlName directive is not updating the model from the input value.



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Not able to select subscription ID in azure

techie:

I am using below code to select subscription id in Power shell script, but when i click on the subscription id it does not select...

$subscriptionId = (Get-AzureRmSubscription | Out-GridView -Title 'Select Azure Subscription:' -PassThru).SubscriptionId Select-AzureRmSubscription -SubscriptionId $subscriptionId



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Javafx how to give a fixed width to Gridpane

loUIS CK:

I have got this gridPane in my code and i want to give it a fixed width of 800,i tried setting style like this

    grid.setStyle("width: 400px;");

But it didn't work.



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Inital Data Load Unauthenticated Firebase

Ryan Temple:

So I have an iOS app that is using Firebase as a backend service. When my app initially launches (before the user signs up) I want to pull a list of all the "Schools" available to use.

/Schools is the path where all the schools will be.

{
 "rules": {
   ".read": "auth != null",
   ".write": "auth != null",
  }
}

Currently I only have default rules in place. What rules should I apply so that an unauthenticated user can read from /Schools and not .write?

Thanks!



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Select table NAME with a selected data

Lloyd:

I wanted to try something, which is to select a table NAME with a selected data. I wanted to do something like that,lets say I have 3 Tables: account,info,products. Each of them have 2 cols (id and name). And these are the data inside each table:

Table (account):
id=1
name=yourname

Table (info):
id=1
name=yourname

Table (product):
id=1
name=myname

And now,i wanted to know the table or tables with Column name=yourname.



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: super function called inside a method in python 2

ps3790:

I was trying my hands on super function, below is the code i was executing.

class scene(object):
    def enter(self):
        print "a vllan s n your way. what you'll do?"

class centralcorrdor(scene):
    print "startng pont of the game."
    super(centralcorrdor,self).enter()


a = centralcorrdor()

however this gives error.

class centralcorrdor(scene):
File "game.py", line 8, in centralcorrdor
super(centralcorrdor,self).enter()

NameError: name 'centralcorrdor' is not defined

And this does not.

class scene(object):
    def enter(self):
        print "a vllan s n your way. what you'll do?"

class centralcorrdor(scene):
    #print "startng pont of the game."
    def func(self):
        super(centralcorrdor,self).enter()
    #scene.enter()

a = centralcorrdor()
a.func()

Can someone tell why? Is it that super has be called from inside a method in child class?



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Why a separate function works with Must property rather than write the entire expression in it? (FluentValidation)

hmota:

I am a newbie with Linq and fluent validation and I want to know.. Why with the method 1 I get an error but with the method 2 it works without any issue?.

This way doesn't work!! throws a null reference exception.

 RuleFor(x => x)
        .Must(ledger => !_companyDbContext.GeneralLedger.Any(x =>
            x.Deleted == false
            && !(x.Id == ledger.Id)
            && x.AccountNumber == ledger.AccountNumber
            &&  x.LedgerAccount == ledger.LedgerAccount
            && x.AccountType == ledger.AccountType 
            &&  x.Description == ledger.Description
            )).WithMessage(ValidatorResources.Unique_Message);

This way works even if all the properties of the object are null.

    RuleFor(x => x)
        .Must(testDuplicateRecords)
        .WithMessage("duplicated record");

public bool testDuplicateRecords( GeneralLedger ledger)
{
    Expression<Func<GeneralLedger, bool>> predicate = (x) => x.Deleted == false && !(x.Id == ledger.Id)
        && x.AccountNumber == ledger.AccountNumber
        && x.LedgerAccount == ledger.LedgerAccount
        && x.AccountType == ledger.AccountType
        && x.Description == ledger.Description;


    return !_companyDbContext.GeneralLedger.Any(predicate.Compile());

}



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Python - Pass Arguments to setup file

Sam:

I have a setup file that creates an executable using py2exe. To run the setup file I enter

python setup.py py2exe.

I would like to pass versioning information so that the executable generated will be created in a specialized directory with the version, as well as set up versioning metadata.

I tried using argparse but that seems to override the setup.py parameters.

Is there a way to pass additional parameters to setup.py elegantly; preferably with flags? python setup.pu py2exe -v [VERSION]

I know I can parse the command in python but I would like to be able to specify flags if possible...



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: trouble with nested data structure in c++

cateof:

Using http://ift.tt/1D7fWFV I am trying to assign values to a recursive data structure (json_node_t).

#include <iostream>
#include <string>
#include <vector>
#include "json.hpp"

using namespace std;
using json = nlohmann::json;

struct json_node_t {
    int id;
    std::vector<json_node_t> children;
};

void to_json(json& j, const json_node_t& node) {
    j = ID;
    if (!node.children.empty())
        j.push_back({"children", node.children});
}

int main() {
    json_node_t node_0;         
    std::vector<int> values = {1,2,3};

    std::vector<json_node_t> parents;
    parents.resize(20);

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

        if ( i == 0 )
        {
            node_0.id = values[0];
            std::vector<json_node_t> node_children_;
            node_0.children = node_children_;
            parents[0] = node_0;   

        } else {

            json_node_t node_i;
            node_i.id = values[i];

            std::vector<json_node_t> node_i_children_;
            parents[i] = node_i;

            parents[i-1].children.push_back(node_i); 


        }

    }

    json j = node_0;

    cout << j.dump(2) << endl;
    return 0;
}

My purpose is to create a json representation like the following:

{
  "ID": 1,
  "children": [
    {
      "ID": 2
    },
    {
      "ID": 3,
      "children": []

    }
  ]
}

however the nested children are not getting printed. I only get this output

{
  "ID": 1
}

What is wrong? I cannot connect the child to his parent correct.



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Python: Triple Double Quote String format

user1187968:

I'm getting the following error, how should I fix it?

KeyError: 'a' Process finished with exit code 1

s = """
a b c {a}
""".format({'a':'123'})

print s



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Automatically run a PHP script every time a user change a row in MySQL/WordPress database

Matto:

I'm building a small web app to feed one website from a row of a database in another website (a WordPress based website).

Essentially I have three files: one called outputjson.php that will generate a json file called results.json (that live in my WordPress website) and in another website I will ajax that file in order to display an announcers section for a radio station (with pictures of the announcer, socials, time).

My problem is that I have to manually initiate the process but I would like to do it automatically, every time anyone will update my database, I want that my file will listen to the event and run the php script.

So far my code is:

outputjson.php

<?php
global $wpdb;
if(!isset($wpdb))
{
    require_once('wp-config.php');
    require_once('wp-includes/wp-db.php');
}
$result = $wpdb->get_results ( "SELECT * FROM " . $table_prefix . "radio_announcer_on_air" );

$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($result, JSON_UNESCAPED_SLASHES));
fclose($fp);
?>

Which will generate a file like:

results.json

    [  
       {  
          "announcer_id":"19",
          "announcer_time_start":"07:00:00",
          "announcer_time_end":"08:59:59",
          "announcer_photo":"image.jpg",
          "announcer_name":"Name",
          "announcer_facebook":"",
          "announcer_twitter":"",
          "announcer_rss":"",
          "announcer_mail":"",
          "announcer_weekday":"7"
       }
]

My last file will live on another server and will make the magic:

announcers.js

$(function(){
    $.ajax({
      url: "http://ift.tt/2wlEZHs",
      type: "GET",
      dataType: "JSON",
      cache: false,
      success: function(markers) {
//Do something
}

Any suggestion? I could even consider running this script every day for example, since running it every time someone is gonna change my database row (the event) sounds very complicated, at least for my knowledge that I've got so far.



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Print message using SQL Server trigger

user8066749:

I have two dates in SQL Server - [O/R COMPLETE DATE] and [O/R SHIP BY]. I want to check if [O/R COMPLETE DATE] is later than [O/R SHIP BY] and if so, I want to display a message saying Overwrite shipBy date must be later than Overwrite Completed date.

Is it something possible?



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Xamarin - Is it possible to avoid ADK uses?

Emixam23:

I'm currently working on a project and I need to implement few features to be done, however, it's not possible and I need to be done as soon as possible.

I have a solution PCL (.NET 4.5, Profile=111) and for some reasons (that I don't understand from hours now), I can't install the following packages :

  • Stripe (The only one that can be installed is Stripe.net, but I can only install it on Android and iOS, not on the PCL part..)
  • Cloudinary (I tried all of them and... It's not compatible with .NET 4.5, Profile=111)

Do you have any idea or any work around to make it work? :/ I need stripe for payments and cloudinary for images hosting. It's already what the company is using so.. I have to adapt.

I was thinking about don't use any sdk and just do everything by myself, is it allowed/possible?

Thank for any help !



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: R - Update Columns in Very Large Sparse Matrix

Nate Thompson:

I need to update certain columns in a sparse matrix, but the operation is taking so insanely long to complete.

I have a sparse matrix with a little less than 3M rows and around 1500 columns. I also have a data frame with the same amount of rows, but only has 10 columns. I want to update certain column indices in the matrix with the values from the dataframe.

I have no problem doing this with a normal matrix, but when trying it with a sparse matrix it takes eons to do even a single column.

Below is the code that I am working with, what needs to be changed so that this can run efficiently?

library(Matrix)

x <- Matrix(0, nrow = 2678748, ncol = 1559, sparse = TRUE)
df <- data.frame(replicate(5,sample(0:1,2678748,rep = TRUE)))

var_nums <- sample(1:1559,size = 5)

for (i in 1:5){
  x[,var_nums[i]] <- df[,i]
}



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: Ansible changes variable values when set

Stiv Ostenberg:

I have a series of variables set. Call them Hosts and Inthosts. Each has an appropriate value set, as seen in the debug output. When I try to assign the value of inthosts to hosts, it does not actually make them the same, it bolloxes it up changing the double quotes to single quotes and putting a "u" in front of each "item". It there a way to force Ansible to actually do a literal equals in this case without parsing the text? The text should just be treated as a string. In this case the "modified" value is being output to a file, and the change breaks things. The plan was to use the default hosts, and override it with inthosts if the server in question should be using a different set of servers.

Default Variables Set

filebeat_kafka_hosts: '["x.compute-1.amazonaws.com:9093", "y.compute-1.amazonaws.com:9093"]'

filebeat_kafka_inthosts: '["x.compute-1.amazonaws.com:9093", "y.compute-1.amazonaws.com:9093", "z.compute-1.amazonaws.com:9093"]'

Ansible Code

  • debug: msg: "Hosts "

  • debug: msg: "IntHosts "

  • set_fact: filebeat_kafka_hosts=""

  • debug: msg: "Inthosts -> hosts "

Output (editted)

"msg": "Hosts [\"x.compute-1.amazonaws.com:9093\", \"y.compute-1.amazonaws.com:9093\"] " |

"msg": "IntHosts [\"x.compute-1.amazonaws.com:9093\", \"y.compute-1.amazonaws.com:9093\", \"z.compute-1.amazonaws.com:9093\"] "

set {"ansible_facts": {"filebeat_kafka_hosts": ["x.compute-1.amazonaws.com:9093", "y.compute-1.amazonaws.com:9093", "z.compute-1.amazonaws.com:9093"]}, "changed": false}

"msg": "Inthosts -> hosts [u'x.compute-1.amazonaws.com:9093', u'y.compute-1.amazonaws.com:9093', u'z.compute-1.amazonaws.com:9093'] "



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

SOLVED: C++: elegant "polymorphism" with STL types and custom types?

user8385554:

Let's say I have a custom implementation of std::vector named my_vector, and they have the same interface.

There are many functions that take std::vector (or its pointer/reference) as input. I want to make as little modification as possible to these functions, while allowing them to accept either std::vector or my_vector.

Replacing these functions with function templates is a way to go, but there seem to be a lot of change (and hence difficult to rollback), and they can't do type checking unless I use std::is_same to further complicate them. Function overloading is another alternative, but it entails duplicating the code, and is also difficult to rollback the change.

Question: can I design a wrapper type Vector for std::vector and my_vector, and let those functions accept Vector (or its pointer/reference) instead? But the problem with polymorphism is std::vector can't inherit a custom class.

Ideally, the code should similar to this (not required to be the same) :

Definition of function:

// void foo(std::vector<char> vec) {...} // old
void foo(Vector<char> vec) {...}  // new

Use the function:

std::vector<char> stdvec(5,'a');
my_vector<char> myvec(5,'a');
...

foo(stdvec);
foo(myvec);

Thanks!

PS1: accepting iterators instead of objects of containers is a good advice. However, there are some operations that cannot be achieved by iterators (like, push_back(), resize(), reserve()):

void foo(std::vector<char> &vec) {
    size_t so=vec.size();
    vec.reserve(sz*100);
    for (size_t i=sz; sz<sz*100;++sz) {...}
}

PS2: the container might not be std::vector - I am asking about using "polymorphism" on a STL type and a custom type with the same interface.

PS3: don't hesitate to write answers if you think it is not achievable.



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE
Share:

Recent