text:
Q: trying to get random line from text document (python) I'm new to python and was working on a discord bot with Discord.py. I was trying to make it so when you type %quote it would get a random line from a text file. but for some reason it skips the first line or two. maybe I'm getting the logic wrong? here's my code.
@commands.command()
    async def quote(self, ctx, Qnum='janfol91213sdf2uieh1あ2Ⅳ3sんksnaaksd'):
            i = 0
            if Qnum == 'janfol91213sdf2uieh1あ2Ⅳ3sんksnaaksd':
                f = open("cogs\Base\data\Quotes.txt")
                random_lines = random.choice(f.readlines())
                await ctx.send(random_lines)
            else:
                f = open("cogs\Base\data\Quotes.txt")
                for line in f:
                    if i == int(Qnum):
                        quote = f.readline()
                        f.close()
                        break
                    else:
                        i = i+1
                await ctx.channel.send(quote)
                f.close()

the random Qnum thing is for optional parameter or something

A: Assuming your txt file looks something like this:
quote1
quote2

you could read the txt file and split it with \n, like this:
import random
with open('file.txt', 'r') as f:
    read = f.read()
    array = read.split('\n')
    quote = random.choice(array)
await ctx.channel.send(quote)

to make sure it doesnt skip any lines, you can print the array with the quotes to the console, with print(array)


text:
Q: Loading protobuf format file into pig script using loadfunc pig UDF I have very little knowledge of pig. I have protobuf format data file. I need to load this file into a pig script. I need to write a LoadFunc UDF to load it. say function is Protobufloader().
my PIG script would be
A = LOAD 'abc_protobuf.dat' USING Protobufloader() as (name, phonenumber, email);

All i wish to know is How do i get the file input stream. Once i get hold of file input stream, i can parse the data from protobuf format to PIG tuple format.
PS: thanks in advance

A: Twitter's open source library elephant bird has many such loaders:
https://github.com/kevinweil/elephant-bird
You can use LzoProtobufB64LinePigLoader and LzoProtobufBlockPigLoader.
https://github.com/kevinweil/elephant-bird/tree/master/src/java/com/twitter/elephantbird/pig/load
To use it, you just need to do:
define ProtoLoader com.twitter.elephantbird.pig.load.LzoProtobufB64LineLoader('your.proto.class.name');
a = load '/your/file' using ProtoLoader;
b = foreach a generate
  field1, field2;

After loading, it will be automatically translated to pig tuples with proper schema.
However, they assume you write your data in serialized protobuffer and compressed by lzo.
They have corresponding writers as well, in package com.twitter.elephantbird.pig.store.
If your data format is a bit different, you can adapt their code to your custom loader.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to setup OpenCL SDK and link it to Qt C++ project I want to develop a Qt C++ application using OpenCL.
The problem is I don't know what do I need to install/download to use OpenCL in my project.
I am confused by many obsolete threads over the internet. I have downloaded the SDK repo from official Khronos page:
https://github.com/KhronosGroup/OpenCL-SDK
But there are no .lib nor .so files inside, only header files, so I cannot link the library to my project.
I am using Windows 10 and I have an AMD graphic card, but my goal is to develop an application which can be run on any dedicated/integrated GPU.
What is the approach to just make it work and start coding?

A: Once you have installed the graphics driver, you don't need to install anything else. To develop OpenCL code, you just need the OpenCL header files and the .lib file. You can get them either from here (they work for AMD as well, but only OpenCL 1.2) or from Khronos directly (you will have to compile the .lib yourself).


text:
Q: Why is Chrome loading my HTML in a "pre" tag? I have a very basic web page that I'm loading with an Arduino Server.  When I view the page on Safari, everything works fine and looks good when I use the inspector.  But when I load it on Chrome (version 39.0.2), it wraps all of my HTML in a "pre" tag which prevents my webpage from loading (I've attached screenshots showing the Inspector output).  It also moves all of my code out of the "head" tag and into the "body" tag.  First, here is my HTML :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

      <link href='http://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
      <link href='http://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>

              <link rel="stylesheet" type="text/css" href="home.css">

        <title>CANARI JR. | Home</title>

Now when I inspect my page,  I see this:

And it wraps around all my HTML and actually closes the tag outside of my body and html tag!
Anyone see what is going wrong here in Chrome?
Edit 1 - I am using an Arduino Ethernet Shield to host and load this page from an SD card.  (It works perfectly on Safari, so I'm thinking there's something in my code and not an issue with Arduino).
Edit 2 - I've attached screenshot of the Google Chrome Inspector (sorry - copy and pasting replaced a lot of the characters, so I went screenshot route
http://i.stack.imgur.com/d09k8.png
Edit 3 - Added "Network" Tab from Chrome Inspector http://i.stack.imgur.com/zL7L1.png

A: According to your sceenshots the page is delivered with the Content-type: text/plain header.
This leads chrome to display it in a pre tag as it assumes you want to view the HTML as text.
Your webserver needs to write a proper Content-type header.
An example of how to write headers using the arduino ethernet shield can be found here.
Contrary to the code linked above, you should determine the content-type dynamically, using something like the file extension. So that images are transferred with the correct content-type(for example image/jpg) aswell.

A: Add Dependency to your POM
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>


text:
Q: Threading in a Windows Service I've created an app which uses Observable Lists. I've made the ObservableList class threadsafe (I think) and it's working fine now in my application.
Now I'm trying to install my application as a service. This works fine as well, up untill the point something gets added to the list. I think the thread there just dies. I've got the following code:
/// <summary>
/// Creates a new empty ObservableList of the provided type.
/// </summary>
public ObservableList()
{
    //Assign the current Dispatcher (owner of the collection)
    _currentDispatcher = Dispatcher.CurrentDispatcher;
}

/// <summary>
/// Executes this action in the right thread
/// </summary>
///<param name="action">The action which should be executed</param>
private void DoDispatchedAction(Action action)
{
    if (_currentDispatcher.CheckAccess())
        action.Invoke();
    else
        _currentDispatcher.Invoke(DispatcherPriority.DataBind, action);
}

/// <summary>
/// Handles the event when a collection has changed.
/// </summary>
/// <param name="e"></param>
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
    DoDispatchedAction(() => base.OnCollectionChanged(e));
}

While debugging, I've seen the Collection.Add(object) being called. It starts the DoDispatchedAction function, and the last thing the debugger hits, is _currentDispatcher.Invoke(DispatcherPriority.DataBind, action);. After this, the application continues but the code after Collection.Add(object) doesn't get executed anymore. The code which initially added the item to an ObservableList doesn't continue neither. That's why I think the Thread dies or something like that.
When checking the action in the debugger, I found out that the following message was there:

ApartmentState = '_currentDispatcher.Thread.ApartmentState' threw an
  exception of type 'System.Threading.ThreadStateException'

How can I solve this problem? Am I even thinking in the right direction?

A: From what I understand, you have a core code that should run as a Windows service, and a WPF application that uses the same core code.
So basically you should have something like 3 projects in your solution:

*

*a core assembly that does some hardware-related job

*an executable that will be installed as a Windows service. This executable references the core assembly

*a WPF application that also references the core assembly

Dispatchers are helpful to marshall back an action to the UI thread. This is basically used to execute some code in the UI thread in WPF applications. For example, when you bind a collection to a DataGrid, the CollectionChanged event must be fired on the UI thread because it'll cause, thanks to the binding, the UI to be updated. And UI must be updated from the UI thread.
Your core assembly shouldn't have to deal with dispatchers as there is no UI to update. You could use simple Collection here, as you won't bind it to any UI component. Same for your Windows service executable.
For your WPF application, on the other hand, you could use an ObservableCollection binded on a UI component (DataGrid for example). Only in this assembly you'll have to ensure UI components are always updated from the UI thread (which means you need the Dispatcher for that).
So, a code example:
Core assembly:
public IEnumerable<SomeClass> GetHardwareInfo()
{
    return new List<SomeClass> { ... };
}

Windows Service executable:
internal static void Main(string[] args)
{
    ...
    var objs = new MyCoreInstance().GetHardwareInfo();
    ...
}

WPF application (let's say it's the ViewModel):
// Some UI component is binded to this collection that is obersvable
public ObservableCollection<SomeClass> MyCol
{
    get
    {
        return this.myCol;
    }

    set
    {
        if (this.myCol != value)
        {
            this.myCol = value;
            this.RaisePropertyChanged("MyCol");
        }
    }
}

public void UpdateList()
{
    var info = new MyCoreInstance().GetHardwareInfo();

    // Now, marshall back to the UI thread to update the collection
    Application.Current.Dispatcher.Invoke(() =>
        {
            this.MyCol = new ObservableCollection(info);
        });
}

A: As this is a hardware dependent service, this is a little bit different from the usual LOB-style application. The difference is: the changes which should trigger events come from the backend of the application, while the whole UI framework and service architecture is intended to be used so that the frontend asks for data which the backend provides.
You could bring the two together by creating some sort of "neutral ground" where they meet.
In the hardware handling component, I would have a background thread which runs continually or runs triggered by hardware interrupts, and updates its data structures with whatever data it collects from the hardware. Then, I would have a synchronized method which can create a consistent snapshot of the hardware data at the point of time when it is called.
In the WPF client, there would be a dispatcher timer which calls this method in set intervals and updates the ObservableCollections using the data snapshots. This is possible, because it would happen on the UI thread. Actually, if possible you should try to add and remove items from the ObservableCollections, not create new collection instances, unless the data in the collection changes completely from one call to the next.
The WCF client would only be a wrapper around the method which creates data snapshots: it would only send back such a snapshot when it is called.
The WPF client for the WCF service would work as the local WPF client, only it would call the service instead of the hardware library directly, and probably I'd choose a longer interval for the DispatcherTimer, in order to avoid excessive network traffic. You could further optimize this by returning a special code which means "nothing has changed", in order to avoid sending the same data several times, or have separate methods for asking whether data has changed and retrieving the changed data.


text:
Q: ksort doesn't seem to work echo '
'.print_r($listings,1).'
';

ksort($listings, SORT_NUMERIC);

echo '
'.print_r($listings,1).'
';

Output:
Array
(
    [quick-brown-fox] => Array
        (
            [0] => Quick-brown-fox
            [1] => quick-brown-fox
            [4] => general_thumbs/quick-brown-fox.jpg
            [2] => 320
            [3] => 240
        )

)

Array
(
    [quick-brown-fox] => Array
        (
            [0] => Quick-brown-fox
            [1] => quick-brown-fox
            [4] => general_thumbs/quick-brown-fox.jpg
            [2] => 320
            [3] => 240
        )

)

I tried foreach, but it won't affect the original array, and for won't work because the its a key, not an index. What should I do in that case?

A: You have nested array in this $listings array. To sort it, write it like this:
foreach($listings as $k => $a){
    ksort($a, SORT_NUMERIC);
    $listings[$k] = $a;
}

A: array_walk(
    $listings,
    function(&$value) {
        ksort($value, SORT_NUMERIC);
    }
);


text:
Q: Cinnamon CSD and Firefox = unnecessary border around Firefox window Cinnamon + Client Side Decorator + Firefox dev edition (60 beta) = unnecessary border around Firefox window - also after maximize window.
How change this?
The wine is Cinnamona? Firefox? Theme (I have a standard)?

A: Solution from forums.linuxmint.com:

Switching to Mint-Y window theme [...] removes the dark gray border.


text:
Q: Can not type anything in input field returned from a functional component to App.jsx in React.js Please do me a favour. What happen is that I am not able to type anything in the input fields
returned from a functional component to App.jsx in React.
I am trying to construct a user registration form which contains the fields of user's name,
email and phone number.
I returned three inputs of those like this;
import React, { useState } from "react";

function Pages() {
  const [message, setMessage] = useState({
    name: "",
    email: "",
    phone: "",
  });

  function handleChange() {
    setMessage();
  }

  return (
    <div>
      <input
        name="name"
        value={message.name}
        onChange={handleChange}
        type="text"
      />

      <input
        name="email"
        value={message.email}
        onChange={handleChange}
        type="text"
      />

      <input
        name="phone"
        value={message.phone}
        onChange={handleChange}
        type="text"
      />
    </div>
  );
}

export default Pages;

But When I type text in the input field, I found that I am not able to type anything in it.
So, Please advise me how to solve this problem and I have no idea to fix this.
Thank you
Aung

A: This is how your handleChange should look like:
function handleChange(e) {
    setMessage((message) => {
        return {
            ...message,
            [e.target.name]: e.target.value
        }
    })
}

Your input will always have the value from your message.phone, message.email, etc... because you explicitly gave it to the input when you wrote value = {message.phone}, for instance
In order to change the message.phone, for instance, you use the handleChange function to update the state of the component, and, therefore, update the input tag. Notice how now, setMessage is giving it a new value, returning all that message already has and mutating e.target.name (phone) to e.target.value (whatever the user is typing).


text:
Q: Automate collection of data from outlook .msg files to excel field My firewall sends me a notifcation to my email every time a policy is violated.
I have about 2500 emails in .msg format that I want to put into one excel document.
Basically I am looking for a way to automate processing each .msg file and putting it on a new line in an excel document.
All 2500+ .msg files are in a single folder.
I understand that .msg files hold binary data, and thats ok. I can clean up the excel document once it is created.
Thanks,
Aaron

A: Take a look at Outlook MSG file format specification.
You should consider getting the messages in some other format that is easier to parse.

A: Redemption or the Aspose libs can help you out here. There is also Sean Curries script.


text:
Q: Translating objects in nodeJS I have the following object that I need to transform into a slightly different format. I'm pretty sure I can use nodes native map function to translate it. e.g.

var animals = [
  [ 'cats', 1726, 1143, 10, 105, 2382, 0 ],
  [ 'dogs', 640, 0, 0, 0, 0, 0 ],
  [ 'cows' 13509, 0, 3, 1, 196939, 19 ],
  [ 'sheep', 1573, 1084, 10, 105, 2266, 0 ]
             ]

Into this format:

new_animals = [{
    name: 'cats',
    data: [1726, 1143, 10, 105, 2382, 0]
  }, {
    name: 'dogs',
    data: [640, 0, 0, 0, 0, 0]
  }, {
    name: 'cows',
    data: [13509, 0, 3, 1, 196939, 19]
  },
  {
    name: 'sheep',
    data: [1573, 1084, 10, 105, 2266, 0]
  }]

A: Using ES2015 features:
const newAnimals = animals.map(([name, ...data]) => ({ name, data }));

Without ES2015 features:
var newAnimals = animals.map(function (animal) {
  return {
    name: animal[0],
    data: animal.slice(1)
  };
});

A: its actually quite simple:

var animals = [
    ['cats', 1726, 1143, 10, 105, 2382, 0],
    ['dogs', 640, 0, 0, 0, 0, 0],
    ['cows', 13509, 0, 3, 1, 196939, 19],
    ['sheep', 1573, 1084, 10, 105, 2266, 0]
];

console.log(animals.map(([name, ...data]) => ({name, data})));

alternative if your node version does not support lambdas:
animals.map(function (animal) {
    return {
        name: animal.shift(),
        data: animal
    };
});


text:
Q: Custom Background Shape of Button via Code I have managed to create a custom button background shape via XML code
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true" >
        <shape android:shape="rectangle"  >
            <corners android:radius="24dp" />
            <stroke android:width="2dp" android:color="@color/colorWhite" />
            <solid android:color="@color/colorPrimary" />
        </shape>
    </item>
    <item android:state_focused="true">
        <shape android:shape="rectangle"  >
            <corners android:radius="24dp" />
            <stroke android:width="2dp" android:color="@color/colorWhite" />
            <solid android:color="@color/colorPrimary" />
        </shape>
    </item>
    <item >
        <shape android:shape="rectangle"  >
            <corners android:radius="24dp" />
            <stroke android:width="2dp" android:color="@color/colorWhite" />
            <solid android:color="@color/colorWhite" />
        </shape>
    </item>
</selector>

But I am wondering what is the Java code equivalent to that? Any guides please?

A: It's a lot more verbose to do it in Java, but here are the things you would need to do.

*

*Create a new StateListDrawable()

*For each state:

*

*Create a new ShapeDrawable(new RoundRectShape(...)). I don't recall exactly how the constructor args work, but you can experiment.

*Use shapeDrawable.getPaint() to obtain its Paint object and make modifications. You'll probably use setColor(), setStyle(), and setStrokeWidth().

*Construct a state set. This is an array of integers composed of various android state attributes, like android.R.attr.state_pressed, for the state you want.

*Call stateListDrawable.addState(stateSet, shapeDrawable). You can use StateSet.NOTHING (or an empty int[]) for the default state. Make sure you add them in the order they would appear in XML.

Something like this:
StateListDrawable stateListDrawable = new StateListDrawable();
Shape roundRect = new RoundRectShape(...);
// Add states in order. I'll just demonstrate one.
ShapeDrawable pressed = new ShapeDrawable(roundRect);
Paint paint = pressed.getPaint();
paint.setColor(Color.BLUE);
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(10f); // this is in pixels, you'll have to convert to dp yourself
int[] pressedState = { android.R.attr.state_pressed };
stateListDrawable.addState(pressedState, pressed);

A: You can handle button states like this:
StateListDrawable states = new StateListDrawable();
    states.addState(new int[] { android.R.attr.state_pressed }, getResources().getDrawable(R.drawable.img_pressed));
    states.addState(new int[] { android.R.attr.state_focused }, getResources().getDrawable(R.drawable.img_focused));
    states.addState(new int[] {}, getResources().getDrawable(R.drawable.img_normal));
    button.setBackgroundDrawable(states);

See this sample for reference:
StateListDrawable states = new StateListDrawable();
    states.addState(new int[] { android.R.attr.state_pressed }, getSelectedBackground());
    states.addState(new int[] { android.R.attr.state_focused }, getSelectedBackground());
    states.addState(new int[] {}, getNormalBackground());
    button.setBackgroundDrawable(states);

private ShapeDrawable getNormalBackground() {

    int r = 10;
    float[] outerR = new float[] { r, r, r, r, r, r, r, r };
    RoundRectShape rr = new RoundRectShape(outerR, null, null);
    ShapeDrawable drawable = new ShapeDrawable(rr);
    drawable.getPaint().setColor(Color.GRAY);

    return drawable;

}

private ShapeDrawable getSelectedBackground() {

    float[] outerR2 = new float[] { 10, 10, 10, 10, 10, 10, 10, 10 };
    RectF inset2 = new RectF(3, 3, 3, 3);
    float[] innerR2 = new float[] { 9, 9, 0, 0, 0, 5, 0, 0 };
    ShapeDrawable sh2 = new ShapeDrawable(new RoundRectShape(outerR2, inset2, innerR2));
    return sh2;

}

Check this once Defining Drawable Shape with in JAVA code


text:
Q: Javascript closure test- why am I having "undefined" as result? Here is my code -
function test1 () {
  let num = 15;

  return function test2 () {
    console.log(num);
    num++;
  }
}

let f = test1();
console.log(f());
console.log(f());
console.log(f());

This is the output I am getting -

My question is why am I getting the Undefined results after each value?

A: f and test2 don't return a value. What do you expect to see in the console logs? If you add return num, then you'll see the numbers printed twice.

function test1() {
  let num = 15;

  return function test2() {
    console.log(num);
    num++;
    return num;
  }
}

let f = test1();
console.log(f());
console.log(f());
console.log(f());


text:
Q: Creating a database for search I've created code that lets the user input a planet name and it returns the date the planet was found in, else it would return invalid planet name.
My question is, how could I add more details to the code, like for example gravity strength.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class sky {

  private static Map < String, Integer > planetMap = new HashMap < String, Integer > ();

  public static void main(String args[]) {
    populateDB();
    Scanner scanner = new Scanner(System.in);

    String planetName = scanner.nextLine();

    if (planetMap.get(planetName) != null) {
      System.out.println("The planet " + planetName + " was found in " + planetMap.get(planetName));
    } else {
      System.out.println("Invalid Planet Name");
    }

  }

  public static void populateDB() {

    planetMap.put("Earth", 1600);
    planetMap.put("Mars", 1500);
    planetMap.put("Jupiter", 1100);
    planetMap.put("Saturn", 1900);
    planetMap.put("Venus", 1300);
  }
}

Credit for phflack and bluelurker.

A: If you want more details, your could replace your Map<String, Integer> with Map<String, PlanetDetails>, where PlanetDetails is another class which is defined like:
private class PlanetDetails
{
   int date_found;

   double gravity_strength;

   double distance_from_sun;
}

and then while populating, you should do:
planetMap.put("Earth", new PlanetDetails(1600, gravitystrenght, distancefromsun);

A: Depending upon your requirements, you can create a Planet class and/or you make use of Hashmap as value of another Hashmap.
As far as class is concerned, there is already an answer that describes how to do that, anyway will give you an example below:
class Planet {
    String name;
    String gravityStrength;
    String universe;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGravityStrength() {
        return gravityStrength;
    }
    public void setGravityStrength(String gravityStrength) {
        this.gravityStrength = gravityStrength;
    }
    public String getUniverse() {
        return universe;
    }
    public void setUniverse(String universe) {
        this.universe= universe;
    }
}

Then you can have your Hashmap as follow with key as name of the planet (string) and value as Planet object:
HashMap<String, Planet> planets = new HashMap<String, Planet>();

Planet planetEarth = new Planet();
planetEarth.setName("Earth");
planetEarth.setGravityStrength("X");
planetEarth.setUniverse("The Milky Way");

planets.put("earth", planetEarth);

Or you could have the following hasmap where key is the name of the planet as string, and value is another hashmap that takes planet detail name as key and planet detail value as value (both string).
HashMap<String, HashMap<String, String>> planets = new HashMap<String, HashMap<String, String>>();

HashMap<String, String> earth = new HashMap<String, String>();
earth.put("name", "Earth");
earth.put("gravityStrength": "X4");
earth.put("universe", "The Milky Way");

planets.put("earth", earth);

Following is the Planet class implementation of what your code is doing. I have overrided the toString() in the Planet class to allow pretty-print of Planet object.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Sky{
    private static Map<String, Planet> planetMap = new HashMap<String, Planet>();

    public static void main(String args[]) {
        populateDB();

        Scanner scanner = new Scanner(System.in);

        System.out.print("Please input planet name: ");
        String planetName = scanner.nextLine();

        //converting to lowercase so user input Earth and earth and EARTH eArTH all match
        if (planetMap.containsKey(planetName.toLowerCase())) {
            //invokes the overrided toString() of Planet class
            System.out.println(planetMap.get(planetName.toLowerCase()).toString());
        } else {
            System.out.println("Invalid Planet Name");
        }
    }

    public static void populateDB() {
        Planet earth = new Planet("Earth", "4x", 1600);
        Planet mars = new Planet("Mars", "1x", 1500);
        Planet jupiter = new Planet("Jupiter", "3x", 1100);
        Planet saturn = new Planet("Saturn", "16x", 1900);
        Planet venus = new Planet("Venus", "5x", 1300);

        planetMap.put("earth", earth);
        planetMap.put("mars", mars);
        planetMap.put("jupiter", jupiter);
        planetMap.put("saturn", saturn);
        planetMap.put("venus", venus);
    }
}

class Planet {
    String name;
    String gravityStrength;
    int found;

    //empty constructor
    public Planet() {}

    public Planet(String name, String gravityStrength, int found) {
        this.name = name;
        this.gravityStrength = gravityStrength;
        this.found = found;
    }

    /* Getters and setters */

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public String getGravityStrength() {
        return gravityStrength;
    }
    public void setGravityStrength(String gravityStrength) {
        this.gravityStrength = gravityStrength;
    }

    public int getFound() {
        return found;
    }
    public void setUniverse(int found) {
        this.found = found;
    }

    //override toString methdo to pretty-print planet
    public String toString() {
        return "Planet " + name + " with gravity strenght " + gravityStrength + " was found in " + found;
    }
}

And if you do not like the Planet class implementation then you can always use the Hashmap inside Hashmap implementation below:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Sky {
    private static Map<String, HashMap<String, String>> planetMap = new HashMap<String, HashMap<String, String>>();

    public static void main(String args[]) {
        populateDB();
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter planet name to search for: ");
        String planetName = scanner.nextLine();

        if (planetMap.containsKey(planetName.toLowerCase())) {
            HashMap<String, String> p = planetMap.get(planetName.toLowerCase());
            System.out.println("The planet " + planetName + " was found in " + p.get("name")
                    + " and has gravity strenght of " + p.get("gravityStrength"));
        } else {
            System.out.println("Invalid Planet Name");
        }

    }

    public static void populateDB() {
        HashMap<String, String> earthDetails = new HashMap<String, String>();
        earthDetails.put("name", "Earth");
        earthDetails.put("gravityStrength", "4X");
        earthDetails.put("found", "1600");

        HashMap<String, String> marsDetails = new HashMap<String, String>();
        marsDetails.put("name", "Mars");
        marsDetails.put("gravityStrength", "31X");
        marsDetails.put("found", "1500");

        HashMap<String, String> jupiterDetails = new HashMap<String, String>();
        jupiterDetails.put("name", "Jupiter");
        jupiterDetails.put("gravityStrength", "1X");
        jupiterDetails.put("found", "1100");

        HashMap<String, String> saturnDetails = new HashMap<String, String>();
        saturnDetails.put("name", "Saturn");
        saturnDetails.put("gravityStrength", "100X");
        saturnDetails.put("found", "1900");

        HashMap<String, String> venusDetails = new HashMap<String, String>();
        venusDetails.put("name", "Venus");
        venusDetails.put("gravityStrength", "150X");
        venusDetails.put("found", "1300");

        planetMap.put("earth", earthDetails);
        planetMap.put("mars", marsDetails);
        planetMap.put("jupiter", jupiterDetails);
        planetMap.put("saturn", saturnDetails);
        planetMap.put("venus", venusDetails);
    }
}


text:
Q: Blur flowdocument in WPF I'm looking a way to blur FlowDocument like this:
 FlowDocument doc = new FlowDocument();
 BlurEffect blur = new BlurEffect();
 blur.Radius = 10;
 doc.Effect = blur; // it doesn't work! (FlowDocument doesn't have Effect property)

Update:
Above code is a part of a Converter which return FlowDocument for using in a FlowDocumentScrollViewer. Some items (returned flow documents) have specific conditions which should be blurred.
<DataGrid ItemsSource="{Binding Items}">
  <DataGrid.Columns>
     <DataGridTemplateColumn>
         <DataGridTemplateColumn.CellTemplate>
           <DataTemplate>
              <FlowDocumentScrollViewer
                Document="{Binding ., Converter={StaticResource ItemToFlowDocConverter}}"/>
           </DataTemplate>
         <DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
</DataGrid.Columns>


text:
Q: 'AnyHashable' is not convertible to 'NSObject' I am converting mine Objective-C code to Swift.
I am having my own DataStructure class called "DCclass" inherrited from  "NSObject"...
i have done all required things like: In Bridging-header imported the "DCclass.h" and etc things fine but while having its for in loop i am facing error something like its type conversion issue.
Thanks In Advance.
Current Objective-C code:
#import "DCclass.h"
@interface LPFPickerCell ()
@property (nonatomic) NSMutableArray *myMutableArray;
@end

@implementation LPFPickerCell
- (void)setSelectedData:(NSString *) selectedString
{
    int i = 0;
    for (DCclass *dc in self.myMutableArray)    /// Swift is showing compile time error here
    {
        NSLog(@"DCclass.empName = %@",dc.empName);
    }
}
@end

Converted Swift Code:
class LPFPickerCell {

    var myMutableArray = [AnyHashable]()

    func setSelectedData(_ selectedString: String?) {
        let i: Int = 0
        for dc: DCclass in myMutableArray {    ///'AnyHashable' is not convertible to 'DCclass'
        print("DCclass.empName = \(dc.empName)")
        }
    }
}

A: Maybe you need to change your array type
var myMutableArray = [AnyHashable]()

to
var myMutableArray = [DCclass]()

And then in the for loop you can access it like this
for dc in myMutableArray {
    print("DCclass.empName = \(dc.empName)")
}

A:
The AnyHashable type forwards equality comparisons and hashing operations to an underlying hashable value, hiding its specific underlying type.
You can store mixed-type keys in dictionaries and other collections that require Hashable conformance by wrapping mixed-type keys in AnyHashable instances:

Problem is that using AnyHashable will not work for type DCclass and so you need to manually cast the myMutableArray to particular type:
var myMutableArray = [DCclass]()

Convert code would be like:
class LPFPickerCell {
    var myMutableArray = [DCclass]()

    func setSelectedData(_ selectedString: String?) {
        let i: Int = 0
        for dc: DCclass in myMutableArray {
            print("DCclass.empName = \(dc.empName)")
        }
    }
}


text:
Q: need Iptables example for UDP I setup openvpn at Centos vps. It has venet0 and tun0 nic. I try to open 5060 udp port for my vpn client pfsene, it shows udp port open or filter. Is these right iptables rules?
iptables -A FORWARD -d 10.8.0.2 -i venet0 -p udp -m udp --dport 5060 -j ACCEPT
iptables -t nat -A PREROUTING -d "vps public ip" -p udp -m udp --dport 5060 -j DNAT --to-destination 10.8.0.2
iptables -t nat -A POSTROUTING -s 10.8.0.0/255.255.255.0 -o venet0 -j SNAT --to-source "vps public ip"

A: You can simply configure iptables rules using firewall-cmd utility.
For example:
firewall-cmd --permanent --add-port=5060/udp
firewall-cmd --permanent --add-masquerade
firewall-cmd --reload


text:
Q: using CakePHP 'Acl' component I'm a newbie to CakePHP components.
I had built a CakePHP application which has a login feature.
I had not used "Auth" component but was using my custom method for authenticating.
Now I want to use the 'Acl' component in the same appllication but I'm unable to do so because it requires the "Auth" component also.
Is it possible to use 'Acl' without "Auth".
If so, can anyone give some pointers?

A: It is possible to use them separately, at least according to the Cake PHP Manual. As long as you can link your authenticated users to an ARO in the database it should work. You can see some of the basics on CakePHP ACL here: http://book.cakephp.org/2.0/en/core-libraries/components/access-control-lists.html and here's a decent tutorial on setting up ACL: http://bakery.cakephp.org/articles/view/user-permissions-and-cakephp-acl
If you don't have your users in the database that makes it a little trickier. As long you can retrieve an ARO that has the required permissions after login you should be OK.

A: Yes it is possible - as long as you link your user accounts with ACL everything should be ok.
Let's say your users log in using their e-mail and password then your ARO table in alias field can contain the e-mail address and foreign_id pointing to the id of your users table.
Once you have all the ACOs in place checking for permissions can be done using
$res =  $this->Acl->check(
        $us, // user alias (e-mail)
        $this->name, // name of the controller
        $privilege // privilege i.e. 'read' or '*'
        );
    return $res;

called in your beforeFilter of AppController


text:
Q: Me tira el error array to string conversion cuando intento eliminar un registro Laravel Livewire

Ayúdenme por favor, no consigo el error.
public function destroy(Post $post){
    $post->delete();

    return view('welcome');

    //$this->emit('alert2', '¡Se elimino el post!');

}

                  Editar

            <x-jet-button wire:click="destroy({{$post->id}})">Eliminar</x-jet-button>
        </td>
    </tr>
    @endforeach


text:
Q: React Native: Possible unhandled promise rejection I'm getting the following error:

Possible unhandled promise rejection (id:0: Network request failed)

Here's the promise code, I don't see what's wrong here, any ideas?
  return fetch(url)
    .then(function(response){
      return response.json();
    })
    .then(function(json){
      return {
        city: json.name,
        temperature: kelvinToF(json.main.temp),
        description: _.capitalize(json.weather[0].description)
      }
    })
    .catch(function(error) {
    console.log('There has been a problem with your fetch operation: ' + error.message);
    });
}

Edit:
I added a catch function and got a better error:

You passed an undefined or null state object; instead, use forceUpdate(). index.ios.js:64 undefined

Here's the index.ios.js code. The url is fine and giving me the correct json data. I can see with console log that both region.latitude and region.longitude are available in Api(region.latitude, region.longitude). But data is undefined.
I'm still not sure what's going on, why there's a problem with data and why it's undefined.
// var React = require('react-native'); --deprecated

// updated
import React from 'react';

// updated
import {
  AppRegistry,
  MapView,
  View,
  Text,
  StyleSheet,
} from 'react-native';

/*
var {
  AppRegistry,
  MapView,
  View,
  Text,
  StyleSheet
} = React;
*/ // -- depreciated

var Api = require('./src/api');

var Weather = React.createClass({
  getInitialState: function() {
    return {
      pin: {
        latitude: 0,
        longitude: 0
      },
      city: '',
      temperature: '',
      description: ''
    };
  },
  render: function() {
    return <View style={styles.container}>
      <MapView
        annotations={[this.state.pin]}
        onRegionChangeComplete={this.onRegionChangeComplete}
        style={styles.map}>
      </MapView>
      <View style={styles.textWrapper}>
        <Text style={styles.text}>{this.state.city}</Text>
        <Text style={styles.text}>{this.state.temperature}</Text>
        <Text style={styles.text}>{this.state.description}</Text>
      </View>
    </View>
  },
  onRegionChangeComplete: function(region) {
    this.setState({
      pin: {
        longitude: region.longitude,
        latitude: region.latitude
      }
    });

    Api(region.latitude, region.longitude)
      .then((data) => {
        console.log(data);
        this.setState(data);
      });
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'stretch',
    backgroundColor: '#F5FCFF'
  },
  map: {
    flex: 2,
    marginTop: 30
  },
  textWrapper: {
    flex: 1,
    alignItems: 'center'
  },
  text: {
    fontSize: 30
  }
});

AppRegistry.registerComponent('weather', () => Weather);

A: catch function in your api should either return some data which could be handled by Api call in React class or throw new error which should be caught using a catch function in your React class code. Latter approach should be something like:
return fetch(url)
.then(function(response){
  return response.json();
})
.then(function(json){
  return {
    city: json.name,
    temperature: kelvinToF(json.main.temp),
    description: _.capitalize(json.weather[0].description)
  }
})
.catch(function(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
 // ADD THIS THROW error
  throw error;
});

Then in your React Class:
Api(region.latitude, region.longitude)
  .then((data) => {
    console.log(data);
    this.setState(data);
  }).catch((error)=>{
     console.log("Api call error");
     alert(error.message);
  });

A: You should add the catch() to the end of the Api call. When your code hits the catch() it doesn't return anything, so data is undefined when you try to use setState() on it. The error message actually tells you this too :)

A: According to this post, you should enable it in XCode.

*

*Click on your project in the Project Navigator

*Open the Info tab

*Click on the down arrow left to the "App Transport Security Settings"

*Right click on "App Transport Security Settings" and select Add Row

*For created row set the key "Allow Arbitrary Loads", type to boolean and value to YES.

A: Adding here my experience that hopefully might help somebody.
I was experiencing the same issue on Android emulator in Linux with hot reload. The code was correct as per accepted answer and the emulator could reach the internet (I needed a domain name).
Refreshing manually the app made it work. So maybe it has something to do with the hot reloading.

A: In My case, I am running a local Django backend in IP 127.0.0.1:8000
with Expo start.
Just make sure you have the server in public domain not hosted locally on your machine.
If it is hosted locally find the local IP address like 192.168.0.105 or something and use that

A: delete build folder projectfile\android\app\build and run project


text:
Q: Python script through the Tor network I have written a simple python script that fetches my ip.
import urllib
import socks
import socket

#set the proxy and port
socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 9150)

#initialize the socket
socket.socket = socks.socksocket

#store the URL that we want
url = 'https://check.torproject.org/'

#open the URL and store it into 'response'
response = urllib.urlopen(url)

#parse the response
html = response.read()

#print to console
print html

Nothing too complex, however the problem starts when analyzing the response from check.torbrowser. The site will always give me an address that is different from my currently running Tor browser that is on the same page. However, the html response will say that I am being routed through the Tor network but it doesnt look to be coming from the 'standard' tor browser. The latter part I understand, though I did not include it in the code above, I was playing with User-Agent strings and other headers, so I will chalk it up to that being the primary cause. What I do not understand is where in the h-e-double hockey sticks did the IP come from that was served as a response from the py script?
My next question, which builds on top of all this, is how do I connect my python script to the tor network correctly? After a little googling, I found that tor will block traffic for everything other than the socks protocol and that an alternative is to use privoxy in conjunction with tor. My initial thought is to do some kind of routing that would result in the layering of software. In my mind, it would look like:
Python -> Privoxy -> Tor -> Destination
My end goal in all of this is to grab a .onion based address and save/read it. However, I have put that to the side after all of these problems started occurring. A little info to help get better answers: I am using a Windows machine, though I have a Linux one if there is some functionality that may be present there that would help this process, and I am using Python 2.7 though, again, this can be easily changed.
I would like to ask that the steps to make all this happen be laid out - or at least some links/direction, I am by no means afraid to read a few good blogs/tutorials about the subject. However, I feel like this is really a couple of seperate questions, and would require quiet a lengthy answer so I would be more than happy to just know that I am on the right path before I rip more of my hair out :)

A: Your code is correct, however your assumption that Tor will always give you the same IP address is not. Thanks to circuit isolation, a privacy feature of Tor that ensures isolation between the connections you open, you're routing the request through a different exit node than the Tor Browser will.
Reliably emulating the Tor Browser behavior is hard and I would recommend against it. Your method for connecting to the Tor network looks correct.
Tor will allow you to use any protocol you want, but yes you need to connect through the SOCKS protocol. That's fine though: almost all network protocols (http included) play nicely with SOCKS.

A: With torpy library you can renew circuits as you wish.
>>> from torpy.http.requests import TorRequests
>>>
>>> def show_ip(resp):
...     for line in resp.text.splitlines():
...         if 'Your IP address appears to be' in line:
...             print(line)
...
>>> with TorRequests() as tor_requests:
...     print("build circuit")
...     with tor_requests.get_session() as sess:
...         show_ip(sess.get("https://check.torproject.org/"))
...         show_ip(sess.get("https://check.torproject.org/"))
...     print("renew circuit")
...     with tor_requests.get_session() as sess:
...         show_ip(sess.get("https://check.torproject.org/"))
...         show_ip(sess.get("https://check.torproject.org/"))
...
build circuit

Your IP address appears to be:  178.17.171.102

Your IP address appears to be:  178.17.171.102

renew circuit

Your IP address appears to be:  49.50.66.209

Your IP address appears to be:  49.50.66.209


text:
Q: jQuery synchronization of functions (only works with alert) Here I construct an array:
var optionTexts = [];
    $('#stripeMeSubSubCat tr').each(function(){
        if ($(this).find('input:checkbox.subsubcat_chkclass:not(:checked)').length == 0)
            {
                subsubrow_cat_id_no = parseInt($(this).closest("tr").attr("id"));
                optionTexts.push(parseInt(subsubrow_cat_id_no));
            };
    });

The code below only works whenever the alert is enabled. I have read that this might be due to a synchronization issue. Is there a solution towards the code below? Thank you.
$('#stripeMeSubSubCat tr').each(function(){
        myindex = parseInt($.trim($(this).closest("tr").attr("id")));

        if (jQuery.inArray(myindex, optionTexts) == -1) {
             var equal="FALSE";
        }else{
             var equal="TRUE";
            $("#stripeMeSubSubCat tr[id='" + myindex + "'] input").attr('checked', true);
        };

        //alert(equal);
});

A: You probably need to wait for the DOM to load. Try wrapping this code in:
$(function(){
  // put code here
});

A: What do you mean by "only works whenever the alert is enabled"? You need to describe the difference in behavior in both cases.
Your code has no asynchronous calls, so there shouldn't be  synchronization issue.  However, you seem to be using an integer as a DOM element id. This isn't allowed.


text:
Q: Scraping all tables from a webpage using python ps4 I want to use beautifulsoup to get all the tables at this link https://www.investing.com/indices/indices-futures, following that I want to get the titles in the Index Column, and the Links of those titles.
I want what's in the first column only.
So for example.
title        href
Dow Jones    /indices/us-30-futures
S&P 500      /indices/us-spx-500-futures
...
Mini DAX     /indices/mini-dax-futures
...
VSTOXX Mini  /indices/vstoxx-mini

I use the following code
url = "https://www.investing.com/indices/indices-futures"
req = requests.get(url, headers=urlheader)
soup = BeautifulSoup(req.content, "lxml")
table = soup.find('div', id="cross_rates_container")
for a in table.find_all('a', href=True):
    print (a['title'], a['href'])

I can see the table variable, but I can't seem the access the title (which contains the index name) and href (which contains the links)
What's wrong with it how can I get all the tables' entries at once?

A: You can iterate over <td> elements and get the <a> link under them.
For example:
import requests
from bs4 import BeautifulSoup

url = 'https://www.investing.com/indices/indices-futures'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0'}
soup = BeautifulSoup(requests.get(url, headers=headers).content, 'html.parser')

print('{:<30} {}'.format('Title', 'URL'))
for a in soup.select('td.plusIconTd > a'):
    print('{:<30} {}'.format(a.text, 'https://www.investing.com' + a['href']))

Prints:
Title                          URL
Dow Jones                      https://www.investing.com/indices/us-30-futures
S&P 500                        https://www.investing.com/indices/us-spx-500-futures
Nasdaq                         https://www.investing.com/indices/nq-100-futures
SmallCap 2000                  https://www.investing.com/indices/smallcap-2000-futures
S&P 500 VIX                    https://www.investing.com/indices/us-spx-vix-futures
DAX                            https://www.investing.com/indices/germany-30-futures
CAC 40                         https://www.investing.com/indices/france-40-futures
FTSE 100                       https://www.investing.com/indices/uk-100-futures
Euro Stoxx 50                  https://www.investing.com/indices/eu-stocks-50-futures
FTSE MIB                       https://www.investing.com/indices/italy-40-futures
SMI                            https://www.investing.com/indices/switzerland-20-futures
IBEX 35                        https://www.investing.com/indices/spain-35-futures
ATX                            https://www.investing.com/indices/austria-20-futures
WIG20                          https://www.investing.com/indices/poland-20-futures
AEX                            https://www.investing.com/indices/netherlands-25-futures
BUX                            https://www.investing.com/indices/hungary-14-futures
RTS                            https://www.investing.com/indices/rts-cash-settled-futures

... and so on.

EDIT: Screenshot with <td> elements:


text:
Q: Is mod_WSGI replacing what apache is doing and how I can make wsgi work at a specific path only I am quite new to Apache and WSGI, there are a lot of things confusing me.
After a fresh install of apache2 on ubuntu, I can open this URL to see the default apache page http://localhost/index.html, the file is residing in /var/www/html. So this is the function that apache server provices, serving http connection.
Here's the current situation:
I've created a simple Django project and install mod_wsgi onto my apache server,and finally I managed to deploy the project to apache and the page iIve created can be accessed correctly.
BUT now when I try to access the index.html i mentioned above, it shows the url mapping cannot be found(yes I do not have this mapping in the django project).Is Django taking over all the path that point to the server?
How can I make the django project only map to a specific path like http://localhost/Django/[MY URL MAPPING] and keep other url mapping untouched.
So I can access the static HTML(index.html) by accessing http://localhost/index.html/ and access my Django project by accessing http:/localhost/Django/[xxx]
Is this possible? or I have to use another virtual host at another port?
Any help will be much appreciated.

A: You can do this by mounting Django at a different point:
WSGIScriptAlias /Django /path/to/mysite.com/mysite/wsgi.py

This runs the WSGI application at /Django, and leaves Apache to serve the rest of the files directly.


text:
Q: How to print AND redirect print content into a file? I know how to redirect stdout into a file:
import sys
sys.stdout = open('log.txt', 'w')
print 'test'

This will create a log.txt where test will be written in it.
However, test will not be print in stdout.
How can i print and redirect test in both terminal and file without changing every print statement in the program.
PS: I know that redirecting sys.stdout is bad (but i still need to do it)

A: The tee unix command reads standard input and writes it to both standard output and one or more files. In might be an option for you to redirect the output of your script to tee.

A: You should probably run your entire script piped to tee: python hello.py | tee logfile.txt . Altering sys.stdout to a file-like object which contains the splitting functionality is possible, but won't cover subprocesses run by your script. You then need to use the second process via pipe, and by then there's no need to reinvent the wheel.


text:
Q: Identify Rows with Same Values in 2 Different Columns I have a data set of roughly 405,000 rows and 23 columns.  I need the records where the value in column "D" is the same as the value in column "H" for that row.
So for
A  B  C  D  E  F  G  H
13 8 21 ok  3  S  - of
51 7 22 no  3  A  k no
24 3 23 by  3  S  * we
24 4 24 we  3  S  ! ok
24 9 25 by  3  S  @ we
75 2 26 ok  3  S  9 ok

etc...
I'd get back the 2nd row, the 6th row, etc...
A  B  C  D  E  F  G  H
51 7 22 no  3  A  k no
75 2 26 ok  3  S  9 ok

Based on other posts like: Formula to find matching row value based on cells in multiple columns I tried using a Pivot Table, but it complains I can't put either of my two columns in the "Columns" area because there is too much data.  With both columns in the "Rows" area, I get a relationship of D to H, but I can't then find a way to filter on only those where D = H.
I've also looked into countifs(), vlookup, and index / match functions, but I can't figure this out.  Help please.

A: I would do a simple "IF()" formula in a new column.
For your example add a new column I and use the following formula in the first data row (I2):
=IF(D2=H2,"Yes","No")

Fill down to the end of the data.
Then using Excel filters or countif you can check the number of "Yes" vs "No" in your data.


text:
Q: R, using table function on a list If I define a list like this:
a <- list(1,2,3,4,5,1)

and then call table(a) , I get:
, , a.3 = 3, a.4 = 4, a.5 = 5, a.6 = 1

   a.2
a.1 2
  1 1

Isn't this behavior weird? How could I use the table function on this list to get something like:
1 2 3 4 5
2 1 1 1 1

A: The table function provides "a contingency table of the counts at each combination of factor levels" (from ?table). Since it works on vectors and not a list, you just need to unlist it:
unlist(a)
# [1] 1 2 3 4 5 1
table(unlist(a))
# 1 2 3 4 5
# 2 1 1 1 1


text:
Q: SonarCloud branch has no lines of code - bitbucket pipelines - sonarsource/sonarcloud-scan I am trying to integrate sonarcloud with Bitbucket pipeline. I have a simple test project with single file named index.php consisting few lines.
I am exactly not sure what method should I follow.
I have created sonar-project.properties files that consists following lines.
sonar.sourceEncoding=UTF-8
sonar.host.url=https://sonarcloud.io/dashboard?id=first_ftp
sonar.projectKey=first_ftp

Here is my yml file
image: aariacarterweir/lamp-gitftp:latest

clone:
  depth: full # SonarCloud scanner needs the full history to assign issues properly

definitions:
  caches:
    sonar: ~/.sonar/cache  # Caching SonarCloud artifacts will speed up your build
  steps:
    - step: &build-test-sonarcloud
        name: Build, test and analyze on SonarCloud
        caches:
          - node
          - sonar
        script:
          - npm install --quiet
          - npm run test -- --code-coverage --no-watch --no-progress --browsers=ChromeHeadlessNoSandbox
          - pipe: sonarsource/sonarcloud-scan:0.1.5
            variables:
              SONAR_TOKEN: ${SONAR_TOKEN}
              EXTRA_ARGS: '-Dsonar.sources=src -Dsonar.tests=src -Dsonar.test.inclusions="**/testing/**,**/*.spec.ts" -Dsonar.typescript.lcov.reportPaths=coverage/lcov.info'

When I check into sonarcloud website, It tells
The main branch has no lines of code

Can anybody help me how to configure properly sonarcloud with bitbucket for php project.

A: I've had the same issue - in my case it was because of the name of the project - it was called ---------Test, and apparently, by default, Sonar will treat that as a test assembly and will exclude it from analysis.

A: Before running code analysis in bitbucket pipelines, you would have to first manually run analysis(only once). By following below steps.


text:
Q: CKEditor insert empty paragraph In the CKEditor plugin I'm writing, i need to create a new empty paragraph.
I know that empty paragraphs (

) are collapsed by most browsers, that is why CKEditor has some special handling for them:

*

*When displaying the HTML source, CKEditor displays

 for an empty paragraph (for example, when you press enter twice)

*Depending on the browser, in the editing area CKEditor fills the Paragraph with another placeholder. For example in Mozilla Firefox, it inserts a
 into the paragraph.

However, when inserting a p DOM node manually (using the CKEditor dom object), this special handling is omitted. It magically appears when i switch to source view and back edit mode, though.
I've tried:
var new_p = new CKEDITOR.dom.element('p');
editor.insertElement(new_p);

And:
var new_p = new CKEDITOR.dom.element.createFromHtml('

');
editor.insertElement(new_p);

And also:
editor.insertHtml('
');

But the special handling of the empty paragraph does not take place. I get an empty Paragraph, but as the Browser is collapsing it, I can't see or edit its content correctly.
When switching back and forth to the source code view, CKEditor detects the empty paragraph and inserts the filler. Also when submitting the data. But i need the filler to appear immediately when inserting the new node.
How do i get CKEditor to handle my new paragraph like any other empty paragraph it would create when a user hits Enter twice?
I know i could also insert   manually as HTML content to the new DOM node, but thats a huge difference - because in this case, the space really appears in the editing area, so when a user enters content into the new paragraph, he must delete the non-breaking space manually.

A: After researching how CKEditor handles the press of [ENTER] internally, i came to this solution:
var new_node = new CKEDITOR.dom.element( 'p' );

// insert UTF-16 non-breaking space
var dummy = editor.document.createText( '\u00A0' );
dummy.appendTo( new_node );
editor.insertElement(new_node);

// move cursor to beginning of new element
var range = editor.createRange();
range.moveToPosition( new_node, CKEDITOR.POSITION_AFTER_START );
editor.getSelection().selectRanges( [ range ] );


text:
Q: Splitting variable length delimited string across multiple rows (SQL) I have a table that contains in one column a variable length delimited string for example:

20,0, 5,,^24,0, 0,,^26,0, 0,,^
  281,0, 0,,^34,0, 2,,^48,0, 2,,^44,0, 2,,^20,0, 10,,^
  20,5, 5,,^379,1, 1,,^26,1, 2,,^32,0, 1,,^71,0, 2,,^

What i need to do is split this string so that each number after the ^ character is returned on a new row. like:

Item Number    Item Code
  Item1    20
  Item2   ^24
  Item3   ^24
  Item4   ^27
  Item5   ^28
  Item6   ^65
  Item7   ^66
  Item8   ^39
  Item9   ^379
  Item10  ^448
  Item11  ^427

I've tried various split functions and I can manage to achieve the result i need by substring'ing the values across multiple columns and then using unpivot to return them across multiple rows however this method doesnt handle teh variable length of this string.
Any ideas of a better approach?

A: First, let me just say that this is the reason that you shouln't have comma separated data in a field in the first place. There is no easy or efficient way to work with it.
That said, you can use a recursive query to split the string and get the numbers from it:
with split as
(
  select
    item = cast('' as varchar(max)),
    source = cast('20,0, 5,,^24,0, 0,,^26,0, 0,,^281,0, 0,,^34,0, 2,,^48,0, 2,,^44,0, 2,,^20,0, 10,,^20,5, 5,,^379,1, 1,,^26,1, 2,,^32,0, 1,,^71,0, 2,,^' as varchar(max))
  union all
  select
    item = substring(source, 1, charindex(',,', source)),
    source = substring(source, charindex(',,', source) + 2, 10000)
  from split
  where source > ''
)
select substring(item, 1, charindex(',', item) -1)
from split
where item > ''

Result:
20
^24
^26
^281
^34
^48
^44
^20
^20
^379
^26
^32
^71


text:
Q: Search domain : multiple condition in odoo How to convert this expression : ((A & B) | ( C & D)) | (( E & F) | (G & H))  in  OpenERP domain syntax
PostgreSQL query is :
SELECT
  *
FROM
   calendar_event
WHERE
  (
    (start_datetime <= '2020-01-07 09:00:00' and '2020-01-07 09:00:00' <= stop_datetime) or
    (start_datetime <= '2020-01-07 11:00:00' and '2020-01-07 11:00:00' <= stop_datetime)
  ) or (
    ('2020-01-07 09:00:00' <= start_datetime and start_datetime <= '2020-01-07 11:00:00') or
    ('2020-01-07 09:00:00' <= stop_datetime and stop_datetime <= '2020-01-07 11:00:00')
  )

I try to make like this but is not correct, where i'm wrong please?
   inParams1.push([
         "|",
         "&",
         ["start_datetime", "<",  '2020-01-07 09:00:00'],
         ['2020-01-07 09:00:00', "<=", "stop_datetime"],
         "&",
         ["start_datetime", "<=", '2020-01-07 11:00:00'],
         ['2020-01-07 11:00:00', "<=", "stop_datetime"],

         "|",
         "&",
         ['2020-01-07 09:00:00', "<=", " start_datetime"],
         ["start_datetime", "<=",'2020-01-07 11:00:00'],
         "&",
         ['2020-01-07 09:00:00', "<=",  "stop_datetime"],
     ["stop_datetime", "<=",'2020-01-07 11:00:00']
]);

Please i need your help, i have many days working and i can't find a solution :(

A: I find this answer very helpful for complicated domain. https://stackoverflow.com/a/57853916/8211573
According to that answer, you can use odoo.osv.expression.
In [6]: from odoo.osv.expression import AND,OR

In [7]: a,b,c,d,e,f,g,h = ([("field_" + x, "=", "value_" + x)] for x in "ABCDEFGH")

In [8]: OR([OR([AND([a,b]),AND([c,d])]),OR([AND([e,f]),AND([g,h])])])
Out[8]:
['|',
 '|',
 '&',
 ('field_A', '=', 'value_A'),
 ('field_B', '=', 'value_B'),
 '&',
 ('field_C', '=', 'value_C'),
 ('field_D', '=', 'value_D'),
 '|',
 '&',
 ('field_E', '=', 'value_E'),
 ('field_F', '=', 'value_F'),
 '&',
 ('field_G', '=', 'value_G'),
 ('field_H', '=', 'value_H')]

A: You complicated the filter by parentheses:
(
    (start_datetime <= '2020-01-07 09:00:00' and '2020-01-07 09:00:00' <= stop_datetime) or
    (start_datetime <= '2020-01-07 11:00:00' and '2020-01-07 11:00:00' <= stop_datetime)
  ) or (
    ('2020-01-07 09:00:00' <= start_datetime and start_datetime <= '2020-01-07 11:00:00') or
    ('2020-01-07 09:00:00' <= stop_datetime and stop_datetime <= '2020-01-07 11:00:00')
  )

Is the same as this:
    (start_datetime <= '2020-01-07 09:00:00' and '2020-01-07 09:00:00' <= stop_datetime)
     or
    (start_datetime <= '2020-01-07 11:00:00' and '2020-01-07 11:00:00' <= stop_datetime)
    or
    ('2020-01-07 09:00:00' <= start_datetime and start_datetime <= '2020-01-07 11:00:00')
    or
    ('2020-01-07 09:00:00' <= stop_datetime and stop_datetime <= '2020-01-07 11:00:00')

So just try this:
    [    '|'
         "&",
         ["start_datetime", "<",  '2020-01-07 09:00:00'],
         ["stop_datetime", ">=", '2020-01-07 09:00:00'],
         '|',
         "&",
         ["start_datetime", "<=", '2020-01-07 11:00:00'],
         ["stop_datetime", ">=", '2020-01-07 11:00:00'],
         '|',
         "&",
         ["start_datetime", ">=", '2020-01-07 09:00:00'],
         ["start_datetime", "<=",'2020-01-07 11:00:00'],
         "&",
         ["stop_datetime", ">=",  '2020-01-07 09:00:00'],
         ["stop_datetime", "<=",'2020-01-07 11:00:00']
     ]

let me know if it doesn't work for you.


text:
Q: ModuleNotFoundError: No module named 'routers' I've got this error :
from routers.patients import router as  PatientsRouter
ModuleNotFoundError: No module named 'routers'
When i try to run docker-compose up api with my project.
My file structure:

My Dockerfile:
FROM python:3.9-slim-buster

WORKDIR /project

COPY ./requirements.txt .

RUN pip install -r requirements.txt

COPY ./api /project/api/

CMD ["uvicorn", "api.main:app", "--host=0.0.0.0", "--port=8000"]

EXPOSE 8000

My docker-compose:
version: "3.8"
services:
  api:
    build: .
    command: ["uvicorn", "api.main:app", "--host=0.0.0.0", "--port=8000"]
    volumes:
      - ./api:/project/api
    ports:
      - "8000:8000"

A: In order to import from routers, python needs the __init__.py file in that same directory to treat it as a module.
It looks like your init file in the api directory has an extra underscore at the beginning.


text:
Q: Count number of unique rows based on two columns, by group I have a data.table in r
    col1 col2 col3   col4
 1:  5.1  3.5  1.4 setosa
 2:  5.1  3.5  1.4 setosa
 3:  4.7  3.2  1.3 setosa
 4:  4.6  3.1  1.5 setosa
 5:  5.0  3.6  1.4 setosa
 6:  5.1  3.5  3.4    eer
 7:  5.1  3.5  3.4    eer
 8:  5.1  3.2  1.3    eer
 9:  5.1  3.5  1.5    eer
10:  5.1  3.5  1.4    eer

DT <- structure(list(col1 = c(5.1, 5.1, 4.7, 4.6, 5, 5.1, 5.1, 5.1,
5.1, 5.1), col2 = c(3.5, 3.5, 3.2, 3.1, 3.6, 3.5, 3.5, 3.2, 3.5,
3.5), col3 = c(1.4, 1.4, 1.3, 1.5, 1.4, 3.4, 3.4, 1.3, 1.5, 1.4
), col4 = structure(c(1L, 1L, 1L, 1L, 1L, 4L, 4L, 4L, 4L, 4L), .Label = c("setosa",
"versicolor", "virginica", "eer"), class = "factor")), .Names = c("col1",
"col2", "col3", "col4"), row.names = c(NA, -10L), class = c("data.table",
"data.frame"))

I want to count unique (distinct) combinations of col1 and col2 for each value of col4.
Expected output is
   col1 col2 col3   col4 count
 1:  5.1  3.5  1.4 setosa     4
 2:  5.1  3.5  1.4 setosa     4
 3:  4.7  3.2  1.3 setosa     4
 4:  4.6  3.1  1.5 setosa     4
 5:  5.0  3.6  1.4 setosa     4
 6:  5.1  3.5  3.4    eer     2
 7:  5.1  3.5  3.4    eer     2
 8:  5.1  3.2  1.3    eer     2
 9:  5.1  3.5  1.5    eer     2
10:  5.1  3.5  1.4    eer     2

How can I do this in 1 data.table syntax only?

A: I had to go through a few attempts first, and ended up with this.  Any good?
DT[, count:=nrow(unique(.SD)), by=col4, .SDcols=c("col1","col2")]
DT
    col1 col2 col3   col4 count
 1:  5.1  3.5  1.4 setosa     4
 2:  5.1  3.5  1.4 setosa     4
 3:  4.7  3.2  1.3 setosa     4
 4:  4.6  3.1  1.5 setosa     4
 5:  5.0  3.6  1.4 setosa     4
 6:  5.1  3.5  3.4    eer     2
 7:  5.1  3.5  3.4    eer     2
 8:  5.1  3.2  1.3    eer     2
 9:  5.1  3.5  1.5    eer     2
10:  5.1  3.5  1.4    eer     2
>

and the same but faster thanks to Procrastinatus comment below :
DT[, count:=uniqueN(.SD), by=col4, .SDcols=c("col1","col2")]


text:
Q: how to prove the following for first order taylor's approximation? we have the taylor approximation as follows
$$f(x) = f(\bar x) + \nabla f(\bar x)(x − \bar x) + o(\|x − \bar x\|)$$
How to prove this?
If f is continuous over $[\bar x, x]$ and differentiable over $(\bar x, x)$, then:
$$f(x) = f(\bar x) + \nabla f(z)(x − \bar x),
  \; \text{for some} \; z \in [\bar x, x]$$


text:
Q: minted+latex: color differently every occurrence of a given command Say my LaTeX package defines only \MyMarvelousCommand.
In my package documentation, I have many different listings typeset with minted. \MyMarvelousCommand should appear in red inside each listing.
Here is my actual solution:

*

*use minted's escapeinside||

*In all my listings, replace \MyMarvelousCommand by |\MyMarvelousCommand|

*Redefine \MyMarvelousCommand at the beginning of the minted environment using hooks.

\documentclass{article}
\RequirePackage{minted}
\newcommand\MyMarvelousCommand[1]{Do marvelous things with #1}
\AtBeginEnvironment{minted}{
  \def\MyMarvelousCommand{{\color{red}\string\MyMarvelousCommand}}
}
\begin{document}
\begin{minted}[escapeinside=||]{latex}
\texttt{|\MyMarvelousCommand|{\LaTeX}}
\end{minted}
\texttt{\MyMarvelousCommand{\LaTeX}}
\end{document}

This is far from optimal:

*

*I must parse the code by myself

*It breaks MWE with spurious characters, which is very annoying

*it does not work on listing+output examples (like in tcblisting)

Is there another approach

A: Here I add two options to minted

*

*post processor=<script.py>

*post processor args=<more_args>
minted is also patched to execute python3 <script.py> <hash.pygtex> <more_arg> before input a <hash.pygtex> file each time. Here <hash.pygtex> represents the (intermediate) output tex file of pygments. You can think it as the cached _mint-<main>/<hash.pygtex>.
Then your need can be served by a simple python script which replaces \MyMarvelousCommand to a wrapped form, like \wrapper{\MyMarvelousCommand}. Since we are handling the pygments output, \<cmd> is actually \PYGZbs{}<cmd>.
Since pygments is itself a python library, executing a python script will not add any extra dependencies. Also the following script is more or less a proof-of-concept, so you can extend the script to make it more flexible.
#!/usr/bin/python3
import fileinput
import sys

# This is `highlightcmd.py`
# Usage: python3 highlightcmd.py xxx.pygtex MyCommandFirst

if len(sys.argv) < 4:
    raise ValueError(f'Need three args, given {len(sys.argv)}')

fin = sys.argv[1]
cmd = sys.argv[2]
wrapper = sys.argv[3]
# python highlighter of vscode accepts only uppercase `R` to represent raw string
# see https://github.com/MagicStack/MagicPython/issues/114
pattern_find = fR'{{\PYGZbs{{}}{cmd}}}'
pattern_sub = fR'{{\{wrapper}{{\PYGZbs{{}}{cmd}}}}}'

with fileinput.input(fin, inplace=True) as file:
    for line in file:
        print(line.replace(pattern_find, pattern_sub), end='')

\documentclass{article}
\usepackage{minted}
\newcommand\MyMarvelousCommand[1]{Do marvelous things with #1}

\makeatletter
\pretocmd\minted@inputpyg{%
  \minted@postprocesspyg
    {\minted@get@opt{post processor}{}}
    {\minted@outputdir\minted@infile}
    {\minted@get@opt{post processor args}{}}%
}{}{\fail}

\minted@def@opt{post processor}
\minted@def@opt{post processor args}

% #1 = name of the python script, e.g., "process.py"
% #2 = input ".pygtex" file, always be "\minted@outputdir\minted@infile"
% #3 = more args passed to the python script, possibly empty
\newcommand{\minted@postprocesspyg}[3]{%
  \ifstrempty{#1}{}{%
    % execute "python3 <script.py> <file.pygtex> <more_args>"
    \ShellEscape{python3 #1 #2 #3}%
  }%
}
\makeatother

\begin{document}
\setminted{
  autogobble,
  post processor=highlightcmd.py,
  post processor args=MyMarvelousCommand wrapper
}
\newcommand{\wrapper}[1]{\textcolor{red}{#1}}

\begin{minted}{latex}
  \MyMarvelousCommand{\LaTeX}
\end{minted}
\texttt{\MyMarvelousCommand{\LaTeX}}
\end{document}


text:
Q: Can the hypergeometric function be extended analytically to the complex plane in the interval [1,$\infty$ )? Just a thought. The hypergeometric function, which can be written as:
$$F(a,b,c \space;z) = \frac{\Gamma (c)}{\Gamma (b) \Gamma (c-b)}\int_0^1t^{b-1}(1-t)^{c-b-1}(1-zt)^{-a}dt$$
is obviously continuous on the unit disc. I was wondering if it could be extended to the positive real line?

A:
The contour integration representation (Barnes integral) allows one to analytically continue the hypergeometric function to the entire complex plane.
  See Roelof Koekoek's lecture supplement Barnes integral representation.  -- Random Variable

A: Use the Transformation formulae $_2F_1(a,b;c;z)=(1-z)^{-b}{}_2F_1\left(b,c-a;c;\dfrac{z}{z-1}\right)$ or $_2F_1(a,b;c;z)=(1-z)^{-a}{}_2F_1\left(a,c-b;c;\dfrac{z}{z-1}\right)$ in e.g. http://en.wikipedia.org/wiki/Hypergeometric_function#Transformation_formulas


text:
Q: Ensure /etc/export contains rule using bash What's a working example of modifying /etc/export using bash?
Example:
I want to ensure the following rule is present and valid:
/export/home 2400:123::/32(rw,no_root_squash)

And it should:

*

*Add only if it doesn't exist already (in any form)

*If it partly exists, it shold update existing entry (e.g options update)

Possible syntaxes in existing file:

*

*Multiple whitespaces, and different options
/export/home                    2400:123::/32(rw,no_root_squash,no_subtree_check)

*Multiple allow on same line
/export/home 2400:123::/32(rw,no_root_squash,no_subtree_check) 2400:321::/32(rw,no_root_squash,no_subtree_check)
In addition to combinations of the above.
Initially I wanted to use augeas for this, but there's a bug with IPv6 adresses in the /etc/exports file.
The /etc/exports file should allow independent modifying witout breaking the script (which should ensure only the rule in question is correct and valid, and leave the rest of the rules alone)

A: If you can't use Augeas and Puppet, here's what I would do:
if grep -qF '^/export/home' /etc/exports;then
    sed -i \
    's@^/export/home.*$@/export/home 2400:123::/32(rw,no_root_squash)@'\
    /etc/exports
else
    echo '/export/home 2400:123::/32(rw,no_root_squash)' >> /etc/exports
fi

Careful, though: this assumes that any rule for exporting /export/home is fair game for being replaced by your given definition.

A: I found that the /etc/exports lense for Augeas has been fixed for IPv6 in trunk, and can be imported manually:
https://github.com/hercules-team/augeas/blob/master/lenses/exports.aug
Putting this file into /usr/share/augeas/lenses/ makes it take presendence over the default lense.


text:
Q: Out of space, even when I have around 300gb free I have been using Ubuntu 14.04 for a while now, but I still get confused sometimes by the directory structure. I have a 500gb harddisk (just the one partition) mounted on /.
I am running TileStache (v1.50.1) to cache VectorTiles, and I keep getting the error message that I am out of space. Even though I have around 290gb free. What is going on? How can I get my application to make use of the free space that I have (TileStache doesn't allow me to store the tiles it has created on a different partition)
This is the error I get: OSError: [Errno 28] No space left on device: '/home/muzaffar/TileStache/scripts/~/cache2/stache/tmpXoywE3.json.gz:

When I use gparted this is what I get: /dev/sda1 mountpoint / unused 300.21 GiB:

And inside the scripts folder referenced in the original error: Free space: 291.5 GB:

A: The Error in your screenshot does not refer to the HDD space as you have rightfully pointed. It refers to the size of the "Device" in this case your tilestache cache.
Please check if there some junk files or old unused cache files. If so you can safely remove them and try again. In case you require further information, refer to the following thread.
http://ubuntuforums.org/showthread.php?t=2177876
Also check how much inodes you have left,
use df -i
It should return something like
Filesystem      Inodes  IUsed   IFree IUse% Mounted on
udev            489954    491  489463    1% /dev
tmpfs           492649    483  492166    1% /run
/dev/sda5      3131408 246990 2884418    8% /
none            492649      2  492647    1% /sys/fs/cgroup

if there are sufficient inodes present there should be no reason why your cache cant grow. If this dint help either, please do revert with the output from the shell.


text:
Q: How to print sum of 2 numbers in MIPS? I am trying to get the sum of 2 numbers but facing difficulties. I did tried to store values in v0 and tried to add them using s0. But it didn't worked out.

A: #below is an example
.data
int1 : .word 23
int2 : .word 3
result : .word 0
.globl main
.text
main:
lw $t0, int1
lw $t1, int2
add $t2,$t0,$t1
sw $t2, result
li $v0, 1  #these instructions will be used to print
lw $a0, result
syscall

A: .data
A: .word 2 # this is the block to initialize values
B: .word 4

.text

.globl  main
.ent    main
main:
    lw $t0,A # load value of A in temp register t0
    lw $t1,B # load value of B in temp register t1
    add $t2,$t0,$t1 # add the value of temp register t0 and t1 then place it in temp register t2

    li $v0,10 #
    syscall   # exit the program
.end    main


text:
Q: Need a common object between httpcontext and httpcontextbase I'm using both asp.net mvc 5 and asp.net web api 2 owin based web application.
The first one is the website and the second one is the backend api.
I need to share some libraries,
in the asp.net mvc application i can access to HttpContextBase.Request that is a HttpBaseRequest
in the web.api a can access to httpContext.Request that is a HttpRequest
Planning to upgrade to asp.net core in future, what is the best way to have a common object to share in my class libraries?

A: You could define an interface representing access to httpcontext, however without binding it to any specific http-related type
Then, provide implementations specific to frameworks that your libraries and apps are dealing with. .net framework and .net mvc and dotnet-core each define different implementations for http contexf, request, response.
e.g.
interface IMyHttpContext

class Net4HttpContext : IMyHttpContext

class NetCoreHttpContext : IMyHttpContext

then, expose just what you need. e.g. GetRequestPath, WriteToResponse, GetHeader, SetCookie. etc..It'll be a lot of and ongoing work, but as a result, your netstandard libraries (one of which should host your interface, btw) won't care about the impementation. Obviously, you'll have to replace all usages of specific http objects to your interface.
So, IMyHttpContext goes to one new netstandard assembly..This assembly will work with all dotnet frameworks.
Net4HttpContext goes to net45 assembly, itself referencing System.Webb. you reference this one by windows-only, .net framework apps.
NetCoreHttpContext goes to dotnetcore or netstandard assembly, referencing dotnet core's http-related nuget packages. use this one with dotnet core apps.
Then, throughout your apps, whether they are net45 or netcore, along with some DI setup, you reference just your interface. Implementations get to be injected.
Good luck.


text:
Q: glusterfs geo replication on non standard ssh port I need to achieve glusterfs geo replication.
In my production environment the port 22 is not open between the servers I want to do replication (This is by design and we have to leave with it).
Is there a way I can use a customize ssh port (i.e 22222) to achieve it.
Is there any other solution for this.
NOTE: I can not use other servers other then this two.

A: Gluster uses the installed ssh client meaning you can override configuration using the normal ssh_config.
So create .ssh/config in the homedir of the user that runs glusterfs (probably root) and configure the client using the documented Host:
[glusterfsnode-hostname]
Port 2222

Alternatively, you can configure glusterfs to use a different ssh-command, and add -p 2222 there


text:
Q: Java Eclipse java.lang.UnsatisfiedLinkError JNI loading dll and C code I am trying to use a code library that involves using JNI to access dll files and C code. I have tried everything I can think of and I can't seem to resolve this error.
The problem is with
 System.loadLibrary("psjw");

where psjw is a dll/C code that is located in the same folder as the java class invoking this method. I have tried

*

*setting java.library.path in the JVM differently in Eclipse

*putting the file in a separate folder and adding this as a Native Library in Eclipse

*using System.load("fully qualified path in here"); instead

none of which resolve the issue.
I'm using a mac with OSX 10.8.5 but I don't think that's relevant.

A: You can't load a dll file on Mac OS X. OS X JNI code is in jnilib files and have to be built for OS X not Windows.


text:
Q: How to overlay a view above a keyboard in iOS I need to present a help screen that overlays an open keyboard - the help screen should dim the whole view underneath and keep just a small hole with full transparency to "highlight" that piece. The point is to provide some information about several view components while highlighting them. Without a keyboard, I could just put a view at top of the hierarchy, but in this case the UI uses a keyboard with a custom input accessory that needs to be visible.
I tried to insert a new UIWindow and put it above all the UIWindows:
class CustomTextField: UITextField {
    override var canResignFirstResponder: Bool {
        return false
    }
}

class ViewController: UIViewController {
    var textField: UITextField = CustomTextField()

    override func viewDidAppear(_ animated: Bool) {
        view.backgroundColor = .white
        super.viewDidAppear(animated)

        textField.frame = CGRect(x: 0, y: 0, width: 200, height: 50)
        view.addSubview(textField)
        textField.backgroundColor = UIColor.gray
        textField.becomeFirstResponder()

        DispatchQueue.main.asyncAfter(wallDeadline: .now() + 1) {

            self.window.windowLevel = 100000002.0 // based on experiments with UIApplication.shared.windows this should be the top most window
            let controller = UIViewController()
            controller.view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
            self.window.rootViewController = controller
            self.window.makeKeyAndVisible()
        }
    }
    let window = UIWindow(frame: UIScreen.main.bounds)
}

But there are two problems with this approach:

*

*The keyboard gets hidden as soon as the window becomes key and visible.

*Even when using windowLevel = 100000002.0 it seems that the keyboard is above the window (the keyboard gets animated, so while hiding, I can see that its above my window).

Any ideas how to deal with these two problems? Is it even possible?

A: OK, as pointed out by @Krunal, this is kind of a duplicate of this question. The trick there is to add the overlay view to the window in which keyboard is (which happens to be the UIApplication.shared.windows.last):

class ViewController: UIViewController {
    var textField: UITextField = UITextField()

    override func viewDidAppear(_ animated: Bool) {
        view.backgroundColor = .white
        super.viewDidAppear(animated)

        textField.frame = CGRect(x: 0, y: 0, width: 200, height: 50)
        view.addSubview(textField)
        textField.backgroundColor = UIColor.gray
        textField.becomeFirstResponder()

        DispatchQueue.main.asyncAfter(wallDeadline: .now() + 1) {
            // this does the trick
            let customView = UIView(frame: self.view.bounds)
            customView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
            customView.layer.zPosition = CGFloat(Float.greatestFiniteMagnitude)
            UIApplication.shared.windows.last?.addSubview(customView)
        }
    }
}


text:
Q: Azure Event Hub diagnostic set up for User Errors I am running a set up, where Stream Analytics job is reading from Azure Event Hub. Event Hub is contained within a namespace and there is consumer group created for SA specifically.
Recently I noticed User Error on Event Hub metrics.

Event Hub Namespace is configured to push all logs to OMS:

*

*ArchiveLogs

*OperationalLogs

*AutoScaleLogs

*KafkaCoordinatorLogs

*EventHubVNetConnectionEvent

*CustomerManagedKeyUserLogs

*KafkaUserErrorLogs

But that does not seem to cover that particular case, since I am unable to find that error in Log Analytics Workspace (e.g. by doing search "UserError" over last 24 hours).
Searching through docs is not to helpful either. Closest I have found was in .NET SDK for Azure:
Namespace: Microsoft.Azure.EventHubs
Assembly: Microsoft.Azure.EventHubs.dll
UserError Identifies the exception as a user error and user needs to take an action to address the failure.

But that is not very helpful either, as it does not even indicate whether user is the sender or receiver of message.
What is the UserError in that case and how to pinpoint, what is actually happening?

A: User errors generally occur due to mistakes in the client application like,
User Errors in Event hub and service bus occurs due to similar reasons .. You can refer Azure Service Bus Message Queue User Errors Metric


text:
Q: How to ADD CONSTRAINT UNIQUE to colums that contains more characters than default I want to add unique to the columns that is title, language and download (3 columns). Since i don't have other options to get rid of duplicate entries. Here is the code:
ALTER TABLE datapdf ADD CONSTRAINT tb_uq UNIQUE (title, language, download);

But i get this error:
1071 - Specified key was too long; max key length is 1000 bytes
Is there any solution for this? But remember, it should match by this three columns.

A: It seems that your this three columns' length are too long,I have do a test,look at it.
drop table if exists datapdf;
create table datapdf
(
title varchar(200),
 language varchar(300),
 download varchar(510)
);

ALTER TABLE datapdf ADD CONSTRAINT tb_uq UNIQUE (title, language, download);

I get an error the as same as your.
Error Code: 1071. Specified key was too long; max key length is 767 bytes

But if I change the structure of table datapdf,it runs succeed.
drop table if exists datapdf;
create table datapdf
(
title varchar(100),
 language varchar(100),
 download varchar(100)
);

ALTER TABLE datapdf ADD CONSTRAINT tb_uq UNIQUE (title, language, download);

This is the Action.
ALTER TABLE datapdf ADD CONSTRAINT tb_uq UNIQUE (title, language, download)

So I think you can change your table's structure(if possible) to solve this problem.However,it's not a good solution,because you may lose your data.One of the best solution is what @N.B said(the first comment of this question):"
Add a fourth column. Save the hash of the 3 columns combined. Make the column unique."


text:
Q: Generate and Insert surrogate keys into already existing BigQuery table I have an existing table without any unique ID. I'm planning to generate surrogate keys using GENERATE_UUID() statement however I'm sure not how to insert this new column... What is the best option here?

A: One way is to use CREATE OR REPLACE TABLE ... AS SELECT
CREATE OR REPLACE TABLE table_a
AS SELECT GENERATE_UUID() uuid, * FROM table_a

The drawback is:

*

*The metadata of the table is lost (table options, column descriptions etc.)

*Nullability of the columns is lost, all columns becomes NULLABLE

If both are acceptable, then approach above is the simplest way
If not, then you need to add a column through UI or API, then do
UPDATE table_a
SET uuid = GENERATE_UUID()
WHERE uuid IS NULL


text:
Q: How do I connect and make request to flickr,facebook and other social media? I am trying to integrate flickr,facebook and picasa in my webpage so that User can authenticate by signing into his account from any one of these and he can get images from his account and upload onto my webpage.And after editng those images he can upload back to the same website.
So how should I proceed.Can anyone give me your suggestions?
Here is the sample link what I mean?
http://www.showzey.com/

A: Read the API documentation

*

*Flickr: http://www.flickr.com/services/api/

*Facebook: https://developers.facebook.com/

*Picasa:
http://code.google.com/apis/picasaweb/overview.html


text:
Q: Bootstrap Carousel Jumps to top of page when advancing When I advance the slider manually, the slider jumps to the top of the page. How can I prevent this from happening? Help much appreciated! Here's the code:

                ‹
        ›

A: You can either do this inline (less clean) :

or you can do globally assuming you remove the href="#controlid :
$('body').on('click','.carousel-control',function() {
   $(this).closest('.carousel').carousel( $(this).data('slide') );
});

or you can do it individually by being more specific in your selector
$('body').on('click','#carouselID .carousel-control',function() {
   $(this).closest('.carousel').carousel( $(this).data('slide') );
});

A: you should try with jquery:
$('.carousel-control').click(function (e) {
  e.preventDefault();
});

A: You can add data-target attribute refering to your carousel: data-target="#carousel"

A: It turns out there was a smooth page jump script for another page that was causing this issue. It works after I moved out the the following from custom.js:
  function filterPath(string) {
    return string
    .replace(/^\//,'')
    .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
    .replace(/\/$/,'');
  }
  var locationPath = filterPath(location.pathname);
  var scrollElem = scrollableElement('html', 'body');

  $('a[href*=#]').each(function() {
    var thisPath = filterPath(this.pathname) || locationPath;
    if (  locationPath == thisPath
      && (location.hostname == this.hostname || !this.hostname)
      && this.hash.replace(/#/,'') ) {
      var $target = $(this.hash), target = this.hash;
    if (target) {
      var targetOffset = $target.offset().top;
      $(this).click(function(event) {
        event.preventDefault();
        $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
          location.hash = target;
        });
      });
    }
  }
});

  // use the first element that is "scrollable"
  function scrollableElement(els) {
    for (var i = 0, argLength = arguments.length; i <argLength; i++) {
      var el = arguments[i],
      $scrollElement = $(el);
      if ($scrollElement.scrollTop()> 0) {
        return el;
      } else {
        $scrollElement.scrollTop(1);
        var isScrollable = $scrollElement.scrollTop()> 0;
        $scrollElement.scrollTop(0);
        if (isScrollable) {
          return el;
        }
      }
    }
    return [];
          }

A: This one worked well for me. Replace href with "data-target"

A: When you link to an HTML anchor, it will be relative to where the
 is, which by default with Twitter Bootstrap, is located at the top of the carousel. I see that your using the data- tags, therefore I don't believe there is a need for the href attributes.
Change this:

‹
›

to this:

‹
›

Currently I'm not at the office, so I haven't had time to test it in more than 1 scenario, however, from the looks, it should still work & give you your desired results.

A: i tried to set up a working document of this.  i don't see the jump behavior.  did nothing out of the ordinary just copied your markup, added sample images, bootstrap.js, bootstrap-carosel.js, and bootstrap.css
http://brandonam.com/bootTest/boot.html
fyi: typical browser behavior for '#myCarousel' would be to point the window focus to the element marked '#myCarousel'   ... but i think bootstrap prevents this by default.  shouldn't be moving around.

A: Set href to href="javascript:void(0)" then add this somewhere in your js:
$('.carousel-control.right').click(function(){ $('.carousel').carousel('next')});
$('.carousel-control.left').click(function(){ $('.carousel').carousel('prev')});

A: I've had the same problem
my a tag looked like:

it was solved by removing extra mix-panel attributes in the tag:

sorry that it isn't solving your problem, but it might help others with similar problem.

A: We spent quite a lot of time on this but setting the data-target attribute and other solutions did not work for us. The scroll-up/jumping of the page was happening irrespective.
This seems to happen with Bootstrap3 carousels where each slide is of different height. @Fabian's comment above helped us. For those who missed it, adding overflow:hidden to the carousel class is a good hack to fix this:
@media (min-width: 768px)
{
    #our-carousel
    {
      overflow: hidden;    /* workaround to resolve the page jumping/scrolling up on
                              smaller screens on auto/manual advancing of
                              carousel */
    }
}

A: I ended up adding a overflow: hidden; to the carousel class which did the trick.

A: I had the same problem and found that replacing the HTML attribute href= within the indicator button anchor tags with data-target= relieved the page jumping problem.

A: href="#myCarousel" is looking for  and trying to move the window to that position.
try setting your href to href="javascript:void(0)"


text:
Q: Cannot Deserialize Json in localhost I have one application where some dummy data are kept :
 public class ValuesController : ApiController
{
    // GET api/values
    public string Get()
    {
        List<Cars> carslist = new List<Cars>();
        carslist.Add(new Cars { Id = "1", Color = "RED", CompanyName = "AUDI", Years = "1993", Model = "A4" });
        carslist.Add(new Cars { Id = "2", Color = "BLUE", CompanyName = "MERCEDES", Years = "1992", Model = "BENZ" });
        carslist.Add(new Cars { Id = "3", Color = "GREEN", CompanyName = "BMW", Years = "1990", Model = "C-CLASS" });
        carslist.Add(new Cars { Id = "4", Color = "YELLOW", CompanyName = "VOLKSWAGEN", Years = "1989", Model = "JETTA" });
        //return carslist;
        //JavaScriptSerializer jss = new JavaScriptSerializer();
        //string jsonstring = jss.Serialize(carslist);
        //return jsonstring;

        string JsonString = JsonConvert.SerializeObject(carslist);
        return JsonString;
    }

After JSON Formatting is done, i am requesting this particular data from another application, and Deserializing there, but it always showing error. The code from which i am accepting this data is below:
public ActionResult Index()
    {

        Uri url = new Uri(@"http://localhost:51933/api/Values");
        WebRequest webRequest = WebRequest.Create(url);
        WebResponse response = webRequest.GetResponse();
        StreamReader streamReader = new StreamReader(response.GetResponseStream());
        string responseData = streamReader.ReadToEnd().Trim();

        var sdf = JsonConvert.DeserializeObject<List<Cars>>(responseData);

        return View();
    }

The Model is like this
    public class Cars
{
    public string Id { get; set; }
    public string CompanyName { get; set; }
    public string Model { get; set; }
    public string Years { get; set; }
    public string Color { get; set; }

}

public class ListOfCars
{
    public List<Cars> listofcars { get; set; }
}

I am really not understanding, why the deserialization is not happening. Please help me out.
Thanks in advance.
Both the applications are running on localhost
This is the error :
Error

A: From the screenshot with your error I can see that you are trying to deserialize to ListOfCars class, not to List<Cars>. Change the type to List<Cars>.


text:
Q: Facebook importing details ios This is the first time i am trying to integrate Facebook into my ios app.
I am trying to import first name, last name and some other details from Facebook. I am able to log in to Facebook but i cannot import the details. I think my code is wrong somewhere and i don't know where!
    if (appDelegate.session.isOpen) {
    [FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection,
                                                           id<FBGraphUser> user,
                                                           NSError *error2) {

        regdet.firstname = user.first_name;
        regdet.lastname = user.last_name;
        regdet.email = [user objectForKey:@"email"];
        regdet.address1 = [user objectForKey:@"locale"];
        regdet.city = [user.location objectForKey:@"name"];
        NSLog(@"firstname %@",regdet.firstname);

    }];

} else {
    if (appDelegate.session.state != FBSessionStateCreated) {
        // Create a new, logged out session.
        appDelegate.session = [[FBSession alloc] init];
    }

    // if the session isn't open, let's open it now and present the login UX to the user
    [appDelegate.session openWithCompletionHandler:^(FBSession *session,
                                                     FBSessionState status,
                                                     NSError *error1) {

        [FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection,
                                                               id<FBGraphUser> user,
                                                               NSError *error2) {

                regdet.firstname = user.first_name;
                regdet.lastname = user.last_name;
                regdet.email = [user objectForKey:@"email"];
                regdet.address1 = [user objectForKey:@"locale"];
                regdet.city = [user.location objectForKey:@"name"];
                NSLog(@"firstname %@",regdet.firstname);

        }];
         [self performSegueWithIdentifier: @"Facebooksegue" sender: self];

    }];
}

A: Here is Facebook documentation and example. You need to ask for additional permission.
[FBSession openActiveSessionWithReadPermissions:@[@"basic_info", @"email"]
                                   allowLoginUI:YES
                              completionHandler:^(FBSession *session,
                                                  FBSessionState status,
                                                  NSError *error) {
                                  // Respond to session state changes,
                                  // ex: updating the view
                              }];

Here is Facebook permission keys and description

A: Try this
FBLoginView *loginView=[[FBLoginView alloc]init];
loginView.delegate=self;
loginView.readPermissions = @[@"first_name",
                              @"last_name",
                              @"location",
                              @"id",
                              @"access_token",
                              @"email"];
NSArray* permissions =  [NSArray arrayWithObjects: @"email", nil];
loginView.readPermissions = @[@"email"];
loginView.readPermissions=permissions;

{

    [FBSession openActiveSessionWithReadPermissions:Nil allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {

[FBRequestConnection
 startForMeWithCompletionHandler:^(FBRequestConnection *connection,
                                   id<FBGraphUser> user1,
                                   NSError *error)
    {
        if (!error)
        {

            firstname=user1.first_name;
            lastname=user1.last_name;
            city=[user1.location objectForKey:@"name"];
            email=user1[@"email"];
            fbid=user1.id;

            [[NSUserDefaults standardUserDefaults]setObject:Loggedin forKey:@"token"];
            [[NSUserDefaults standardUserDefaults]synchronize];
        }
        NSURL *url = [[NSURL alloc]initWithString:[NSString stringWithFormat:@"%@action=currfbuser&email=%@&fb_id=%@",MainURL,email,fbid ]];
        NSError *errors;
        NSData *data = [NSData dataWithContentsOfURL:url];
        NSDictionary *json = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errors];
        NSString  *status = json[@"status"];
        user = json[@"user"];
        if ([status isEqualToString:@"success"])
        {
            [self performSegueWithIdentifier: @"LogIN" sender: self];
        }
        else if (!([fbid isEqualToString:@""]))
        {
            [self performSegueWithIdentifier: @"Facebooksegue" sender: self];
        }
        NSLog(@"%@",firstname);
        NSLog(@"%@",lastname);
        NSLog(@"%@",city);
        NSLog(@"%@",email);
        NSLog(@"%@",fbid);

    }];}];
}