text:
Q: Connection to SignalR Hub fails with Negotiate 404 (not found) I've been researching this issue for 3 days now and cannot find a solution.  I created a SignalR Hub with the following code:
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;

namespace Messenger.Hubs
{
    public class MessengerHub : Hub
    {
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }
}

Simple enough, the startup code is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Messenger.Hubs;

namespace Messenger
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddSignalR();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseSignalR(routes =>
            {
                routes.MapHub<ChatHub>("c:/myapp/Messenger");
            });
            app.UseMvc();
        }
    }
}

I pretty much cut and pasted the code from a solution posted on the internet somewhere, I forget where, not stackoverflow though.  I then created the following client in a Xamarin (v4.12.3.81) project using Visual Studio 2017 (v15.9.10).  That code is:
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Client;

namespace SignalR.Client.Hubs
{
    public class SampleHub
    {
        // MessengerHub is a appliaction folder aliased as MessengerHub
        // the direct path on the machine is c:\mywebapp\messenger
        private const string _hubUrl = "http://example.com/MessengerHub";
        private readonly HubConnection _hubConnection;
        public event EventHandler<string> OnMessageReceived;

        public SampleHub()
        {
            var builder = new HubConnectionBuilder().WithUrl(_hubUrl);
            _hubConnection = builder.Build();
        }

        public async Task<bool> ConnectAsync()
        {
            try
            {
                await _hubConnection.StartAsync();
                _hubConnection.On("messageReceived", (string platform, string message) =>
                {
                if (OnMessageReceived != null)
                    {
                        OnMessageReceived(this, string.Format("{0}: {1}", platform, message));
                    }
                });
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
                //Console.WriteLine($"Connection error: {ex.Message}");
                return false;
            }

            return true;
        }

        public async Task<int> GetNumberAsync(int number)
        {
            return await _hubConnection.InvokeAsync<int>("GetNumber", number);
        }

        public Task Send(string message)
        {
            return _hubConnection.SendAsync("Send", message);
        }
    }
}

The code in the activity that uses that client is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

using Android.Views.InputMethods;
using SignalR.Client.Hubs;

namespace MyXamarinApp
{
    [Activity(Label = "Messenger")]
    public class Messenger : Activity
    {
        protected override async void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            SetContentView(Resource.Layout.Messenger);

            RequestedOrientation = Android.Content.PM.ScreenOrientation.Portrait;
            try
            {
                var input = FindViewById<EditText>(Resource.Id.Input);
                var messages = FindViewById<ListView>(Resource.Id.Messages);

                var inputManager = (InputMethodManager)GetSystemService(InputMethodService);
                var adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, new List<string>());

                messages.Adapter = adapter;

                var hub = new SampleHub();

                await hub.ConnectAsync(); // <---- fails here

                input.EditorAction +=
                  delegate
                  {
                      inputManager.HideSoftInputFromWindow(input.WindowToken, HideSoftInputFlags.None);

                      if (string.IsNullOrEmpty(input.Text))
                          return;

                      hub.Send(input.Text);

                      input.Text = "";
                  };

                hub.OnMessageReceived +=
                  (sender, message) => RunOnUiThread(() =>
                    adapter.Add(message));
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
            }
        }
    }
}

The hub is (I believe) running correctly on the server, I set logging on and this is what is in the log:
Hosting environment: Production
Content root path: C:\mywebapp\Messenger
Application started. Press Ctrl+C to shut down.

The attempt to connect to the hub generates the following error:
{System.Net.Http.HttpRequestException: 404 (Not Found)

  at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode () [0x0002a] in <25ebe1083eaf4329b5adfdd5bbb7aa57>:0

  at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection+<NegotiateAsync>d__44.MoveNext () [0x00226] in <843c441fa9954906b53e3710152bebb9>:0

--- End of stack trace from previous location where exception was thrown
  --- at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection+<GetNegotiationResponseAsync>d__51.MoveNext () [0x00077] in <843c441fa9954906b53e3710152bebb9>:0

--- End of stack trace from previous location where exception was thrown
  ---
 at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection+<SelectAndStartTransport>d__43.MoveNext () [0x00169] in <843c441fa9954906b53e3710152bebb9>:0

--- End of stack trace from previous location where exception was thrown
  ---
  at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection+<StartAsyncCore>d__40.MoveNext () [0x00118] in <843c441fa9954906b53e3710152bebb9>:0

--- End of stack trace from previous location where exception was thrown
  --- at System.Threading.Tasks.ForceAsyncAwaiter.GetResult () [0x0000c] in <843c441fa9954906b53e3710152bebb9>:0

  at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection+<StartAsync>d__39.MoveNext () [0x0008b] in <843c441fa9954906b53e3710152bebb9>:0

--- End of stack trace from previous location where exception was thrown
  --- at Microsoft.AspNetCore.SignalR.Client.HttpConnectionFactory+<ConnectAsync>d__3.MoveNext () [0x0009d] in <d50de232736c4c8f910083ea0cb358a8>:0

--- End of stack trace from previous location where exception was thrown
  ---
 at Microsoft.AspNetCore.SignalR.Client.HttpConnectionFactory+<ConnectAsync>d__3.MoveNext () [0x00142] in <d50de232736c4c8f910083ea0cb358a8>:0

--- End of stack trace from previous location where exception was thrown
  ---
 at Microsoft.AspNetCore.SignalR.Client.HubConnection+<StartAsyncCore>d__47.MoveNext () [0x00130] in <f381011e9b214489bcb373743f31ed9d>:0

--- End of stack trace from previous location where exception was thrown
  ---
 at System.Threading.Tasks.ForceAsyncAwaiter.GetResult () [0x0000c] in <f381011e9b214489bcb373743f31ed9d>:0

  at Microsoft.AspNetCore.SignalR.Client.HubConnection+<StartAsync>d__39.MoveNext () [0x00091] in <f381011e9b214489bcb373743f31ed9d>:0

--- End of stack trace from previous location where exception was thrown
  ---
  at SignalR.Client.Hubs.SampleHub+<ConnectAsync>d__6.MoveNext () [0x00037] in C:\Users\<username>\Documents\Visual Studio 2017\Projects\signalr_client\signalr_client\Resources\layout\Client.cs:28 }

This is what I see in the IIS Log for the site.
"POST /MessengerHub/negotiate HTTP/1.1" 303 446
"GET /MessengerHub/negotiate HTTP/1.1" 404 1509

I have no idea what to try next.

A: I struggled with this error today and after some rather wasted time I had simple forgot to add:
app.UseEndpoints(endpoints =>
{
    endpoints.MapHub<FooHub>("/FooHub");
});

To the Startup.cs >> public void Configure(...) in my .NET 5 ASP.NET application.
Things have changed a little since this was originally posted (and I did see some Xamarin) but hopefully this gives somebody some guidance in the future.

A: I had the same problem with SignalR NetCore 5, Blazor webassembly project when deployed to IIS, worked fine in localhost on dev machine.
The solution was to use full url in the hub connection:
First include hub endpoint in the Startup.cs
 endpoints.MapHub<BroadcastHub>("/broadcastHub");

Then when setting up the hub connection, instead
   hubConnection = new HubConnectionBuilder()
              .WithUrl(navigationManager.ToAbsoluteUri("/broadcastHub")
                 .Build();

use full url:
     hubConnection = new HubConnectionBuilder()
            .WithUrl("http://myserver.com/bcwa/broadcastHub")
            .Build();

bcwa is my IIS deploy folder


text:
Q: how can i export db from mysql without exec() function I am trying to get the database dump from a live mysql server. I don't have db access. from googling I have found a way to get this through exec() like this
$command='mysql -h' .$mysqlHostName .' -u' .$mysqlUserName .' -p' .$mysqlPassword .' ' .$mysqlDatabaseName .' < ' .$mysqlImportFilename;
        exec($command,$output=array(),$worked);

working nice on local host . But when i tried this on live server then i come to know that exec() is not enable on server . I have checked this with this method
if(function_exists('exec')) {
    echo "exec is enabled";
}else
{
  echo "exec is not enabled";
 }

and also tried this
if(exec('echo EXEC') == 'EXEC'){
    echo 'exec works';
}else
{
  echo "exec is not enabled";
}

I want to know is there a method so that i can export db dump without exec() function .Because I don't have server access.

A: If you don't need you own script you should go for phpMyAdmin to create dumps or use a tool like phpMiniAdmin. You can also check their sources to see how simple it is creating dumps just with plain queries and without the need of exec()

redpajama_set_name: RedPajamaStackExchange


text:
Q: ArcPy .replace Field Calculator - replace only standalone 0's with 111, not all instances of 0 I've searched on google intensively, must be missing something here: I only want to replace (in a string field) standalone zeros (len is 1 character), but the .replace function replaces all instances of 0.
How can I only replace a single character (meaning the value is simply 0).  If the value is say 10004 or 02223 or 12450, leave alone.

A: Use the Show Codeblock option and use this function:
def replace_zero_string(value):
    if value == '0': # assuming the field is a text field
        return value.replace('0', '111')
    else:
        return value

Then outside/below the code block section call the function like:
replace_zero_string(!rpuid!)


text:
Q: JFileChooser, is it possible to return current directory without clicking anything else than add? I would like to have the following (if possible):

*

*the user wants to add some files, he opens the File Chooser

*without clicking/selecting any files or directory, he clicks instead directly on the add button

*all the files contained in the current directory will be retrieved

Is it feasible?


text:
Q: Load log4j from stream is it possible to load log4j configuration from the ByteStream?
or from something else, but not from the file?
Thanks

A: From DOM element.
Extending the DOMConfigurator perhaps even with InputStream.


text:
Q: Behat "When I fill the following fields" input todays date? Is there a way in behat to get it to input todays date when I fill in a field?
an example
Given I fill in the following fields
| field_date | TODAY |
And I would like the output as dd/mm/YYYY
I cant understand why I cant find it, or find someone else who has done this before? I have found answers for gherkin and cucumber, but nothing for PHP and behat..
Thanks

A: I managed to get this working...add this to your FormContext file -
/**
 * Fills in specified field with date
 * Example: When I fill in "field_ID" with date "now"
 * Example: When I fill in "field_ID" with date "-7 days"
 * Example: When I fill in "field_ID" with date "+7 days"
 * Example: When I fill in "field_ID" with date "-/+0 weeks"
 * Example: When I fill in "field_ID" with date "-/+0 years"
 *
 * @When /^(?:|I )fill in "(?P<field>(?:[^"]|\\")*)" with date "(?P<value>(?:[^"]|\\")*)"$/
 */
public function fillDateField($field, $value)
{
    $newDate = strtotime("$value");

    $dateToSet = date("d/m/Y", $newDate);
    $this->getSession()->getPage()->fillField($field, $dateToSet);
}


text:
Q: Objects to ArrayList All am trying to do is add objects to the list. But I don't know why I am getting an error with the line shapetizer.add(circleone);. Can anybody help me out please.
Main
import java.util.*;

public class Main {

    //create an empty list of shape objects
    ArrayList<Shape> shapetizer = new ArrayList<Shape>();

    //create 2 circle objects
    Circle circleone = new Circle(10);
    Circle circletwo = new Circle(20);

    //Add the created circles to the list
    shapetizer.add(circleone);

}

Shape
public abstract class Shape {

    // yet to be filled

}

Circle
public class Circle extends Shape {

    private float radius;

    public Circle(float radius) {
        super();
        this.radius = radius;
    }

    public String toString() {
        return "Circle [radius=" + radius + "]";
    }

}

The errors I am getting for the line I mentioned above are:

*

*syntax error on token(s), misplaced construct(s)

*syntax error on token "circleone", VariableDeclaratorId expected after this token

A: Your Code is in the Main class not in a main method !


text:
Q: Show a toast message when entering a number in Edit text I'd like to show a toast message when entering a number less than 180 , I'm a beginner but I need some help , so i want to show a specific message when entering a number less than 180 , so what to write in the if method ?
public class MainActivity extends Activity {
EditText ed1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ed1 = (EditText)findViewById(R.id.editText1);

}

public void mansaf (View v)
{

    if (){

        Toast.makeText(MainActivity.this, "Message1", Toast.LENGTH_LONG).show();
    }
        else
        Toast.makeText(MainActivity.this, "Message2 ", Toast.LENGTH_LONG).show();

}

}

and this is the xml code :

<EditText
    android:id="@+id/editText1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="number"
    android:hint="ما السرعة التي تقود بها عادة ؟" >

    <requestFocus />
</EditText>

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="ما مستوى قيادتي ؟"
    android:onClick="mansaf"/>

A: if (Integer.valueof( ed1.getText().toString)<180))
    Toast.makeText(MainActivity.this, "Message1", Toast.LENGTH_LONG).show();
else
    Toast.makeText(MainActivity.this, "Message2 ", Toast.LENGTH_LONG).show();

A: Compare the text with 180 by:
if(Integer.valueOf(ed1.getText().toString())<180)

    Toast.makeText(getBaseContext(),"Message",Tosat.LENGTH_LONG).show();


text:
Q: Using lodash and trying to update and Object with multiple objects. (editing items) I am using lodash and redux/react to make a simple app. Right now I have it returning an object with multiple objects in it. So it looks something like this when I get the final object.
Object { 2: Object, 34: Object}
Each Object has a title , id, and description. I used lodash to mapKeys and make each object within the single object to be keyed with the ID. This way it is easier to find each object. For example Mainobject[34] will return that object even though it is second in the Object.
So this is all working well now and I want to be able to update the object or edit some code and replace one of the excising objects. I am using redux/react so understanding of that will be required to understand what I am trying to do.
As you can see I am trying to use the _.get to find the item out of the mainObject and then update that particular item with the _.merge, I then am trying to use _.update, but in my console.log of my current state I am getting this in the console:
current state is: -> Object {2: Object, 34: Object}
current state is: -> Object {2: Object, 34: Object, object Object: undefined}
The second console has the object with the id of 34 and everything is updated and working correctly, but I am getting the undefind object Object at the end.
Here is my reducer:
const reducer = function(state={}, action) {
  switch(action.type) {
    case "POST_BOOK":
      return _.mapKeys(action.payload, 'id');
    break;
    case "DELETE_BOOK":
      return _.omit(state, action.payload);
    break;
    case "UPDATE_BOOK":
      let foundItem = _.get(state, action.payload.id);
      let updateItem = _.merge(state[action.payload.id],foundItem,action.payload);
      console.log(updateItem);
      return _.update(state, state[action.payload.id], updateItem);
    break;
  }
  return state
}

Here are my actions:
store.dispatch({
  type: "POST_BOOK",
  payload: [
  {
    id: 34,
    title: 'this is the book title',
    description: 'this is the book description',
    price: 3
  },
  {
    id: 2,
    title: 'this is the book title 2',
    description: 'this is the book description 2',
    price: 3.2
  }
]
});

// store.dispatch({
//   type: "DELETE_BOOK",
//   payload: 2
// });

store.dispatch({
  type: "UPDATE_BOOK",
  payload: {
    id: 34,
    title: 'this is book edit title',
    description: 'this is book edit edit',
    price: 2341.23
  }
})

A: Well, you are very close to the solution here. The only thing wrong with your code is that _.update needs a function as third parameter while you are giving it an object.
Actually you can achieve what you want only with the _.merge method which recursively merges two objects.
So you just need to create an object that has the key of the item you want to update, and merge it with the previous state.
It'd look like this:
case "UPDATE_BOOK":
  let updates = {[action.payload.id]: action.payload};
  return _.merge(state, updates)

And this should do the trick (I have to admit I haven't tested the code)


text:
Q: simple lookups in Data Access Layer, Business Layer or in UI? ASP .NET MVC4
Class #1:
public class F61BPROD
{
    public int WPDOCO { get; set; }
    public string WPDCTO { get; set; }
    public string WPMCU { get; set; }
    public string WPLOCN { get; set; }
    public string WPDCT { get; set; }
    public int WPTRDJ { get; set; }
    public string WPKYPR { get; set; }
    public string WPLITM { get; set; }
    public decimal WPTRQT { get; set; }
    public string WPKYFN { get; set; }
    public string WPLOTN { get; set; }
    public string WPLRP1 { get; set; }
    public string WPLRP2 { get; set; }
    public string WPLRP3 { get; set; }
    public string WPLRP4 { get; set; }
    public string WPLRP5 { get; set; }
    public string WPLRP6 { get; set; }
    public string WPLRP7 { get; set; }
    public string WPLRP8 { get; set; }
    public string WPLRP9 { get; set; }
    public string WPLRP0 { get; set; }
    public string WPFLAG { get; set; }
    public string WPLOT1 { get; set; }
    public string WPLOT2 { get; set; }
}

For one of the properties of Class #1 i need to fetch one of Class #2:
    public class JDEItemBasic
    {
        public int itm { get; set; }
        public string litm { get; set; }
        public string dsc { get; set; }
        public string dsce { get; set; }
        public string ean14 { get; set; }
        public string cc { get; set; }
        public string uom1 { get; set; }
        public string uom2 { get; set; }
        public int uom1ea { get; set; }
        public int bxuom1 { get; set; }
        public int uom1gr { get; set; }
}

There is a DAL that gets the above classes. I need to combine these classes a new class that will have most of the properties of the above classes.
Should i create a third class and do the job in BLL?
or should i do it in UI using LINQ to Entities after i fetch them?

A:
Should i create a third class and do the job in BLL?
or should i do it in UI using LINQ to Entities after i fetch them?

That would depend on where you need this class. If it is for displaying purposes then it should live in the UI. This class even has a name in this case: it's called a view model and is what your controller action could pass to the view after querying your DAL layer and projecting the various results to this view model.


text:
Q: Java Flight Recorder options not working and file is stored only in the end of the duration setting I have a Java process and I start it (as suggested here : parameters for FR) with the options :
-XX:+UnlockCommercialFeatures -XX:+FlightRecorder -XX:StartFlightRecording=duration=2m,filename=myflightrecord.jfr -XX:FlightRecorderOptions=maxsize=100k,maxage=1m
in order to have Flight Recorder information.
I would expect that the maxage=1m would give me only one minute of record, and maxsize=100k the file size wouldnt be larger than 100Kb, but none of them does work as expected.
Another problem that I encounter is that I want the file to be stored every amount of time, lets suppose every one minute. But the file "myflightrecord.jfr" is empty until the duration is reached (2minutes in the example).
Is there any way to make the Flight recorder flush before the end of the duration?
ps: The version of Java I am using is JDK1.8.0_45

A: This is for JDK 7 and JDK 8 (Hotspot), and JDK 5 and 6 (JRockit).
First, maxsize and maxage only works if you have a disk based recording, since the parameters controls how much data to keep on disk.
If you have an in-memory recording (defaultrecording=true,disk=false), the size of the memory buffers depends on the number of threads that are in use, how much memory each thread is allowed to use, number of global buffers etc.
Flight Recorder was designed for large servers with GB of memory and TB of disk, so I don't think the JVM will be able to respect the number you provided, i.e. a single event could be larger than 100 kb, but typically they are about 50-150 bytes.
Second, the name of the parameters (maxsize and maxage) are misleading. It's not the maximum size/age, but the threshold at which the JVM will remove a log file when they are rotated, which typically happens every 12 MB. To minimize overhead the JVM doesn't stop all the threads immediately when the threshold is met, which means  data spills over so in reality it is 12-15 MB. If the system is highly saturated, it could be a lot more, think 30-40 MB.
So setting the maxsize to 100k will not work, you will always get at least 12 Mb,
If you set the maxage to 1 minute you will get data for at least one minute, perhaps more if it can fit in the size of about one log file, 12-15 Mb.
If you have an in-memory recording, the data is copied from the memory buffers to disk when the recording ends. That's why your file is empty. If you want Flight Recorder to write continuously to disk, you should set disk=true.

A: The maxage and maxsize options only apply when you have a continuous recording (= have not set duration). I also think that they are only guidelines, not exact limits.
If you want to get the data flushed to disk for a continuous recording, you can set disk=true, and if you want to specify where the data should end up, you can set repository=path
(I believe the data will only be flushed to disk when the the in memory buffers are full, I'm not sure if it's when the thread local buffers are full, or when the global buffers are full, see slide 13 in this slidedeck for a picture describing this: http://www.slideshare.net/marcushirt/java-mission-control-java-flight-recorder-deep-dive)
See https://docs.oracle.com/javase/8/docs/technotes/tools/windows/java.html
XX:FlightRecorderOptions for more info. You can check the threadbuffersize and globalbuffersize as well.
I know the valid combinations of flags have varied a bit, so the documentation might not be entirely up to date.
Kire Haglin can correct me where I've misunderstood things.


text:
Q: Unhandled exception thrown: read access violation in C++ I am facing the problem. Here is my code.
The visual studio replied "Unhandled exception thrown: read access violation. cur was 0xCDCDCDCD."
for (int i = 0; i < size; i++) {
            fin >> data;
            node* p = new node;
            p->info = data;
            if (head->next == NULL || data <= head->info) {
                p->next = head;
                head = p;
            }
            else {
                node* prev = head;
                node* cur = head->next;
                while (cur != NULL && data > cur->info) { //this is the problem
                    prev = cur;
                    cur = cur->next;
                }

                p->next = prev->next;
                prev->next = p;
            }

The expecatation of this code is insert a node at the end of the linked-list from the file which contain the ordered integer data.
size is the first data of the file.
Like file3.txt:
7
1 2 3 4 5 6 7
the first data I get is size
then I want to make a linked-list order by ascending order.


text:
Q: Xamarin Native map point open infowindow by default Im loading a native map application (android,IOS) with a custom pin location and with a custom marker.What i need is when i load the map i need to open the map pin marker info window by default.
currently what is happening is when user tap the pin info then only the pin info window shows up.
I have seen some code there markerOpt1.showInfoWindow() there is no method like this.
As per the documentation  i know only one info window can pops up.In my scenario only one pin is there
Android implementation
public void OnMapReady(GoogleMap map)
{
    MarkerOptions markerOpt1 = new MarkerOptions();
    markerOpt1.SetPosition(new LatLng(50.379444, 2.773611));
    markerOpt1.SetTitle("Vimy Ridge");

    var bmDescriptor = BitmapDescriptorFactory.DefaultMarker (BitmapDescriptorFactory.HueCyan);
    markerOpt1.InvokeIcon(bmDescriptor);

    map.AddMarker(markerOpt1);
}

I have write custom renders for Android native application markers and ios mkmapview how can i show up the information view when loading the map

A: Here is the official sample of customrenderers-map-pin, to open infowindow by default,
In iOS:
    protected override void OnElementChanged(ElementChangedEventArgs<View> e)
    {
        base.OnElementChanged(e);

        //...

        if (e.NewElement != null)
        {
            var formsMap = (CustomMap)e.NewElement;
            var nativeMap = Control as MKMapView;
            customPins = formsMap.CustomPins;

             //...
             //add MapLoaded  Event
             nativeMap.MapLoaded += NativeMap_MapLoaded;
        }
    }

And in NativeMap_MapLoaded:
private void NativeMap_MapLoaded(object sender, EventArgs e)
{
    annotationView.SetSelected(true,true);
}

In Android, try this:
protected override void OnMapReady(GoogleMap map)
{
    base.OnMapReady(map);

    MarkerOptions markerOpt1 = new MarkerOptions();
    markerOpt1.SetPosition(new LatLng(50.379444, 2.773611));
    markerOpt1.SetTitle("Vimy Ridge");

    var bmDescriptor = BitmapDescriptorFactory.DefaultMarker(BitmapDescriptorFactory.HueCyan);

    Marker marker =  map.AddMarker(markerOpt1);
    marker.ShowInfoWindow();
}


text:
Q: Get Python to raise MemoryError instead of eating all my disk space If I run a Python program with a memory leak, I would normally expect the program to eventually die with MemoryError.  But instead, what happens is that all the virtual memory is used until my disk runs out of space.  I am running Mac OS X 10.8 on a retina MacBook Pro.  My computer generally has between 10GB to 20GB free.  Mac OS X is smart enough to not die completely when the disk runs out of space (rather, it gives me a dialog letting me force quit my GUI programs).
Is there a way to make Python just die when it runs out of real memory, or some reasonable amount of virtual memory?  This is what happens on Linux, as far as I can tell.  I guess Mac OS X is more generous than Linux with virtual memory (the fact that I have an SSD might be part of this; I don't know just how smart OS X is with this stuff).  Maybe there's a way to tell the Mac OS X kernel to never use so much virtual memory that leaves less than, say, 5 GB free on the hard drive?

A: Python Level
According to this post, resource.setrlimit() maybe what you need.
Example
#!/usr/bin/python

import resource
import sys
import signal
import time

import os

soft, hard = resource.getrlimit(resource.RLIMIT_STACK)
print 'Soft limit starts as  :', soft

# Use env MY_PY_SET_LIMIT to control limit value
# If MY_PY_SET_LIMIT is not set, RLIMIT_STACK will not change
MY_PY_SET_LIMIT = os.getenv('MY_PY_SET_LIMIT')

if MY_PY_SET_LIMIT != None :
  resource.setrlimit(resource.RLIMIT_STACK, (int(MY_PY_SET_LIMIT), int(MY_PY_SET_LIMIT)))

soft, hard = resource.getrlimit(resource.RLIMIT_STACK)
print 'Soft limit changed to :', soft

TMP = ""

for i in range(10240):
  TMP += "0123456789"
  print len(TMP)

System Level
For Linux, it is actually answer multiple times before on various "board" of stackexchange and other sites too. The best answer I found is here which contain an example.
The answer is use ulimit -v < kByte >. For example, limiting the vm to 10M:
ulimit -v 10240

However, on OS X there are indication (here & here) that ulimit maybe ignore. Those links are very old. I am not sure if situation change in more recent OS X releases.
There is this post for OS X to use launchd conf. It suggest using a Stack section in a plist config
<key>SoftResourceLimits</key>
<dict>
    <key>Stack</key>
    <integer>10000000000</integer>
</dict>

Or with /etc/launchd.conf
launchd.conf
umask 002
limit stack 67104768 67104768
limit maxproc 3400 4500
limit maxfiles 256 unlimited
setenv PATH /opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin

PS: according to Mountain Lion man launchd.conf(5) per user launchd.conf is not support
 $HOME/.launchd.conf  Your launchd configuration file (currently unsupported).


text:
Q: supervisor field on the page of the title with Beamer I am editing a presentation of a research project, I am wondering if there is a field for "supervisor" on the page of the title, for instance \supervisor(which actually does not work)... If not, where do people conventionally add it?

A: This worked for me:
\author[author1]{author1\\[10mm]{\small Supervisors: supervisor1 \\ \hspace{18mm} supervisor2}}

After substituting the names, you have to find the XXmm yourself by trial and error.

A: A field like \supervisor doesn't exist in beamer. If you want to insert additional field to the titlepage you can create your own titlepage.
In other way is to use the optional argument of \author and co.
\author[<used as label>]{<used on titelpage>}

A: I think this might work:
\documentclass{beamer}
\usepackage[utf8]{inputenc}
\usetheme{Antibes}
\setbeamertemplate{footline}[page number]
\setbeamertemplate{navigation symbols}{}
\setbeamertemplate{headline}{}

\title{Thermal Hydraulics}

\author{{John Williams} & {Johanna Williams} \\
{\and} \\
{\textit{Supervisors}} \\
{Jack Williams} \\ {Jackie Smith}}

\institute{LaTeX University}
\date{\today}

\begin{document}

\frame{\titlepage}

\end{document}

I compiled the code on Overleaf and it gave this:

You may also put the authors on separate lines, replacing the \author command with:
\author{{John Williams} \\ {Johanna Williams} \\
{\and} \\
{\textit{Supervisors}} \\
{Jack Williams} \\ {Jackie Smith}}

which will give you:

A: As already mentioned by Marco Daniel, a field \supervisor does not exist in beamer. However, I would like to follow a different approach.
mregine on latex-community mentioned that you can just include the supervisors in the \author command which also lets you associate the affiliations to the supervisors. To make only your name appear in the footline, use the optional argument of the \author command. Thus, I would suggest a command like the following:
\author[author1]{author1\inst{1}\\[1ex]  {\small supervisor1\inst{1,2}}

I hope this is close to what you want.


text:
Q: go routine not printing `shutdown msg` after closing channel `done` Two go routines reading from the same channel. The first go routine never prints its shutdown message after the done channel is closed, while the second go routine always does.
Why is the message from the first go routine not printing and is the method even returning?
main.go
func main() {
done := make(chan bool)
c := make(chan os.Signal, 1)

cameras := client.CameraConfig()
client.DrawUserControls(cameras)

operator := client.NewOperator(cameras)
go operator.UserInputListener(done)
go operator.ParseAndExecuteUserCommand(done)

signal.Notify(c, os.Interrupt)
for range c {
    close(done)
    break
}

log.Println("Interrupt signal received. Shutting client down....")
time.Sleep(5 * time.Second)
}

client.go
func (o *Operator) UserInputListener(done <-chan bool) {
    reader := bufio.NewReader(os.Stdin)
    for {
        select {
        case <-done:
            log.Println("Keyboard listener shutting down.") // <-- this never prints
            return
        default:
            line, _, err := reader.ReadLine()
            if err != nil {
                log.Println(err)
            }

            data := strings.Split(string(line), "")

            id, err := strconv.Atoi(data[1])
            if err != nil {
                log.Println(err)
                continue
            }

            switch data[0] {
            case "b":
                o.Controls <- Ctrl{
                    Identifier: id,
                    Ctrl:       "run",
                }
            case "t":
                o.Controls <- Ctrl{
                    Identifier: id,
                    Ctrl:       "terminate",
                }
            case "r":
                o.Controls <- Ctrl{
                    Identifier: id,
                    Ctrl:       "record",
                }
            case "s":
                o.Controls <- Ctrl{
                    Identifier: id,
                    Ctrl:       "stop",
                }
            }
        }
    }
}

func (o *Operator) ParseAndExecuteUserCommand(done <-chan bool) {
    for {
        select {
        case <-done:
            log.Println("Command operator shutting down.")
            return
        case ctrl := <-o.Controls:
            switch ctrl.Ctrl {
            case "run":
                o.Room[ctrl.Identifier].Run()
            case "terminate":
                o.Room[ctrl.Identifier].Close()
            case "record":
                o.Room[ctrl.Identifier].Write()
            case "stop":
                o.Room[ctrl.Identifier].Stop()
            }
        }
    }
}

A: The reason is because you have created synchronous channel and you push here 1 message and then you could read it only once as well. That is because you get only 1 (random) read from done channel.
The way you can shut down your goroutines is to use WaitGroup:
main.go:
var (
    done            chan bool
)

func main() {
    cameras := client.CameraConfig()
    client.DrawUserControls(cameras)
    operator := client.NewOperator(cameras)

    done = make(chan bool, 1)
    wg := &sync.WaitGroup{}
    wg.Add(2)
    go operator.UserInputListener(done, wg)
    go operator.ParseAndExecuteUserCommand(done, wg)

    handleShutdown()
    wg.Wait()
}

func handleShutdown() {
    ch := make(chan os.Signal, 1)
    go func() {
        <-ch //wait for application terminating
        log.Println("Shutdown received.")
        close(done)
    }()
    signal.Notify(ch, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
}

client.go:
func (o *Operator) UserInputListener(done <-chan bool, wg *sync.WaitGroup) {
    defer wg.Done()
    for {
        select {
        case <-done:
            log.Println("Keyboard listener shutting down.")
            return
        ........
        }
    }
}

func (o *Operator) ParseAndExecuteUserCommand(done <-chan bool, wg *sync.WaitGroup) {
    defer wg.Done()
    for {
        select {
        case <-done:
            log.Println("Command operator shutting down.")
            return
        ........
        }
    }
}

Use this link for details

A: The reason UserInputListener is not entering case <-done: is because it is stuck waiting for some input at this line:
line, _, err := reader.ReadLine()

This line is blocking!
What is the solution for this type of problem?
This is not easy.
Read Routine
You could use another go routine to do the reading, send the data into a channel that you read from in the select where you also read from the done channel. That would properly close the UserInputListener but leave the other goroutine to not be closed properly. But maybe that does not matter as much...?
func (o *Operator) UserInputListener(done <-chan bool) {
    // channel with some buffer so reader doesn't have to wait (so much)
    ch := make(chan string, 10)
    go func() {
        reader := bufio.NewReader(os.Stdin)
        for {
            line, _, err := reader.ReadLine()
            if err != nil {
                log.Println(err)
                // stop on error?
                // return
            }
            ch <- string(line)
        }
    }()

    for {
        select {
        case <-done:
            log.Println("Keyboard listener shutting down.") // <-- this never prints
            return
        case line:= <-ch:
            data := strings.Split(line, "")

            id, err := strconv.Atoi(data[1])
            if err != nil {
                log.Println(err)
                continue
            }

            switch data[0] {
            case "b":
                o.Controls <- Ctrl{
                    Identifier: id,
                    Ctrl:       "run",
                }
            case "t":
                o.Controls <- Ctrl{
                    Identifier: id,
                    Ctrl:       "terminate",
                }
            case "r":
                o.Controls <- Ctrl{
                    Identifier: id,
                    Ctrl:       "record",
                }
            case "s":
                o.Controls <- Ctrl{
                    Identifier: id,
                    Ctrl:       "stop",
                }
            }
        }
    }
}

Close Reader Source
You could also try to close whatever the reader is reading from. I have already used this solution in other contexts like reading from serial devices.
This does not work with os.Stdin however as JimB pointed out to me. os.StdIn.Close() will block as it waits for the reader to finish.


text:
Q: Running multiple Applescripts in order in Automator I am trying to automate this process.
step 1: change system date to a specific date.
step 2: open an application.
step 3: change system date back to normal.
Now on Automator, I have three apple scripts placed like this.

on run {input, parameters}

tell application "Terminal"
    do script with command "sudo date 082704002018"
    activate
end tell

delay 1
tell application "System Events"

    keystroke "mypassword" & return
    delay 3

end tell

end run

on run {input, parameters}

tell application "Terminal"
    do script with command "open -a applicationName"
    activate
end tell

end run

on run {input, parameters}

tell application "Terminal"
    do script with command "sudo ntpdate -u time.apple.com"
    activate
end tell

delay 1
tell application "System Events"

    keystroke "mypassword" & return
    delay 3

end tell

end run

The problem is that Automator only runs the first code. I'm not sure how to make it run all the codes in order.
Sorry if this is a stupid question. I am completely new to automator and applescript.
Thank you

A: I'm not quite sure why you chose to use three separate AppleScripts.  You can combine them all into one AppleScript as I have done in this following example.  I'm not quite sure why you used the "activate" commands. I don't think they are necessary so I removed those lines of the code. Anyway, this following code should work for you…
tell application "Terminal"
    do script with command "sudo date 082704002018"
end tell
delay 1
tell application "System Events"
    keystroke "mypassword" & return
    delay 3
end tell
tell application "Terminal"
    do script with command "open -a applicationName"
    delay 1
    do script with command "sudo ntpdate -u time.apple.com"
end tell
delay 1
tell application "System Events"
    keystroke "mypassword" & return
    delay 3
end tell

Alternately, launching Terminal app to run shell scripts is not necessary all the time as you can run  shell scripts in AppleScript by using the "do shell script" command.  This following applescript code is your code using only eight lines of code.
do shell script "sudo date 082704002018"
tell application "System Events" to keystroke "mypassword" & return
delay 3
do shell script "open -a applicationName"
delay 1
do shell script "sudo ntpdate -u time.apple.com"
delay 1
tell application "System Events" to keystroke "mypassword" & return

If my versions of your code throw errors, it may be necessary to adjust the delay commands or re-insert the activate commands
If you are hell-bent on using your version of the code and three separate Applescripts, just remove the  on run {input, parameters} and end run lines of code from each AppleScript and that should eliminate your problem


text:
Q: Go regexp FindAllStringSubmatch here is my snippet of code in Go which can be found here http://play.golang.org/p/L1AcgHf3E4.
package main

import (
    "fmt"
    "regexp"
)

func main() {
    reg := regexp.MustCompile("([0-9]+[dh]){2}")
    str := "2d3h5d"

    fmt.Println(reg.FindAllStringSubmatch(str, -1))

}

I'd expect the result to be [[2d3h 3h] [3h5d 5d]], but it turned out to be [[2d3h 3h]]. Can you explain why? Thanks in advance.

A: the reason is that you can not obtain overlapping results. With regex engines that support lookahead you can use the trick: (?=([0-9]+[dh]){2}) but go language does not support it.
If you want to obtain all results, I suggest you to use FindAllStringIndex() with ([0-9]+[dh]) and then determine all contiguous substrings with the offset.


text:
Q: Declaration of __invoke in viewhelper should be compatible with parents class Please help me, I am newbie with zend framework and OPP.
I am building a viewhelper class, which contain a input hidden (called: ITinputhidden) extends from FormHidden (use Zend\Form\View\Helper\FormHidden and use Zend\Form\Element). I also declared the class in Module.php (function: getViewHelperConfig). But there is a warning when access:
Strict Standards: Declaration of ITEquip\Form\View\Helper\FormHidden::__invoke() should be compatible with Zend\Form\View\Helper\FormInput::__invoke(Zend\Form\ElementInterface $element = NULL) in C:\xampp\htdocs\itequip.mvn\library\ITEquip\Form\View\Helper\FormHidden.php on line 10
Maybe cause is method magic __invoke in my view helper don't compatible with __invoke in Zend. (In __invoke method of viewhelper, I using 2 varibales: $name and $value , but there is only one variable ($element = NULL) in __invoke of Zend\Form\ElementInterface. But I can't fix it.
How will I do?
Please see my code:
My viewhelper file (FormHidden.php):
namespace ITEquip\Form\View\Helper;

use Zend\Form\View\Helper\FormHidden as ZendFormHidden;
use Zend\Form\Element;

class FormHidden extends ZendFormHidden
{
   public function __invoke($name,$value) {
    $element = new Element\Hidden($name);
    $element->setValue($value);
    return $this->render($element);
   }
}

Module.php file
public function getViewHelperConfig(){
    return array(
            'invokables'    =>array(
                'ITFormHidden'  => '\ITEquip\Form\View\Helper\FormHidden',
            )
    );
}

Index.phtml file
<?php
//CREATE INPUT HIDDEN
$inputHiddenOrder   = $this->ITFormHidden('order','ASC');
$inputHiddenOrderby = $this->ITFormHidden('order_by','colorcode');

$strInputHidden     = $inputHiddenOrder. $inputHiddenOrderby;
echo $strInputHidden;
?>

Please help me.
Thank you in advanced.


text:
Q: Why can we take the following sequence of compact sets? I'm studying the proof which goes as follows. Let $\mu$ be a tight Borel probability measure on $L^\infty(X)$, where the set $X$ is not necessary countable. Take $(K_n)_{n=1}^\infty$, an increasing sequence of compact sets in this space with $\mu(\bigcup_{n=1}^\infty K_n)=1$.
How do I know that such sequence exists?
By definition, $\mu$ is tight if $\forall\varepsilon>0,\exists K\subset L^\infty(X)$ compact such that
$$\mu(K)>1-\varepsilon$$
How can I relate this to $(K_n)$?

A: By definition of "tight", for every $n$, taking $\epsilon = 1/k$ there exists a compact set $E_k$ such that $\mu(E_k) > 1 - 1/k$.  Set $K_n = \bigcup_{k=1}^n E_k$, which is also compact, and we have $K_1 \subset K_2 \subset \cdots$.  Note that $E_n \subset K_n$, so $\mu(K_n) > 1-1/n$. Then $\mu(\bigcup_{n=1}^\infty K_n) > 1-1/n$ for every $n$, so $\mu(\bigcup_{n=1}^\infty K_n)=1$.


text:
Q: How to make SQL insert safely? I am creating a Hotel Booking System for the Android application.
I was thinking about how to implement a safe way to insert a booking into my database. The request will be sent from the app to the MySQL database (which is hosted on a web server) via my web service.
When I create a booking I insert the: CustomerID, HotelID, RoomID (via a nested select statement to find an available room), checkInDate and checkOutDate.
However, how can I ensure that two different people won't book the same/last room if they both hit 'book now' at roughly the same time. I thought about using Synchornisedfor the java method but will that make any difference if a range of different users on different mobiles try to make a booking?

A: I don't think that you're asking about threading as much as avoiding a race condition.
Not knowing anything about your architecture, one way to avoid such a race is to set a timestamp when each user hits the 'book now' button and pass it as a field in the transaction.  The application server would then sort all the entries in its queue according to the timestamp, as opposed to simply accepting them in the order they arrive.

A: What you are looking for is transactions.
Using transactions you will be able to isolate access to a given set of records into a single, atomic logical entity. Any operation of a certain complexity affects multiple rows, columns and even tables, or needs multiple (atomic or non-atomic) statements to complete. A transaction is a mechanism to ensure logical consistency of your data even if any of these operations fails. In that case, the incomplete transaction is rolled back, otherwise the transaction is committed.
And these are exactly the both possible outcomes with transactions: commit or rollback. In pseudo code it looks like this:
begin transaction
try {
  required operations to reserve a room for a given time frame

  if( success)
      commit transaction
  else
      rollback transaction

} catch {
  rollback transaction
}

Synchronizing in Java is certainly possible, but it has several major drawbacks:

*

*it prevents you from scaling the application, because it affects only the current process.

*it also prevents you from extending the solution, e.g. by sharing the data with associated programs

*a database transaction is designed to handle crashes without producing inconsistent data

A: You need to create a unique key {room number, date} such that a room can only have one booking per date. Then a client booking becomes an insert of as many rows as there are days in the booking, carried out within a transaction.
Threads really have little to do with it.


text:
Q: (shell) How to remove strings from one file which can be found in another file? file1.txt
aaaa
bbbb
cccc
dddd
eeee

file2.txt
DDDD
cccc
aaaa

result
bbbb
eeee

If it could be case insensitive it would be even more great!
Thank you!

A: grep can match patterns read from a file, and print out all lines NOT matching that pattern. Can match case insensitively too, like
grep -vi -f file2.txt file1.txt

Excerpts from the man pages:
SYNOPSIS
   grep [OPTIONS] PATTERN [FILE...]
   grep [OPTIONS] [-e PATTERN | -f FILE] [FILE...]

   -f FILE, --file=FILE
          Obtain  patterns  from  FILE,  one  per  line.  The empty file contains zero
          patterns, and therefore matches nothing.  (-f is specified by POSIX.)ns zero
          patterns, and therefore matches nothing.  (-f is specified by POSIX.)
   -i, --ignore-case
          Ignore case distinctions in both the PATTERN and the input  files.   (-i  is
          specified by POSIX.)ions in both the PATTERN and the input  files.   (-i  is
          specified by POSIX.)
   -v, --invert-match
          Invert  the  sense  of  matching,  to  select  non-matching  lines.   (-v is
          specified by POSIX.)of  matching,  to  select  non-matching  lines.   (-v is
          specified by POSIX.)

A: From the top of my head, use grep -Fiv -f file2.txt < file1.txt.
-F no regexps (fast)
-i case-insensitive
-v invert results
-f <pattern file> get patterns from file

A: $ grep -iv -f file2 file1
bbbb
eeee

or you can use awk
awk 'FNR==NR{ a[tolower($1)]=$1; next }
{
  s=tolower($1)
  f=0
  for(i in a){if(i==s){f=1}}
  if(!f) { print s }
} ' file2 file1

A: ghostdog74's awk example can be simplified:
awk '
    FNR == NR { omit[tolower($0)]++; next }
    tolower($0) in omit {next}
    {print}
' file2 file1

A: For various set operations on files see:
http://www.pixelbeat.org/cmdline.html#sets
In your case the inputs are not sorted, so
you want the difference like:
sort -f file1 file1 file2 | uniq -iu


text:
Q: How to Install the app twice without interference in android? I have an Android app (let's called X), I want to create a second app X2 but based on the other app. So I changed the manifest application name property to X2 also I changed the package name...but still when I install X2, app X is erased!
What properties should I change so I can install the two app independently on one devices. I'm working on eclispe.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.company.app1"
    android:versionCode="1"
    android:versionName="1.0" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name1"
        android:theme="@style/AppTheme" >

after change.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.company.app2"
android:versionCode="1"
android:versionName="1.0" >

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name2"
    android:theme="@style/AppTheme" >

A: Well it worked on other device with more recent platform ! Anyway the proper response will be you just have to change the name and the package of the application.
EDIT 1: Now if you are using Android Studio use applicationIdSuffix to have one app for each flavor.
debug {
        applicationIdSuffix ".debug"
    }

Read more here developer.android.com

A: also change the package name in gradle script build.gradle module it will work
defaultConfig {
    applicationId "com.me.mesurvey" //put your package name here//
    minSdkVersion 14
    targetSdkVersion 19
}

A: I needed such tool because client wanted to be able use beta and release version of the app in the same time.
I am changing main namespace of the APK to achieve this using apktool.
I follow these steps:

*

*decompile apk using apktool java -jar apktool.jar d -o out -f my-app.apk

*replace com.mainnamespace to com.mainnamespacebeta in all files in out directory

*rename directory out/smali/com/mainnamespace to out/smali/com/mainnamespacebeta

*compile apk again java -jar apktool.jar b -o ./debug.apk -f ./out

*sign the apk with the new key using jarsigner. jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore key.keystore ./debug.apk "password" -storepass "password" -keypass "password"
Here is the manual how to sign the apk to get key.keystore - http://developer.android.com/tools/publishing/app-signing.html
I have also created simple script for linux - https://gist.github.com/vavrecan/8596303

A: step 1: select(give a click on) your app main package and click Shift+f6 and change the package name
Step 2: goto build.gradle and change the applicationId to new package name as below
         defaultConfig {
    applicationId "com.sample.main"//give your new package name

    minSdkVersion 15

    targetSdkVersion 25

}

Step 3: Clean the project
Step 4: Run the project and see it will work for sure
Happy Coding.....


text:
Q: Masking two images and merge into one image I am working on a project where I am using different masks on two different pictures and than would like to combine them into one picture.  So far I have the masking (albeit it has some errors on the edges) and now I am trying to combine the images.

*

*how can I improve the masking so the result on has no errors on the edges (see images )

*how do I effectively combine the images into one to result in the third image?  I have been trying to use some transparency effects but it hasn't worked.  What I am trying to do is merge the two images so they form a complete circle.  If any of the original images are needed please let me know

    from PIL import Image

    # load images
    img_day  = Image.open('Day.jpeg')
    img_night  = Image.open('Night_mirror.jpg')
    night_mask = Image.open('Masks/12.5.jpg')
    day_mask = Image.open('Masks/11.5.jpg')

    # convert images
    #img_org  = img_org.convert('RGB') # or 'RGBA'
    night_mask = night_mask.convert('L')    # grayscale
    day_mask = day_mask.convert('L')

    # the same size
    img_day  = img_day.resize((750,750))
    img_night  = img_night.resize((750,750))
    night_mask = night_mask.resize((750,750))
    day_mask = day_mask.resize((750,750))
    # add alpha channel

    img_day.putalpha(day_mask)
    img_night.putalpha(night_mask)
    img_night = img_night.rotate(-170)

    # save as png which keeps alpha channel
    img_day.save('image_day.png')
    img_night.save('image_night.png')
    img_night.show()
    img_day.show()

Any help is appreciated

A: The main problem are the (JPG) artifacts in your masks (white line at the top, "smoothed" edges). Why not use ImageDraw.arc to generate the masks on-the-fly? The final step you need is to use Image.composite to merge your two images.
Here's some code (I took your first image as desired output, thus the chosen angles):
from PIL import Image, ImageDraw

# Load images
img_day = Image.open('day.jpg')
img_night = Image.open('night.jpg')

# Resize images
target_size = (750, 750)
img_day = img_day.resize(target_size)
img_night = img_night.resize(target_size)

# Generate proper masks
day_mask = Image.new('L', target_size)
draw = ImageDraw.Draw(day_mask)
draw.arc([10, 10, 740, 740], 120, 270, 255, 150)
night_mask = Image.new('L', target_size)
draw = ImageDraw.Draw(night_mask)
draw.arc([10, 10, 740, 740], 270, 120, 255, 150)

# Put alpha channels
img_day.putalpha(day_mask)
img_night.putalpha(night_mask)

# Compose and save image
img = Image.composite(img_day, img_night, day_mask)
img.save('img.png')

That'd be the output:

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.5
Pillow:      8.0.1
----------------------------------------

A: To you points:

*

*You problem with masking simply orginiates from the fact that your masks are not perfect. Open them in paint and you will see that on the top side, there is a white line remaining. Just use the fill in tool to fill that white part with black. Afterwards it should work.

*I suggest mirroring your image horizontally instead of rotating it. You can use PIL.ImageOps.mirror for that. Then you paste one image onto the other image using img.paste(). As a second argument, you give the coordinates where the image should be pasted onto the other, and very importantly, as a third argument, you specify a transparency mask. Since your image already has an alpha channel, you can just use the same image as a mask. PIL will automatically use it's alpha channel for masking. Note that I had to adjust the position of pasting by 4 pixels to overlap the images correctly.
from PIL import Image, ImageOps

# load images
img_day  = Image.open('day.jpg')
img_night  = Image.open('night.jpg')
night_mask = Image.open('night_mask.jpg')
day_mask = Image.open('day_mask.jpg')

# convert images
#img_org  = img_org.convert('RGB') # or 'RGBA'
night_mask = night_mask.convert('L')    # grayscale
day_mask = day_mask.convert('L')

# the same size
img_day  = img_day.resize((750,750))
img_night  = img_night.resize((750,750))
night_mask = night_mask.resize((750,750))
day_mask = day_mask.resize((750,750))
# add alpha channel

img_day.putalpha(day_mask)
img_night.putalpha(night_mask)
img_night = ImageOps.mirror(img_night)

img_night.paste(img_day, (-4, 0), img_day)
img_night.save('composite.png')

Result:


text:
Q: How to start Snipping Tool from PowerShell? I am trying to use the Snipping Tool from the command line.
I can run it from the Run box, but despite how much I try and different ways to do it I cannot open up the Snipping Tool on Windows 7 from PowerShell. I am sick of having to use the mouse to open up the Snipping Tool.
Start process:
[System.Diagnostics.Process]::Start("C:\Windows\system32\SnippingTool.exe")

Call operator:
& "C:\Windows\system32\SnippingTool.exe"

Dot-sourcing:
. C:\Windows\system32\SnippingTool.exe

Using Inovke-Item:
ii "C:\Windows\system32\SnippingTool.exe"

Change to the directory:
PS C:\Windows\system32> ./SnippingTool.exe

A: Try using Start-Process "c:\windows\sysnative\snippingtool.exe"
-Edit to add, if you run the x86 (32-bit) powershell console, you'll have to use SysNative because on a 64-bit system, the C:\Windows\System32 is actually 64-bit processes.  So open the x64 Powershell console, and C:\Windows\System32 will work as expected.  Additionally, C:\Windows\Syswow64 contains 32 bit binaries.  Be safe and use C:\Windows\SysNative and you won't have to think about this type of thing.

A: This works for me.
PS C:\> cd C:\Windows\System32
PS C:\Windows\System32> .\SnippingTool.exe

If you are using PowerShell ISE, try opening a new instance and running it.
Further check if the file is located there.


text:
Q: Does Ubuntu support the CDMA version of the Galaxy Nexus? Looking at the list of supported devices, I see that GSM Galaxy Nexus devices (takju and yakju) are supported but nothing about the CDMA (toro/Verizon or toroplus/Sprint) versions of the Galaxy Nexus.
Are these devices (toro and toroplus) so very different from takju or yakju (other than radios)? Will I be able to flash Ubuntu Touch to a toro or toroplus device?
Thank you for your input.

A: Heres a port for Toro, the call and data isn't working but Im sure it will soon. Just factory reset and flash both files with twrp or cwm.
http://forum.xda-developers.com/showthread.php?s=546095c024512bf2b366ddf1271e6e13&t=2159515
Have fun.


text: Q: Is it possible to add hints and auto-completion in .properties file? I recently started to learn Hibernate for Java (pretty cool thing btw), and i discovered an interesting feature in IntelIJ. If you put a certain line in configs .xml file, the IDE will give you hints to a certain properties. I wanted to configure my SQL connection via .properties instead of .xml file. So i wonder, is it possible to do such thing with properties file, to add autocompletion and hints in .properties file?


text:
Q: .NET Core MVC Bootstrap "Collapse" not working I'm using it just as described in the docs but I'm not seeing any results. Any ideas?
Index.cshtml:

@Html.DisplayFor(modelItem => post.Title)

submitted at @Html.DisplayFor(modelItem => post.CreationDate) by @Html.DisplayFor(modelItem => post.OriginalPoster)

    <button type="button" class="btn btn-outline-primary btn-sm" data-bs-toggle="collapse" data-bs-target="#postContent"
            aria-expanded="false" aria-controls="postContent">+</button>
    <button type="button" class="btn btn-outline-primary btn-sm">comments</button>
    <button type="button" class="btn btn-outline-primary btn-sm">share</button>
    <button type="button" class="btn btn-outline-primary btn-sm">save</button>
    <button type="button" class="btn btn-outline-primary btn-sm">hide</button>

        @Html.DisplayFor(modelItem => post.Content)

A: Be sure use Bootstrap v5.0,because it used data-target instead of data-bs-target before v5.0:
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">

Also, aria-controls,data-bs-target and idare all the same(postContent),you need distinguish them like below:
@model IEnumerable<YourModel>

@{int i = 0; }        //add this

@foreach (var post in Model)
{

@Html.DisplayFor(modelItem => post.Title)

submitted at @Html.DisplayFor(modelItem => post.CreationDate) by @Html.DisplayFor(modelItem => post.OriginalPoster)

        <button type="button" class="btn btn-outline-primary btn-sm" data-bs-toggle="collapse" data-bs-target="#postContent_@i"
                aria-expanded="false" aria-controls="postContent_@i">
            +
        </button>
        <button type="button" class="btn btn-outline-primary btn-sm">comments</button>
        <button type="button" class="btn btn-outline-primary btn-sm">share</button>
        <button type="button" class="btn btn-outline-primary btn-sm">save</button>
        <button type="button" class="btn btn-outline-primary btn-sm">hide</button>

            @Html.DisplayFor(modelItem => post.Content)

    i++;
}

Result:

A: ASP.NET Core 3.1 comes with Bootstrap 4 by default.
When you lookup documentation on the Bootstrap site, as of this time, Bootstrap 5 documentation is shown by default.
So when using the Bootstrap documentation, use the appropriate version. See for example, the documentation for Collapse in Bootstrap 4:
https://getbootstrap.com/docs/4.6/components/collapse/
As shown there and as Rena points out, Bootstrap 4 uses data-toggle instead of data-bs-toggle.
So you may not need to upgrade to Bootstrap 5. I would recommend simply referencing the Bootstrap 4 documentation.


text:
Q: Python write complex nest list into file as it is I trying to write complex nested list into file as it is,
so this is my list format
list=[[x number of elements],'a','b','c'],[y number of elements],'d',e',f']]
I am trying to write this in file as it is
[[x number of elements],'a','b','c'],[y number of elements],'d',e',f']]
So please help me out!

A: If you want to ensure the list can be read again, and you're sure it only contains simple Python types (lists, dictionaries, strings, and numbers), then you can do something like this:
import json
with open('output.txt', 'w') as out_file:
    json.dump(your_list, out_file)

To pull it back into Python, you can do this:
import json
with open('output.txt', 'r') as in_file:
    your_list = json.load(in_file)

A: Ignoring that your list is not correct one, you can do this with:
s = [[[1, 3, 4],'a','b','c'],[4, 5],'d','e','f']
text_file = open("Output.txt", "w")
text_file.write(str(s))
text_file.close()

Thus simply converting the list to a string and saving it.


text:
Q: Having issue uploading image using Alamofire and Swift 4 I am trying to upload image from gallery to server via my app. Here is my code :
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    if let userID:String = userDefaults.string(forKey: "userID"){

        let URL: String = "HERE_IS_URL"
        let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage

        let imageData = UIImageJPEGRepresentation(chosenImage, 1.0)
        dismiss(animated: true, completion: nil)

        userProfilePicture.image = chosenImage
        userProfilePicture.contentMode = .scaleToFill

        let head: HTTPHeaders = [
            "Content-type": "multipart/form-data",
            "key": "key"
        ]

        self.alamoManager?.upload(multipartFormData: { (multipartFormData) in

            if let data = imageData{
                multipartFormData.append(data, withName: "image", fileName: "image.png", mimeType: "image/png")
            }

        }, usingThreshold: UInt64.init(), to: URL, method: .get, headers: head) { (result) in
            switch result{
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    print("response: \(response)")
                    if let err = response.error{
                       print(err)
                        return
                    }
                }
            case .failure(let error):
                print("Error in upload: \(error.localizedDescription)")

            }
        }

     }

}

After selecting image from gallery , i set the image in imageview. Api response is this :

response: FAILURE: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x608000245760 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=MY_URL, NSErrorFailingURLKey=MY_URL, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=The request timed out.}

I am using Swift 4, Xcode 9. Please let me know what I am doing wrong?

A: Here is my working code for image upload with alamofire(swift 4).
  func uploadImage(userImage : UIImage?,withCompletionHandler:@escaping (_ result: Any) -> Void){

    Alamofire.upload(
        multipartFormData: { MultipartFormData in
            if((userImage) != nil){
                MultipartFormData.append(UIImageJPEGRepresentation(userImage!,  0.025)!, withName: "your_tag", fileName: "imageNew.jpeg", mimeType: "image/jpeg")
            }

    }, to: "your_url_here") { (result) in

        switch result {
        case .success(let upload, _, _):

            upload.responseJSON { response in
               // getting success
            }

        case .failure(let encodingError): break
            // getting error
        }

    }
}

A.F.A.I.K.
There should be three possibilities.
1) Image type may be mis-match(eg. extension should be acceptable with back-end).
2) Image size matters.
3) You need to send image with proper key_tag.


text:
Q: Adding tables in Hive experiencing HCatClient error I am running Hortonworks 2.2 sandbox on a Windows 7 host machine. I have allocated 2GB of memory to the virtual machine. Every time I try to create a table, I get the following error:

HCatClient error on create table: {"statement":"use default; create table kjdrg(a bigint, b bigint, c bigint) comment 'k' row format delimited fields terminated by ',';","error":"unable to create table: kjdrg","exec":{"stdout":"","stderr":"15/07/02 12:55:45 WARN conf.HiveConf: HiveConf of name hive.optimize.mapjoin.mapreduce does not exist\n15/07/02 12:55:45 WARN conf.HiveConf: HiveConf of name hive.heapsize does not exist\n15/07/02 12:55:45 WARN conf.HiveConf: HiveConf of name hive.server2.enable.impersonation does not exist\n15/07/02 12:55:45 WARN conf.HiveConf: HiveConf of name hive.auto.convert.sortmerge.join.noconditionaltask does not exist\nSLF4J: Class path contains multiple SLF4J bindings.\nSLF4J: Found binding in [jar:file:/usr/hdp/2.2.0.0-2041/hadoop/lib/slf4j-log4j12-1.7.5.jar!/org/slf4j/impl/StaticLoggerBinder.class]\nSLF4J: Found binding in [jar:file:/usr/hdp/2.2.0.0-2041/hive/lib/hive-jdbc-0.14.0.2.2.0.0-2041-standalone.jar!/org/slf4j/impl/StaticLoggerBinder.class]\nSLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.\nSLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]\n Command  was terminated due to timeout(60000ms).  See templeton.exec.timeout property","exitcode":143}} (error 500)

How can I address this?

A: Not that it matters to anyone since the question has so low views, still I'm posting the solution that worked for me finally.
So the problem was that using Hcat via browser was using up too much RAM. Use PuTTY to ssh into the hive and then create tables, it works smoothly. No code as there was none involved in solving the problem.
Yay, me! sad


text: Q: Count the per Mouse Click and Keyboard Press in Electron MACOS I created an Electron APP in windows with gkm packages and all functions are working. In MACOS, it needed to allow the app from privacy settings so that the function of the app is working. Is there another way to count the per mouse click and keyboard press of electron app in macOS that not needed to be manually allowed in privacy setting?


text:
Q: Firebase priority and child_moved I pushed an item with server time stamp priority. After that I got a child_added message for just pushed item with priority set to local time stamp.
I was expecting that child_moved should be called when locally cached pushed item priority is synchronized with server, but it's never happened.
What is the right way to be notified about server item timestamp priority sync completed.  What is the point of child_moved in that case?

A: The issue that you described was a bug in a previous version of the Firebase client, but was fixed in v2.0.0, released November 4th, 2014. Check out the https://www.firebase.com/docs/web/changelog.html.
Now, when you have a listener for child_moved events, and invoke setPriority(Firebase.ServerValue.TIMESTAMP) on one of the children, you'll receive two child_moved events: the first for the initial client-only change in priority, and a second after the server has populated the server version and your client has seen the latest value.


text:
Q: Number system Problem $N$ leaves a remainder of $4$ when divided by $33$, what are the possible remainders when $N$ is divided by $55$?
My approach :
Number has to be $33k+4$
Possible remainders will be $(33k+4)/55 = 33k/55 + 4/55 = \text{remainder of $\left(3k/5 + 4/55\right)$} =
\text{remainder of $(3k/5)$ + Remainder of $(4/55)$}$
Since, remainder of $3k/5$ will be $1,2,3,4$
And also remainder of $4/55$ will be $4$
So, remainder can be $5,6,7,8$
I think there is some fundamental logical flaw with my approach.
Please let me know what it is.

A: One approach which is similar to yours and does work:
Let $r$ be the remainder when $N$ is divided by 55. So, $N=33k+4=55j+r$. Subtracting $55j$ from both sides, we get $33k-55j+4=r$ or $11(3k-5j)+4=r$. Since $3k-5j$ could end up being any integer, let it be $0,1,2,3$ or $4$.
$$r=11(0)+4=4$$
$$r=11(1)+4=15$$
$$r=11(2)+4=26$$
$$r=11(3)+4=37$$
$$r=11(4)+4=48$$
Other choices for $3k-5j$ produce remainders that are too large (or too small).
Edit: I should note that being able to choose any integer for $3k-5j$ relies on the observation that $3(2n)-5(n)=n$. So choosing $k=2n$ and $j=n$ allows $3k-5j$ to equal any integer $n$. While $3$ and $5$ are small enough to make this easy to see. For larger integers, you may need the Euclidean algorithm and Bézout's identity.

A: Have you learned about the Chinese Remainder Theorem yet? This problem seems specifically geared towards it. I've never seen remainders calculated the way you have, and it doesn't quite work like that. For example taking $k=1$, $33=\text{remainder}(33/55)\neq \text{remainder}(3/5)=3$, since $33=0\cdot 55+33$ and $3=0\cdot 5+3$ when you use the division algorithm, so you can't just cancel factors. Also, $\text{remainder}(33/55)+\text{remainder}(4/55)\neq \text{remainder}(33/55)$, since otherwise you would have $\text{remainder}(4/55)=0$, but it is in fact $4$.
However, using the Chinese Remainder Theorem, you have a situation like this:
Since $N$ has a remainer of $4$ when divided by $33$, you have $N\equiv 4\pmod{33}$. This implies that $N\equiv 4\equiv 1\pmod{3}$ and more importantly, $N\equiv 4\pmod{11}$. To find the possible remainders of $N$ when divided by $55$, you have to use that fact that $55=5\cdot 11$. Choose possible remainders for $N$ upon division by $5$, and then use the Chinese Remainder Theorem to find the remainders modulo $55$.
Does this help somewhat?

A: HINT $\ $ By the Chinese Remainder Theorem,
$\rm\quad\quad\quad\quad\quad\quad\quad\quad x\equiv r\ (mod\ 55)\ $
$\rm\quad\quad\quad\quad\quad\quad\quad\quad x\equiv 4\ (mod\ 33)\ $
is solvable iff $\rm\ r\equiv 4\ (mod\ 11)\ \ $ since $\rm\ \ 11 = gcd(55,33)$
Hence since $\rm\ \ r = 4 + 11\ k\:\ $ we deduce $\rm\ r = 4,\:15\:,\:\cdots\ (mod\ 55)$

A: N is congruent to 4 mod 33 and the highest common factor of 33 and 55 is 11.
So N is congruent to 4 mod 11 and mod 55 can be anything that has this congruence.
Therefore 4, 15, 26, 37 or 48

A: You need to find all values of $x$ satisfying
                     $33k$ + $4=x$  $mod 55$
for some $k\in N$.  Multiplying both sides by 5 gives us
                      $20=5x$  $mod 55$
Note that this is not the same as $4=x$  $mod 55$ as 5 is not a unit in $Z\over{55Z}$.  As a result, there are multiple solutions for $x$.
As for your method, it's probably not best to work with fractions, especially reduced fractions.  The problem you run into is that $3k/5$ only produces remainders of 1,2,3, or 4 while its obvious that the problem could have much larger remainders (for instance, if $k=1$ the remainder is 37).


text:
Q: Using kubernetes secrets in a configmap I'm using Helm on a Kubernetes cluster and have installed the stable rabbitmq-ha chart. I would like to push data to an exchange in rabbitmq from Logstash. I am trying to use the logstash stable chart.
The rabbitmq-ha chart has created a secret that contains the password to connect to it. I'd like to be able to get that password and include it in the logstash configuration so that logstash can connect to it.
The ConfigMap for logstash is templated using items from the values file.
  outputs:
    main: |-
      output {
        rabbitmq {
          exchange => "exchange_name"
          exchange_type => "fanout"
          host => "rabbitmq-ha.default.svc.cluster.local"
          password => "????"
        }
      }

I don't want to hard-code the password in the values file because that's not great for security and it would mean duplicating the configuration for each environment. I can't see a way to get logstash to read the password from an environment variable.
How do people normally do this?
I could use helm secrets to store the whole outputs configuration and include hard-coded passwords. That would avoid having plain-text passwords in my repository but still doesn't feel like the best way.

A: Turns out that it is possible to get logstash to read values from the environment variables since at least version 5.0 of logstash. https://www.elastic.co/guide/en/logstash/current/environment-variables.html
So my values file can look like
  outputs:
    main: |-
      output {
        rabbitmq {
          exchange => "exchange_name"
          exchange_type => "fanout"
          host => "rabbitmq-ha.default.svc.cluster.local"
          password => "${RMQ_PASSWORD}"
        }
      }

The logstash chart allows environment variables to be added to the statefulset using an extraEnv value. The extraEnv allows values to come from secrets.
  extraEnv:
    - name: RMQ_PASSWORD
      valueFrom:
        secretKeyRef:
          name: rabbitmq-ha
          key: rabbitmq-password


text:
Q: Typo3 Translation in Inline Viewhelper I want to set a translation for my Typo3 template.
But I want a translation with {f:translate ...} of a string within a inline viewhelper like this.
{f:if(condition:"{change.newValue}", then : '{change.newValue}', else:
"{f:translate (key:'pdvcalls_form_fields.deleted_close_date')}")}

But this is not working.
Has anyone a idea what I am doing wrong?
Thanks for your help!

A: You have an extra space before the function paratheses.
{f:if(condition:"{change.newValue}", then : '{change.newValue}', else:
"{f:translate(key:'pdvcalls_form_fields.deleted_close_date')}")}


text:
Q: Select specific text from json string I have Json data returning dates of some events. like this
 [{
       "date": "Wed Nov 25 05:56:48 +0000 2016",
       "date": "Wed Nov 24 05:56:48 +0000 2015",
       "date": "Wed Nov 25 05:56:48 +0000 2015"
    }]

But I want have only "Wed Nov 25" format(day and date may change as json data get updated every time).
 like this
Wed Nov 25
Wed Nov 24
Wed Nov 25

Is there a way of doing that in java(if possible then with regex)?

regards.

A: I can't find the answer to my question, but for the time I have used a trick. I have used the substring concept like,
String timeFeed = gson.toJson(myArrayOfDate);
timeFeed = timeFeed.substring(0,11);

This only give me 12 characters which are Wed Nov 24 format.
NOTE: If anyone have answer for my question please share.


text:
Q: Refer to the same footnote multiple times in Pages '09 I would like to refer to the same footnote multiple times in Pages '09.
What it does now, is create a new (identical except for the little number) footnote. So I have three or four identical footnotes which is a waste of space. it looks like this:

These are the first1, second2 and third3 references, all numbers referring to their own (further identical) footnotes.

I would like to have it like this:

These are the first1, second1 and third1 references, all numbers referring to the same footnote.

A: You will have to use cross reference - there is a special option in the cross reference box that allows you to reference with a footnote of an endnote.
Put your cursor at the position you want to have the reference inserted:

*

*Click on Cross-Reference

*In Reference type choose Endnote/footnote

*Uncheck Insert as hyperlink box

*In Insert reference to choose Endnote/Footnote (formatted)

*Uncheck Include above/below box

*In the box at the bottom choose the endnote/footnote you want to reference

*Click Insert

A: There is actually no such support implemented into pages.
You would have to insert the number manually and superscript it, sad to say. The point is that the way you are trying to use it is improper, as I had to learn.


text:
Q: What does parameter "weight" of Page Rank function in NetworkX do? According to this post, weights of a weighted digraph have an effect on the Page Rank of the graph. I have tried the code in that post:
from networkx.algorithms.link_analysis.pagerank_alg import pagerank_numpy
ddd=nx.DiGraph()
ddd.add_weighted_edges_from([('A','B',0.5),('A','C',0.5)])
print(pagerank_numpy(ddd))
ddd['A']['C']['weight']=1
print(pagerank_numpy(ddd))

>>> {'A': 0.2597402597402597, 'B': 0.37012987012987014, 'C': 0.37012987012987014}
>>> {'A': 0.2597402597402599, 'B': 0.3333333333333334, 'C': 0.40692640692640686}

However, at the same time, pagerank_numpy has a parameter called weight. According to the documentation:

weight (key, optional) – Edge data key to use as weight. If None weights are set to 1.

In the above example, weight is not set, but it does not seem that weights are all set to 1. So, what does this parameter weight really do?
Version of NetworkX: 2.1

A: The PageRank algorithm assigns weights to nodes according to a random walk on a network.  We can modify the algorithm by biasing the walk to follow some edges more than others.  To do this we weight the network's edges.  Networkx is very flexible about edge weights.    We can have weights whose name is 'weight' or 'scale_factor' or 'relative_frequency' or any string we want to name them by.  So the PageRank algorithm needs to know which name to use.
That is what you are telling the algorithm when you pass it the weight parameter.  If it doesn't get that, it treats all edges as having weight 1.


text:
Q: IOS 10 Multipeer Is Multipeer working on iOS 10? We are using it on Wifi and once in a while receive unable to connect error message and after that the devices won't connect. We need to restart the app for them to connect again. This is almost a showstopper bug for our project since as soon as this error occurs the application stops working and the devices won't connect at all. We are using the latest iOS 10.2. Please let us know in case there is any workaround for this issue. Any help is much appreciated.
2016-12-23 08:31:27.980778 RestKit[313:14524] [MCNearbyServiceBrowser] Peer [central,40A4EC6F] error in connectedHandler [Unable to connect].
2016-12-23 08:31:27.982179 RestKit[313:14524] [MCNearbyServiceBrowser] Peer [central,40A4EC6F] error in connectedHandler [Unable to connect].
2016-12-23 08:31:27.985532 RestKit[313:14524] [MCNearbyServiceBrowser] Peer [central,40A4EC6F] error in connectedHandler [Unable to connect].
2016-12-23 08:31:27.986003 RestKit[313:14524] [MCNearbyServiceBrowser] Peer [central,40A4EC6F] error in connectedHandler [Unable to connect].
2016-12-23 08:31:27.986351 RestKit[313:14524] [MCNearbyServiceBrowser] Peer [central,40A4EC6F] error in connectedHandler [Unable to connect].
2016-12-23 08:31:28.373599 RestKit[313:19758] disconnected to central
2016-12-23 08:31:29.440309 RestKit[313:14524] [MCNearbyServiceBrowser] Peer [central,40A4EC6F] error in connectedHandler [Unable to connect].

A: it works fine with this version no probem found.
Mario

A: Multipeer will often report connection outages, but continue to work as advertised. This has been true since long before iOS 10, and is the price of working with an abstracted high-end framework which hides the implementation details of bluetooth, Bonjour and peer-to-peer networking which are all used under the hood.
If you want more fine-grained control, you can always use lower-level frameworks and manage the networking issues yourself.


text:
Q: Подгон текста вокруг диаграммы
Имеется диаграмма с левой стороны и текст с правой стороны. Подскажите, каким методом я могу подогнать этот текст. Слева у меня див в котором данная диграмма и текст и с правой стороны див, думал сделать  в один див + position absolute, но мне кажется что есть лучшее решения.


text:
Q: Executing a while loop in main thread until we get the return value from a function called in secondary thread I want to write code that does something like-
In a thread call a function that will return two links and in the main thread keep printing
"processing..." until that function, called in secondary thread returns those values
and when we get those return values the while loop of the main thread terminates and print
those
values.
Now I have tried writing few codes in python but couldn't manage to do it!
I have just started python programming so I'm not familiar with it.
BTW the above-mentioned scenario is just a prototype.
The real case looks something like that:-
    def search_button(self):              #main thread
        mname = self.root.ids.name.text
        quality = Quality

        #print(mname)
        #print(quality)

        global link4, link5

        with concurrent.futures.ThreadPoolExecutor() as executor:
            futures = executor.submit(movie_bot, mname, quality)    #movie_bot is function
            link4, link5 = futures.result()                         #returning two links

        while(link4==None and link5==None):
            self.root.ids.status.text = 'Searching, please wait...'
            self.root.ids.status.text = ''

        print(link4)
        print(link5)

In case further details are required then please just let me know.
Thank you for the help.

A: Tried a lot of things and now finally it got resolved.
Basically what I wanted to do was take two inputs from GUI then call a function (from another python program) with those two parameters and then once the processing is completed then from GUI user and either watch or download that content by pressing the watch or download buttons respectively.
So to do that earlier I was returning the watch and download link from that thread called function and even on calling that function on another thread, as it was returnig values after execution so the GUI freezes and shows not responding
Then after trying a lot of thing I came across daemon thing so I just made that thread daemon and that solved the main problem of freezing but now I wasn't able to take return values (when I tried to take the return values it again started to freeze the GUI)
So then I found an alternative to access those links from the main thread.
Here the point is if the function doesn't return anything that is being called in the thread then just make it daemon thread_name.daemon() = True and now it won't freeze the GUI
Now in case you wanna do something exactly after the thread is finished then this can be used thread_name.is_alive()
MY CODE LOOKS SOMETHING LIKE THAT:-
from selenium_l_headless import movie_bot
from kivy.lang import Builder
from kivymd.app import MDApp
from  kivy.properties import ObjectProperty
from selenium_l_headless import *
import threading
import time
from kivy.clock import Clock

class MovieBot(MDApp):

    mname = ObjectProperty(None)
    quality = ObjectProperty(None)
    Quality = ObjectProperty(None)
    link4 = ObjectProperty(None)
    link5 = ObjectProperty(None)

    checks = []
    def build(self):
        self.theme_cls.theme_style= "Dark"
        self.theme_cls.primary_palette = "Teal"
        return Builder.load_file('kivy_bot_md.kv')

        def checkBox_click(self, instance, value, Q):
            global Quality
            if value==True:
                MovieBot.checks.append(Q)
                Quality=''
                for x in MovieBot.checks:
                    Quality = f'{Quality}{x}'
            else:
                MovieBot.checks.remove(Q)
                Quality = ''
                for x in MovieBot.checks:
                    Quality = f'{Quality} {x}'
        def complete(self):
            self.root.ids.status.text = 'Searching completed, Now you can
                                         download or watch the movie!'
            global flag
            flag=0

        def status_sleep(self, *args):

            try:
                self.root.ids.status.text = 'Searching, please wait...'

                if(t1.is_alive() is False):
                    self.complete()
            except:
                pass

        def search_button(self):
            try:
                mname = self.root.ids.name.text
                quality = Quality

                global link4,link5

                global t1, flag
                flag=1
                t1 = threading.Thread(target = movie_bot, args= [mname, quality])
                t1.daemon = True
                t1.start()

                if(t1.is_alive()):
                    Clock.schedule_interval(self.status_sleep,1)
            except:
                pass

    def watch(self):
        try:
            if(flag is 1):
                pass
            else:
                self.root.ids.status.text = ''
                t2 = threading.Thread(target=watch_now)
                t2.daemon = True
                t2.start()
            except:
                pass

    def download(self):
        try:
            if(flag is 1):
                pass
            else:
                self.root.ids.status.text = ''
                t3 = threading.Thread(target=download_movie)
                t3.daemon = True
                t3.start()
        except:
            pass

    def close(self):
        exit(0)

MovieBot().run()


text:
Q: Application shows on part of android screen I'm starting 3.1 AVD and wnen loading upplication to it the application shows fully but much smaller than actual screen like its dimentions were set statically to be smaller than the screen.

A: Add an appropriate <supports-screens> element to your manifest, and consider adding a <uses-sdk> element with android:targetSdkVersion="11".
If you are supporting tablet screen sizes, a likely  element would be:
<supports-screens android:xlargeScreens="true"
                    android:largeScreens="true"
                    android:normalScreens="true"
                    android:smallScreens="false" />

You could consider adding true for small screens as well, if you are supporting that size too.


text:
Q: Printing a sentence involving a function How can I print out the following sentence

"The temperature is 30"

such that 30 is changeable? In other word, I wrote:
temp = 30
print (The temperature is "+ repr(temp)")

print "The temperature is "+ repr (temp)"

But the system says syntax error.
What is a correct way of writing this?

A: Note: I am assuming you are writing a python program here, as your code does not look like basic code at all. The following has been tested using Python3 but might also work on Python2.

Your string delimiters are all over the place. Everything between the double quotes (") will be treated as a string. As a quick fix you have to move double quotes like this:
print ("The temperature is "+ repr(temp))

Then "The temperature is " is a string and the result of repr(temp) is appended to it. Right now "+ repr(temp)" is interpreted as a string and The temperature is are treated as variables, which have not been defined. Hence the error.
For a little more detail, let's walk through this:
temp = 30 # sets an variable to 30 (integer)
text = "this is a string" + str(temp) # convert temp variable to string
                                      # append it to the string and store it
                                      # in the variable named text
print(text) # print the combined text

Note that str and repr do slightly different things:

*

*str(x) returns a readable string version of the variable x

*repr(x) returns an unambiguous string that is often used in interpreters etc.

In general you want to use str for tasks like this.
For more information about this take a look at this post.


text:
Q: Implementing cartesian product, such that it can skip iterations I want to implement a function which will return cartesian product of set, repeated given number. For example
input: {a, b}, 2
output:
aa
ab
bb
ba

input: {a, b}, 3
aaa
aab
aba
baa
bab
bba
bbb

However the only way I can implement it is firstly doing cartesion product for 2 sets("ab", "ab), then from the output of the set, add the same set. Here is pseudo-code:
function product(A, B):
    result = []
    for i in A:
        for j in B:
            result.append([i,j])
    return result
function product1(chars, count):
    result = product(chars, chars)
    for i in range(2, count):
        result = product(result, chars)
    return result

What I want is to start computing directly the last set, without computing all of the sets before it. Is this possible, also a solution which will give me similar result, but it isn't cartesian product is acceptable.
I don't have problem reading most of the general purpose programming languages, so if you need to post code you can do it in any language you fell comfortable with.

A: Here's a recursive algorithm that builds S^n without building S^(n-1) "first". Imagine an infinite k-ary tree where |S| = k. Label with the elements of S each of the edges connecting any parent to its k children. An element of S^m can be thought of as any path of length m from the root. The set S^m, in that way of thinking, is the set of all such paths. Now the problem of finding S^n is a problem of enumerating all paths of length n - and we can name a path by considering the sequence of edge labels from beginning to end. We want to directly generate S^n without first enumerating all of S^(n-1), so a depth-first search modified to find all nodes at depth n seems appropriate. This is essentially how the below algorithm works:
// collection to hold generated output
members = []

// recursive function to explore product space
Products(set[1...n], length, current[1...m])

    // if the product we're working on is of the
    // desired length then record it and return
    if m = length then
        members.append(current)
        return

    // otherwise we add each possible value to the end
    // and generate all products of the desired length
    // with the new vector as a prefix
    for i = 1 to n do
        current.addLast(set[i])
        Products(set, length, current)
        currents.removeLast()

// reset the result collection and request the set be generated
members = []
Products([a, b], 3, [])

Now, a breadth-first approach is no less efficient than a depth-first one, and if you think about it would be no different from exactly what you're already doing. Indeed, and approach that generates S^n must necessarily generate S^(n-1) at least once, since that can be found in a solution to S^n.


text:
Q: Deduplication of records without sorting in a mainframe sequential dataset with already sorted data This is a query on deduplicating an already sorted mainframe dataset without re-sorting it.
The input sequential dataset has the following structure. 'KEYn' in the first 4 bytes represents the key and the remainder of each row represents the rest of the record's data. There are records in which the same key is repeated though the remaining data is different in each record. The records are already sorted on 'KEYn'.
KEY1aaaaaa
KEY1bbbbbb
KEY2cccccc
KEY3xxxxxx
KEY3yyyyyy
KEY3zzzzzz
KEY3wwwwww
KEY4uuuuuu
KEY5hhhhhh
KEY5ffffff
My requirement is to pick up the first record of each key and drop the remaining 'duplicates'. so the output file for the above input should look like this:
KEY1aaaaaa
KEY2cccccc
KEY3xxxxxx
KEY4uuuuuu
KEY5hhhhhh
Since the data is already sorted, I don't want to use SORT utility with SUM FIELDS=NONE or ICETOOL with SELECT - FIRST operand since both of these will actually end up re-sorting the data on the deduplication key (KEYn). Also the actual dataset I am referring to is huge (1.6 billion records, AVGRLEN 900 VB) and a job actually ran out of sort work space trying to sort it in one go.
My query is: Is there any option available in JCL based utilities to do this deduplication without resorting and using sort work space? I am trying to avoid writing a COBOL/Assembler program to do this.

A: Try this untested.
OPTION COPY
INREC BUILD=(1,4,SEQNUM,3,ZD,RESTART=(5,4),5)
OUTFIL INCLUDE=(5,3,ZD,EQ,1),BUILD=(1,4,8)


text:
Q: Generating dynamic query in spring boot I have a native Mysql query
select tl_id,c_name,m_name,u_first_name,t_name,
tl_logged_at,tl_minutes,tl_description
from users inner join clients on u_id=c_frn_owner_id
inner join matters on m_frn_client_id = c_id
inner join tasks on t_frn_matter_id = m_id
inner join task_logs on tl_frn_task_id = t_id
where c_id =2 and m_id=4 and t_id= 3 and u_id = 4

for which I can write JPQL instead of native query. But how to get the same query using JPA Specification, since the columns or fields in the where conditions c_id, m_id, t_id and u_id are optionals. They are filter options provided to the user.
Generation of native query can be done using if conditions. But they are prone to typo and SQL Injections.
The documentation of JPASpecification has no informations related to joining multiple tables.
Spring Official JPA Specification Doc
I am very new to JPASpecification so any guidance will be valuable.

A:
JPA 2 introduces a criteria API that you can use to build queries
  programmatically.

If you use JPA 2 and you wanted to create dynamic query, I think you should look at the Criteria API to build dynamic queries. Or you can use JpaSpecificationExecutor(I haven't tried, yet.) Check this related question.
Some useful links attached:

*

*JPA Specifications

*JPA Criteria Api

A: Have a look at the querydsl project, I use it extensively in a mid size ERP and hasn't disappointed until now.
http://www.querydsl.com/static/querydsl/latest/reference/html/
for dynamic where clause: you can use com.querydsl.core.BooleanBuilder
So when you have querydsl in place, you can first generate your where clause like the following.
QEmployee employee = QEmployee.employee;
 BooleanBuilder dynamicWhere = new BooleanBuilder();
 if(true) { //Any condition
     dynamicWhere.and(employee.name.equalsIgnoreCase("someName"));
 }
 if(true){
     dynamicWhere.and(employee.age.gt(18));
 }

and then you can write your query like the following.
queryFactory.selectFrom(employee)
    //joins, group by, order by goes here
    .where(dynamicWhere)
    .fetch();