Q: How to change from annual year end to annual mid year in SAS I currently work in SAS and utilise arrays in this way:
Data Test;
input Payment2018-Payment2021;
datalines;

10 10 10 10
20 20 20 20
30 30 30 30
;
run;

In my opinion this automatically assumes a limit, either the start of the year or the end of the year (Correct me if i'm wrong please)
So, if I wanted to say that this is June data and payments are set to increase every 9 months by 50% I'm looking for a way for my code to recognise that my years go from end of June to the next end of june
For example, if I wanted to say
Data Payment_Pct;
set test;

lastpayrise = "31Jul2018";

array payment:
array Pay_Inc(2018:2021) Pay_Inc: ;

Pay_Inc2018 = 0;
Pay_Inc2019 = 2; /*2 because there are two increments in 2019*/
Pay_Inc2020 = 1;
Pay_Inc2021 = 1;

do I = 2018 to 2021;

    if i = year(pay_inc) then payrise(i) * 50% * Pay_Inc(i);

end;

run;

It's all well and good for me to manually do this for one entry but for my uni project, I'll need the algorithm to work these out for themselves and I am currently reading into intck but any help would be appreciated!
P.s. It would be great to have an algorithm that creates the following
Pay_Inc2019 Pay_Inc2020 Pay_Inc2021
1           2           1

OR, it would be great to know how the SAS works in setting the array for 2018:2021 , does it assume end of year or can you set it to mid year or?

A: This is a wonderful use case of the intnx() function. intnx() will be your best friend when it comes to aligning dates.
In the traditional calendar, the year starts on 01JAN. In your calendar, the year starts in 01JUN. The difference between these two dates is exactly 6 months. We want to shift our date so that the year starts on 01JUN. This will allow you to take the year part of the date and determine what year you are on in the new calendar.
data want;
    format current_cal_year
           current_new_year year4.
    ;

    current_cal_year = intnx('year', '01JUN2018'd, 0, 'B');
    current_new_year = intnx('year.6', '01JUN2018'd, 1, 'B');
run;

Note that we shifted current_new_year by one year. To illustrate why, let's see what happens if we don't shift it by one year.
data want;
    format current_cal_year
           current_new_year year4.
    ;

    current_cal_year = intnx('year', '01JUN2018'd, 0, 'B');
    current_new_year = intnx('year.6', '01JUN2018'd, 0, 'B');
run;

current_new_year shows 2018, but we really are in 2019. For 5 months out of the year, this value will be correct. From June-December, the year value will be incorrect. By shifting it one year, we will always have the correct year associated with this date value. Look at it with different months of the year and you will see that the year part remains correct throughout time.
data want;
    format cal_month date9.
           cal_year
           new_year year4.
    ;

    do i = 0 to 24;
        cal_month = intnx('month', '01JAN2016'd, i, 'B');
        cal_year = intnx('year', cal_month, i, 'B');
        new_year = intnx('year.6', cal_month, i+1, 'B');
        year_not_same = (year(cal_year) NE year(new_year) );
        output;
    end;

    drop i;
run;

A: Regarding input Payment2018-Payment2021; there is no automatic assumption of yearness or calendaring. The numbers 2018 and 2021 are the bounds for a numbered range list

In a numbered range list, you can begin with any number and end with any number as long as you do not violate the rules for user-supplied names and the numbers are consecutive.

The meaning of the numbers 2018 to 2021 is up to the programmer.  You state the variables correspond to the June payment in the numbered year.
You would have to iterate a date using 9-month steps and increment a counter based on the year in which the date falls.
Sample code
Dynamically adapts to the variable names that are arrayed.
data _null_;

  array payments payment2018-payment2021;
  array Pay_Incs pay_inc2018-pay_inc2021; * must be same range numbers as payments;

  * obtain variable names of first and last element in the payments array;
  lower_varname = vname(payments(1));
  upper_varname = vname(payments(dim(payments)));

  * determine position of the range name numbers in those variable names;
  lower_year_position = prxmatch('/\d+\s*$/', lower_varname);
  upper_year_position = prxmatch('/\d+\s*$/', upper_varname);

  * extract range name numbers from the variable names;
  lower_year = input(substr(lower_varname,lower_year_position),12.);
  upper_year = input(substr(upper_varname,upper_year_position),12.);

  * prepare iteration of a date over the years that should be the name range numbers;
  date = mdy(06,01,lower_year); * june 1 of year corresponding to first variable in array;

  format date yymmdd10.;

  do _n_ = 1 by 1; * repurpose _n_ for an infinite do loop with interior leave;
    * increment by 9-months;
    date = intnx('month', date, 9);

    year = year(date);
    if year > upper_year then leave;

    * increment counter for year in which iterating date falls within;
    Pay_Incs( year - lower_year + 1 ) + 1;
  end;

  put Pay_Incs(*)=;
run;

Increment counter notes
There is a lot to unpack in this statement
    Pay_Incs( year - lower_year + 1 ) + 1;

*

*+ 1 at the end of the statement increments the addressed array element by 1, and is the syntax for the SUM Statement

variable + expression The sum statement is equivalent to using the SUM function and the RETAIN statement, as shown here:
  retain variable 0;
  variable=sum(variable,expression);

*year - lower_year + 1 computes the array base-1 index, 1..N, that addresses the corresponding variable in the named range list pay_inc<lower_year>-pay_inc<upper_year>

*Pay_Incs( <computed index> ) selects the variable of the SUM statement


Q: Make for loop continue until a goal is accomplished I need to be able to find 5 sequential bits of EEPROM memory, ideally closest to 2 (as I have bit #1 & 2 associated with other data and want things to be kept organized). I developed this code which works, but the for loop continues after it has found a good set of numbers.
Serial.println("got to assignment number finder");
for (int AssignCheck = 2; AssignCheck < 250; AssignCheck++){
  Serial.println("Finding a good assignment number " + String(AssignCheck));
  if (EEPROM.read(AssignCheck) == 255){          //Looks for a blank space which can be used to store the new card
    if (EEPROM.read(AssignCheck + 1) == 255){
      if (EEPROM.read(AssignCheck + 2) == 255){
        if (EEPROM.read(AssignCheck + 3) == 255){
          if (EEPROM.read(AssignCheck + 4) == 255){
            Serial.println("Found assignment numbers " + String(AssignCheck) + " through to " + String(int(AssignCheck) + 4) + ".  Scanner value = " + String(Scanner));
            int StoreValue = AssignCheck;
          }
        }
      }
    }
  }
}

I then thought I could put a while loop around it, and have the while loop stop once a variable is set to 0 as opposed to 1, so I wrote this: (notice the introduction of the while loop, the variable and the Scanner = 0 line in the middle).
Serial.println("got to assignment number finder");
int Scanner = 1;
while (Scanner == 1){
  for (int AssignCheck = 2; AssignCheck < 250; AssignCheck++){
    Serial.println("Finding a good assignment number " + String(AssignCheck) + ".  Scanner value = " + String(Scanner));
    if (EEPROM.read(AssignCheck) == 255){          //Looks for a blank space which can be used to store the new card
      if (EEPROM.read(AssignCheck + 1) == 255){
        if (EEPROM.read(AssignCheck + 2) == 255){
          if (EEPROM.read(AssignCheck + 3) == 255){
            if (EEPROM.read(AssignCheck + 4) == 255){
              Scanner = 0;
              Serial.println("Found assignment numbers " + String(AssignCheck) + " through to " + String(int(AssignCheck) + 4) + ".  Scanner value = " + String(Scanner));
              int StoreValue = AssignCheck;
            }
          }
        }
      }
    }
  }
}

It correctly identifies and sets the variable to 0 when I want, but the while loop doesn't seem to have an impact and the loop continues to produce sets of numbers which could work.
As a novice coder myself, I'm not sure what I could try next.
Any advice would be greatly appreciated.

A: In these case you can use the instruction break:
Serial.println("got to assignment number finder");
for (int AssignCheck = 2; AssignCheck < 250; AssignCheck++){
  Serial.println("Finding a good assignment number " + String(AssignCheck));
  if (EEPROM.read(AssignCheck) == 255){          //Looks for a blank space which can be used to store the new card
    if (EEPROM.read(AssignCheck + 1) == 255){
      if (EEPROM.read(AssignCheck + 2) == 255){
        if (EEPROM.read(AssignCheck + 3) == 255){
          if (EEPROM.read(AssignCheck + 4) == 255){
            Serial.println("Found assignment numbers " + String(AssignCheck) + " through to " + String(int(AssignCheck) + 4) + ".  Scanner value = " + String(Scanner));
            int StoreValue = AssignCheck;
            break;
          }
        }
      }
    }
  }
}

As you can read here, it does exactly what you want.
Please note that your second attempt doesn't work because the for loop is inside the while: it completes before the whole for loop and, after, it compare the "scanner" variable of the while loop
You can correct it in this way:
Serial.println("got to assignment number finder");
int Scanner = 1;
for (int AssignCheck = 2; (AssignCheck < 250) && (Scanner == 1); AssignCheck++){
  Serial.println("Finding a good assignment number " + String(AssignCheck) + ".  Scanner value = " + String(Scanner));
  if (EEPROM.read(AssignCheck) == 255){          //Looks for a blank space which can be used to store the new card
    if (EEPROM.read(AssignCheck + 1) == 255){
      if (EEPROM.read(AssignCheck + 2) == 255){
        if (EEPROM.read(AssignCheck + 3) == 255){
          if (EEPROM.read(AssignCheck + 4) == 255){
            Scanner = 0;
            Serial.println("Found assignment numbers " + String(AssignCheck) + " through to " + String(int(AssignCheck) + 4) + ".  Scanner value = " + String(Scanner));
            int StoreValue = AssignCheck;
          }
        }
      }
    }
  }
}

A: Reading EEPROM is expensive, please consider this:
Serial.println("got to assignment number finder");
int Scanner = 1;
char rollingBuffer[5];
rollingBuffer[0] = EEPROM.read(2 + 0);
rollingBuffer[1] = EEPROM.read(2 + 1);
rollingBuffer[2] = EEPROM.read(2 + 2);
rollingBuffer[3] = EEPROM.read(2 + 3);
rollingBuffer[4] = EEPROM.read(2 + 4);
pointRoll = 0;
for (int AssignCheck = 7; (AssignCheck < 255); AssignCheck++)
{
    if ((rollingBuffer[0] == 255) && (rollingBuffer[1] == 255) && (rollingBuffer[2] == 255) && (rollingBuffer[3] == 255) && (rollingBuffer[4] == 255))
    {
        Serial.println("Found assignment numbers " + String(AssignCheck-5) + " through to " + String(int(AssignCheck-1)) + ".  Scanner value = " + String(Scanner));
        int StoreValue = AssignCheck;
        break;
    }
    rollingBuffer[pointRoll] = EEPROM.read(AssignCheck);
    pointRoll++;
    if (pointRoll > 4) pointRoll = 0;
}


Q: Laravel back() doesn't use _previous Trying to use
return back();

In one of my controllers however it always seems to return back to the home page if I however use
return Redirect::to($request->session->get('_previous')['url']);

It does work so it seems that for some reason the back() function isn't grabbing _previous correctly. Any way to fix this? I've noticed it in other controllers as well.


Q: Confused in Dependency Injection I am new to MVC and dependency injection. Please help me to understand how that should work. I use Ninject. Here is my code:
in Global.asax file:
private void RegisterDependencyResolver()
    {
        var kernel = new StandardKernel();
        kernel.Bind<IDbAccessLayer>().To<DAL>();
        // DAL - is a Data Access Layer that comes from separated class library
        DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
    }

protected void Application_Start()
    {
        RegisterDependencyResolver();
    }

IDbAccessLayer implementation is very simple:
public interface IDbAccessLayer
{
  DataContext Data { get; }
  IEnumerable<User> GetUsers();
}

now in a Controller I need to create a constructor that gets IDbAccessLayer param. And that just works.
Now I don't know how to pass a connection string to DAL. if I try to replace DAL's constructor with something that accepts a parameter, it doesn't work. Throws an exception with message No parameterless constructor defined for this object

A: You could specify constructor parameters:
kernel
    .Bind<IDbAccessLayer>()
    .To<DAL>()
    .WithConstructorArgument("connectionString", "YOUR CONNECTION STRING HERE");

And instead of hardcoding the connection string in your Global.asax you could read it from your web.config using:
ConfigurationManager.ConnectionStrings["CNName"].ConnectionString

and now your DAL class could take the connection string as parameter:
public class DAL: IDbAccessLayer
{
    private readonly string _connectionString;
    public DAL(string connectionString)
    {
        _connectionString = connectionString;
    }

    ... implementation of the IDbAccessLayer methods
}

A: Create a parameter-less constructor that calls the one-parameter constructor with a default connection string.
public DAL() : this("default connection string") {

}

public DAL(string connectionString) {
    // do something with connection string
}

A: I've not worked with ninject, just a bit with Unity.  But all the IOC containers seem to gravitate towards you making your own factory class that takes your stateful parameters (your connection string), which returns your real object.  For example, if you had a Person class which requires a "name" and "age" for the constructor, then you must make a factory which would interact with Unity rather like this:
IPerson foo = container.Resolve<IPersonFactory>().Create("George", 25);

This is one of the things I don't like about IOC containers, but it's generally where it goes...

A: Just stupid idea having no knowledge of ninject:
kernel.Bind<IMyConnectionString>().To<MyConnectionString>();

And to your DAL constructor accepting IMyConnectionString


Q: Change App name dynamically based on user input I want to change the name of the app and the form title based on the user input. I know to do those changes in the manifest and styles, but how to make it dynamic. Please suggest me how to do it?. What are the changes to be done.

A: Did you try this?
myActivity.setTitle(userInput); //Where userInput is new title given by user

Hope this helps.

A: You can simply call the setTitle() function from within your Activity. It takes either an int (resource ID) or a CharSequence as a parameter.
or
this.setTitle("New Title Here");

or change in manifest file

A: If you just want to change the string in the Title bar, you can use setTitle as @android_beginner or @Mystic Magic suggested.
If you intend on changing the name of the app as it appears in the Android desktop, I'm afraid that's not possible.


Q: How to replace table name in sql query with regex in Java? I want to replace table name in a sql query string. I only want to change table name. How can I do that in java with regex?
I do not want to use any dependencies.
For example,
Input:
select ... from table1 where/etc ....

expected output:
select ... from UPDATED_TABLE_NAME where/etc ....

A: If you mutate the query explicitly you open yourself to SQL injection. What you could do is use a PreparedStatement with a parameterized query to provide the table name safely.
try (PreparedStatement statement = connection.prepareStatement("SELECT * FROM ?")) {
    statement.setString(1, "my_table");

    try (ResultSet results = statement.executeQuery()) {

    }
}

If you're insistent on using regex you can just use the query above and replace ? with the table name. I would not do this in a production environment.
String query = "SELECT * FROM ?";

String queryWithTable = query.replaceAll("?", "my_table");


Q: Get Azure Webjob History - 403 Token invalid I am trying to retrieve the web job history of an Azure web job via REST using a .NET backend and the OAuth2 credentials flow (as described here
https://learn.microsoft.com/en-us/rest/api/appservice/web-apps/get-triggered-web-job-history-slot)
How do I need to authenticate correctly?
I retrieve the token as follows:
POST https://login.microsoftonline.com/{MySubscription}/oauth2/v2.0/token
client_id={MyApp}
&grant_type=client_credentials
&scope=https://management.azure.com/.default
&client_secret={myclient_secret}

I get a token back, however I get a 403 error message when I try to retrieve the resource:
GET https://management.azure.com/subscriptions/{MySubscription}/resourceGroups/{MyResource}/providers/Microsoft.Web/sites/{MyApp}/slots/{MySlot}/triggeredwebjobs/{MyWebjob}/history?api-version=2021-02-01
Authorization: Bearer {MyToken}

Client '{MyApp}' with object ID '{MyApp}' is not
authorized to perform the action
'Microsoft.Web/sites/slots/triggeredwebjobs/history/read' using the
scope
'/subscriptions/{MySubscription}/resourceGroups/{MyResource}/providers/Microsoft.Web/sites/{MyApp}/slots/{MySlot}/triggeredwebjobs/{MyWebjob}'
or the scope is invalid. If access was granted recently, please update
your credentials.

What am I doing wrong?
I already added the API-Permission

A: The "403 Token invalid" error usually occurs if you missed giving permissions to particular scope (Azure Service Management).
By giving this scope it enables you to access https://management.azure.com
To resolve this error, please follow below steps:
Go to Azure Ad ->your application -> API permissions -> Add permission -> Azure Service Management -> delegated permissions ->User impersonation -> Add

After giving these permissions try to retrieve the resource again, there won't be any error.

A: Since I didn't find a solution that worked with OAuth2 and the Credentials flow, I got it working with Basic Authentication. The username (userName) and password (userPWD) can be taken from the publishing profile of the respective app service.
GET https://{appservicename}.scm.azurewebsites.net/api/triggeredwebjobs/{jobName}/history
Authorization Basic ....


Q: Meteor loginWithFacebook permissions not being asked I am using Meteor.loginWithFacebook:
 Meteor.loginWithFacebook({
      // https://developers.facebook.com/docs/reference/fql/permissions/
      requestPermissions: ['read_friendlists','user_about_me','user_birthday',
      'user_education_history', 'user_friends', 'user_likes', 'user_photos',
      'user_religion_politics', 'user_work_history'],
      loginStyle: "popup"
    }, function (err,res) {
      if(err)  alert(err)
      else console.log(res)
    });

But when my actual login box pops up, thought the user is logged in and I get access to all their publicly availabe information, it doesn't actually request any of the specified permissions (and I therefore don't have access to them). Is there something in my code I need to change in order to have the permissions actually be requested?

A: @kittyminky you right
the solution is
Accounts.ui.config({ requestPermissions: { facebook: [the_permissons_you_want] } });

A: on my case using Accounts.ui.config yields an error since i only have Accounts defined, Accounts.ui isn't defined for me.
Perhaps because i didn't add that package, but must be a way without using the .ui ?


Q: How to save All excel Charts in one pdf then Email it I would greatly appreciate it if you could help me with this, I am creating a dynamic excel sheet and I managed so far to create excel charts using Excel vba.
However, I am struggling with exporting all of the charts and one additional sheet to one pdf. I have around 15 excel charts and one excel sheet that I need to put in one pdf. And I need the excel sheet to be the first page in the pdf. Then email this pdf (all using vba).
Could you please help me on this! Your help is much appreciated. Thank you in advance!

A: Well you could Publish the workbook to PDF, just make sure your fist page is the first sheet
Option Explicit
Sub PDF_And_Mail()
    Dim FileName As String

    '// Call the function with the correct arguments
    FileName = Create_PDF(Source:=ActiveWorkbook, _
                              OverwriteIfFileExist:=True, _
                              OpenPDFAfterPublish:=False)

    If FileName <> "" Then
        Mail_PDF FileNamePDF:=FileName
    End If

End Sub

'// Create PDF
Function Create_PDF(Source As Object, OverwriteIfFileExist As Boolean, _
                                OpenPDFAfterPublish As Boolean) As String
    Dim FileFormatstr As String
    Dim Fname As Variant

    '// Test If the Microsoft Add-in is installed
    If Dir(Environ("commonprogramfiles") & "\Microsoft Shared\OFFICE" _
         & Format(Val(Application.Version), "00") & "\EXP_PDF.DLL") <> "" Then

            '// Open the GetSaveAsFilename dialog to enter a file name for the pdf
            FileFormatstr = "PDF Files (*.pdf), *.pdf"
            Fname = Application.GetSaveAsFilename("", filefilter:=FileFormatstr, _
                                                  Title:="Create PDF")

        '// If you cancel this dialog Exit the function
        If Fname = False Then
            Exit Function
        End If

        'If OverwriteIfFileExist = False we test if the PDF
        'already exist in the folder and Exit the function if that is True
        If OverwriteIfFileExist = False Then
            If Dir(Fname) <> "" Then Exit Function
        End If

        'Now the file name is correct we Publish to PDF
        Source.ExportAsFixedFormat _
                Type:=xlTypePDF, _
                FileName:=Fname, _
                Quality:=xlQualityStandard, _
                IncludeDocProperties:=True, _
                IgnorePrintAreas:=False, _
                OpenAfterPublish:=OpenPDFAfterPublish

        'If Publish is Ok the function will return the file name
        If Dir(Fname) <> "" Then
            Create_PDF = Fname
        End If
    End If
End Function

'// Email Created PDF
Function Mail_PDF(FileNamePDF As String)
    Dim GMsg As Object
    Dim gConf As Object
    Dim GmBody As String
    Dim Flds As Variant

    Set GMsg = CreateObject("CDO.Message")
    Set gConf = CreateObject("CDO.Configuration")

    gConf.Load -1    ' CDO Source Defaults
    Set Flds = gConf.Fields

    With Flds
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
        .Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "GmailAddress@gmail.com"
        .Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password"
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
        .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
        .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
        .Update
    End With

    GmBody = "Hi there" & vbNewLine & vbNewLine

    With GMsg
        Set .Configuration = gConf
        .To = "recip@email.com"
        .CC = ""
        .BCC = ""
        .From = "Reply@something.com"
        .Subject = "Important message"
        .TextBody = GmBody
        .AddAttachment FileNamePDF
        .Send
    End With

End Function

Most codes from Ron de Bruin


Q: Folium map not displaying Running on canopy version 1.5.5.3123
With;
Folium Version: 0.1.2, Build: 1
The following code;
import folium
import pandas as pd
LDN_COORDINATES = (51.5074, 0.1278)
from IPython.display import HTML
import shapefile
#create empty map zoomed in on London
LDN_COORDINATES = (51.5074, 0.1278)
map = folium.Map(location=LDN_COORDINATES, zoom_start=12)
display(map)

Returns
<folium.folium.Map at 0x10c01ae10>

But nothing else.
How do i get to display a map within an ipython notebook?

A: _build_map() doesn't exist anymore. The following code worked for me
import folium
from IPython.display import display
LDN_COORDINATES = (51.5074, 0.1278)
myMap = folium.Map(location=LDN_COORDINATES, zoom_start=12)
display(myMap)

A: Considering the above answers, another simple way is to use it with Jupiter Notebook.
for example (on the Jupiter notebook):
import folium

london_location = [51.507351, -0.127758]

m = folium.Map(location=london_location, zoom_start=15)
m

and see the result when calling the 'm'.

A: Is there a reason you are using an outdated version of Folium?
This ipython notebook clarifies some of the differences between 1.2 and 2, and it explains how to put folium maps in iframes.
http://nbviewer.jupyter.org/github/bibmartin/folium/blob/issue288/examples/Popups.ipynb
And the code would look something like this (found in the notebook above, it adds a marker, but one could just take it out):
m = folium.Map([43,-100], zoom_start=4)

html="""

 This is a big popup

    With a few lines of code...

        from numpy import *

        exp(-2*pi)

    """
iframe = folium.element.IFrame(html=html, width=500, height=300)
popup = folium.Popup(iframe, max_width=2650)

folium.Marker([30,-100], popup=popup).add_to(m)

m

The docs are up and running, too, http://folium.readthedocs.io/en/latest/

A: I've found this tutorial on Folium in iPython Notebooks quite helpful. The raw Folium instance that you've created isn't enough to get iPython to display the map- you need to do a bit more work to get some HTML that iPython can render.
To display in the iPython notebook, you need to generate the html with the myMap._build_map() method, and then wrap it in an iFrame with styling for iPython.
import folium
from IPython.display import HTML, display
LDN_COORDINATES = (51.5074, 0.1278)
myMap = folium.Map(location=LDN_COORDINATES, zoom_start=12)
myMap._build_map()
mapWidth, mapHeight = (400,500) # width and height of the displayed iFrame, in pixels
srcdoc = myMap.HTML.replace('"', '"')
embed = HTML(''.format(srcdoc, width, height))
embed

Where by returning embed as the output of the iPython cell, iPython will automatically call display.display() on the returned iFrame. In this context, you should only need to call display() if you're rendering something else afterwards or using this in a loop or a function.
Also, note that using map as a variable name may might be confused with the .map() method of several classes.

A: You can also save the map as html and then open it with webbrowser.
import folium
import webbrowser

class Map:
    def __init__(self, center, zoom_start):
        self.center = center
        self.zoom_start = zoom_start

    def showMap(self):
        #Create the map
        my_map = folium.Map(location = self.center, zoom_start = self.zoom_start)

        #Display the map
        my_map.save("map.html")
        webbrowser.open("map.html")

#Define coordinates of where we want to center our map
coords = [51.5074, 0.1278]
map = Map(center = coords, zoom_start = 13)
map.showMap()

A: There is no need to use iframes in 2022. To display the map, simply use the
{{ map | safe }} tag in html and _repr_html_() method in you view. It is also not necessary to save the map to the template
sample.py
@app.route('/')
def index():
    start_coords = (46.9540700, 142.7360300)
    folium_map = folium.Map(location=start_coords, zoom_start=14)
    return folium_map._repr_html_()

template.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

{{ folium_map | safe }}

A: i have same error and nothing work for me
finally i found it
print(dir(folium.Map))
see method save dose not exist instead use


Q: Python-How I pass list or vector in pd.read_sql query New to Python Data science.
Here I have a sql server extract and I am extracting the data via 'pyodbc.connect' and reading the data by pd.read_sql(.....SQL query) from SQL server.
Here my intention is want to use a list or vector (example below) in SQL query where condition. How I do that? It hleps us not fetching millions of rows into memory.
I like to know how I pass number list and string list (both have different use cases)
1st whare conditions string:
raw_data2 = {'age1': ['ten','twenty']}
df2 = pd.DataFrame(raw_data2, columns = ['age1'])

2nd where condition number:
   raw_data2 = {'age_num': [10,20,30]}
    df3 = pd.DataFrame(raw_data2, columns = ['age_num'])

Thank you for your help and this will reduce our fetch time to 80%

A: Consider using pandas' read_sql and pass parameters to avoid type handling. Additionally, save all in a dictionary of dataframes with keys corresponding to original raw_data keys and avoid flooding global environment with many sepeate dataframes:
raw_data = {'age1': ['ten','twenty'],
            'age_num': [10, 20, 30]}

df_dict = {}
for k, v in raw_data.items():
   # BUILD PREPARED STATEMENT WITH PARAM PLACEHOLDERS
   where = '{col} IN ({prm})'.format(col=k, prm=", ".join(['?' for _ in v]))
   sql = 'SELECT * FROM mytable WHERE {}'.format(where)
   print(sql)

   # IMPORT INTO DATAFRAME
   df_dict[k] = pd.read_sql(sql, conn, params = v)

# OUTPUT TOP ROWS OF EACH DF ELEM
df_dict['age1'].head()
df_dict['age_num'].head()

For separate dataframe objects:
def build_query(my_dict):
   for k, v in my_dict.items():
      # BUILD PREPARED STATEMENT WITH PARAM PLACEHOLDERS IN WHERE CLAUSE
      where = '{col} IN ({prm})'.format(col=k, prm=", ".join(['?' for _ in v]))
      sql = 'SELECT * FROM mytable WHERE {}'.format(where)

   return sql

raw_data2 = {'age1': ['ten','twenty']}
# ASSIGNS QUERY
sql = build_query(raw_data2)
# IMPORT TO DATAFRAME PASSING PARAM VALUES
df2 = pd.read_sql(sql, conn, params = raw_data2['age1'])

raw_data3 = {'age_num': [10,20,30]}
# ASSIGNS QUERY
sql = build_query(raw_data3)
# IMPORT TO DATAFRAME PASSING PARAM VALUES
df3 = pd.read_sql(sql, conn, params = raw_data3['age_num'])


Q: EF Core overwrite mechanic to send commands to database I want to use EF Core for my application but instead that EF Core should send a SQL command onto a datbase it should just simply send it to another application which will care about multi-tenancy and choosing the right database (tennant) for this command.
So is there a way to overwrite the main point in EF Core where the command is allready generated and WOULD be now send into the given database and instead of sending it into that, just do things?

A: EF Core Interceptors allow you to do just that:
public class QueryCommandInterceptor : DbCommandInterceptor
{
    public override async ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
        DbCommand command,
        CommandEventData eventData,
        InterceptionResult<DbDataReader> result,
        CancellationToken cancellationToken = default)
    {
        var resultReader = await SendCommandToAnotherAppAsync(command);

        return InterceptionResult<DbDataReader>.SuppressWithResult(resultReader);
    }

    private Task<DbDataReader> SendCommandToAnotherAppAsync(DbCommand command)
    {
        // TODO: Actual logic.
        Console.WriteLine(command.CommandText);

        return Task.FromResult<DbDataReader>(null!);
    }
}

Make sure to override other methods like ScalarExecuting, NonQueryExecuting, sync and async variants.

A: Multitenancy is already supported in EF Core. The options are described in the Multi-tenancy page in the docs.
In this case, it appears a different database per tenant is used. Assuming there's a way/service that can return who the tenant is, a DbContext can use a different connection string for each tenant. Assuming there's a way/service to retrieve the current tenant name, eg ITenantService, the DbContext constructor can use it to load a different connection string per tenant. The entire process could be abstracted behind eg an ITenantConnectionService, but the docs show how this is done explicitly.
The context constructor will need the tenant name and access to configuration :
public ContactContext(
    DbContextOptions<ContactContext> opts,
    IConfiguration config,
    ITenantService service)
    : base(opts)
{
    _tenantService = service;
    _configuration = config;
}

Each time a new DbContext instance is created, the connection string is loaded from configuration based on the tenant's name:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    var tenant = _tenantService.Tenant;
    var connectionStr = _configuration.GetConnectionString(tenant);
    optionsBuilder.UseSqlite(connectionStr);
}

This is enough to use a different database per tenant.
Scope and lifecycle
These aren't a concern when a DbContext is used as a Scoped or Transient service.
By default AddDbContext registers DbContexts as scoped services. The scope in a web application is a single request. Once a request is processed, any DbContext instances created are disposed.
Connection Pooling
Connection pooling isn't a concern either. First of all, a DbContext doesn't represent a database connection. It's a disconnected Unit-of-Work. A connection is only opened when the context needs to load data from the database or persist changes when SaveChanges is called. If SaveChanges isn't called, nothing gets persisted. No connections remain open between loading and saving.
Consistency is maintained using optimistic concurrency. When the data is saved EF Core checks to see if the rows being stored have changed since the time they were loaded. In the rare case that some other application/request changed the data, EF Core throws a DbConcurrencyException and the application has to decide what to do with the changed data.
This way, there's no need for a database transaction and thus no need for an open connection. When optimistic concurrency was introduced in ... the late 1990s, application scalability increased by several (as in more than 100, if not 1000) orders of magnitude.
Connection pooling is used to eliminate the cost of opening and closing connections. When DbConnection.Close() is called, the actual network connection isn't terminated. The connection is reset and placed in a pool of connections that can be reused.
That's a driver-level feature, not something controlled by EF Core. Connections are pooled by connection string and in the case of Windows Authentication, per user. This eliminates the chance of a connection meant for one user getting used by another one.
Connection pooling is controlled by ADO.NET and the database provider. Some drivers allow connection pooling while others don't. In those that do support it, it can be turned off using keywords in the connection string or driver settings.


Q: When using Object.assign, why only the inner object properties of copied object are changed, when changing the original object? I'm doing a shallow copy and trying to understand why only the inner objects properties are changed, given the fact that a shallow copy copies the reference from, lets say car into copiedCar, so if I change a property on the car object, shouldn't that property also change on the copiedCar object?

const car = {
  name: "Audi",
  properties: {
    color: "yellow",
    wheels: 19
  }
}

const copiedCar = Object.assign({}, car);

car.name = "BMW",
car.properties.color = "Green"
car.properties.wheels = 15

console.log(copiedCar)

//Here it will print:
//{
//   name:"Audi",
//   properties: {
//    color:"Green",
//    wheels:15
//  }
//}

Why are only the properties of inner object changed and not also the property of the object?


Q: How to programmatically install a jar file to startup on all operating systems - Java So i have come across a problem with installing my java application to startup on all Operating Systems.
Firstly I know this is possible on Windows by adding a new key to registry (I think).
I believe the command: 'reg add' works on windows.

I'm not 100% sure about Mac but i believe you can use a service wrapper?
And for Linux I have no clue.
Basically i want my application to be installed to startup when a user ticks a box, no matter which operating system it is run on.
Just some clarification on these and if possible an example for each would really assist me.
Any help with this is greatly appreciated.
Thanks.

A: Add a .desktop file to one of the following directories:

*

*$XDG_CONFIG_DIRS/autostart/ (/etc/xdg/autostart/ by default) for all users

*$XDG_CONFIG_HOME/autostart/ (~/.config/autostart/ by default) for a particular user

See the FreeDesktop.org Desktop Application Autostart Specification for details.
So for example,
    PrintWriter out = new PrintWriter(new FileWriter(
        System.getProperty("user.home")+"/.config/autostart/myapp.desktop"));
    out.println("[Desktop Entry]");
    out.println("Name=myapp");
    out.println("Comment=Autostart entry for myapp");
    out.println("Exec=" + installPath + "/bin/myapp_wrapper.sh");
    out.println("Icon=" + installPath + "/myapp_icon.png");
    out.flush();
    out.close();


Q: iOS NSURLSession Get Request JSON always showing outdated data I have the following doubts about the JSON data returned from using both "GET" versus "POST" request. In the following URL JSON DATA, the data is not always updated based on the server changes (eg: database). For example, if I delete all the suggestion records from the database when I had 3 previously, it still returns 3 suggestion records in my JSON response body when I call dataTaskWithRequest.
However, if I change to POST, then the JSON response body will always be updated with the actual records from the server. In my server code (Using CakePHP), I did not check for post or get data. Actually, it was intended to be a GET method, but for some reason, only POST method seems to always fetch the most up to date data from JSON as opposed to GET.
Below is my code from my iOS client, but I'm not too sure if its very useful. I was wondering if there is a cache issue for GET request as opposed to POST request? However, I tried disabling cache for NSURLSessionConfig but it had no impact.
config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;

The code base is below:
NSString *requestString = [NSString stringWithFormat:@"%@/v/%@.json", hostName, apptIDHash];

NSURL *url = [NSURL URLWithString:requestString];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:url];

NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){

    if (!error) {
        NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
        if (httpResp.statusCode == 200) {
            NSError *jsonError;
            NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
            [self printJSONOutputFromDictionary:jsonObject];
            if (!jsonError) {
                block(jsonObject, nil);
            }
            else{
                block(nil, jsonError);
            }
        }
        else{
            NSError *statusError = [self createServerUnavailableNSError:httpResp];
            block(nil, statusError);
        }
    }
    else{
        block(nil, error);
    }
}];

[dataTask resume];

In the above code fragment, the JSON body is always showing outdated data.
I really want to understand the issue, and would really appreciate if anyone could explain this issue for me.

A: Try adding the following request header:
[req addRequestHeader:@"Cache-Control" value:@"no-cache"];

I encountered the same problem as you and adding the above code solved the problem for me.
Taken from ASIHTTPRequest seems to cache JSON data always


Q: Numeric comparison during merge in R Dataframe d1:
x  y
4 10
6 20
7 30

Dataframe d2:
x   z
3 100
6 200
9 300

How do I merge d1 and d2 by "x" where d1$x should be matched against exact match or the next higher number in d2$x. Output should look like:
x   y    z
4  10  200 # (4 is matched against next higher value that is 6)
6  20  200 # (6 is matched against 6)
7  30  300 # (7 is matched against next higher value that is 9)

If merge() cannot do this, then is there any other way to do this? For loops are painfully slow.

A: This is pretty straightforward using rolling joins with data.table:
require(data.table)   ## >= 1.9.2
setkey(setDT(d1), x)  ## convert to data.table, set key for the column to join on
setkey(setDT(d2), x)  ##  same as above

d2[d1, roll=-Inf]

#    x   z  y
# 1: 4 200 10
# 2: 6 200 20
# 3: 7 300 30

A: Input data:
d1 <- data.frame(x=c(4,6,7), y=c(10,20,30))
d2 <- data.frame(x=c(3,6,9), z=c(100,200,300))

You basically wish to extend d1 by a new column. So let's copy it.
d3 <- d1

Next I assume that d2$x is sorted nondecreasingly and thatmax(d1$x) <= max(d2$x).
d3$z <- sapply(d1$x, function(x) d2$z[which(x <= d2$x)[1]])

Which reads: for each x in d1$x, get the smallest value from d2$x which is not smaller than x.
Under these assumptions, the above may also be written as (& should be a bit faster):
d3$z <- sapply(d1$x, function(x) d2$z[which.max(x <= d2$x)])

In result we get:
d3
##   x  y   z
## 1 4 10 200
## 2 6 20 200
## 3 7 30 300

EDIT1: Inspired by @MatthewLundberg's cut-based solution, here's another one using findInterval:
d3$z <- d2$z[findInterval(d1$x, d2$x+1)+1]

EDIT2: (Benchmark)
Exemplary data:
set.seed(123)
d1 <- data.frame(x=sort(sample(1:10000, 1000)), y=sort(sample(1:10000, 1000)))
d2 <- data.frame(x=sort(c(sample(1:10000, 999), 10000)), z=sort(sample(1:10000, 1000)))

Results:
microbenchmark::microbenchmark(
{d3 <- d1; d3$z <- d2$z[findInterval(d1$x, d2$x+1)+1] },
{d3 <- d1; d3$z <- sapply(d1$x, function(x) d2$z[which(x <= d2$x)[1]]) },
{d3 <- d1; d3$z <- sapply(d1$x, function(x) d2$z[which.max(x <= d2$x)]) },
{d1$x2 <- d2$x[as.numeric(cut(d1$x, c(-Inf, d2$x, Inf)))]; merge(d1, d2, by.x='x2', by.y='x')},
{d1a <- d1; setkey(setDT(d1a), x); d2a <- d2; setkey(setDT(d2a), x); d2a[d1a, roll=-Inf] }
)
## Unit: microseconds
##         expr       min            lq    median        uq       max neval
## findInterval   221.102      1357.558  1394.246  1429.767  17810.55   100
## which        66311.738     70619.518 85170.175 87674.762 220613.09   100
## which.max    69832.069     73225.755 83347.842 89549.326 118266.20   100
## cut           8095.411      8347.841  8498.486  8798.226  25531.58   100
## data.table    1668.998      1774.442  1878.028  1954.583  17974.10   100

A: cut can be used to find the appropriate matches in d2$x for the values in d1$x.
The computation to find the matches with cut is as follows:
as.numeric(cut(d1$x, c(-Inf, d2$x, Inf)))
## [1] 2 2 3

These are the values:
d2$x[as.numeric(cut(d1$x, c(-Inf, d2$x, Inf)))]
[1] 6 6 9

These can be added to d1 and the merge performed:
d1$x2 <- d2$x[as.numeric(cut(d1$x, c(-Inf, d2$x, Inf)))]
merge(d1, d2, by.x='x2', by.y='x')
##   x2 x  y   z
## 1  6 4 10 200
## 2  6 6 20 200
## 3  9 7 30 300

The added column may then be removed, if desired.

A: Try: sapply(d1$x,function(y) d2$z[d2$x > y][which.min(abs(y - d2$x[d2$x > y]))])


Q: Serialize Point, PointF Objects I am new to serialization concept and i am trying to serialize PointF class as i need to send it over socket connection (I am using ObjectOutputStream and ObjectInputStream). My problem is while sending no matter what values i have in my PointF object while sending , after receiving i get default value.
example if i sent pointF(1.0,4.0) i get (0.0,0.0).
Following is my code for implimenting serializable.
public class MyPointF extends PointF implements Serializable {

/**
 *
 */
private static final long serialVersionUID = -455530706921004893L;

public MyPointF() {
    super();
}

public MyPointF(float x, float y) {
    super(x, y);
}
}

Can anybody point out the problem?
Also, after searching a little i found that this thing happens to android.canvas.Path class also. Please correct me where I am Wrong.

A: Your superclass PointF is not serialisable.  That means that the following applies:

To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime.
During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream.

See: http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html
You will need to look at readObject and writeObject:

Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:
 private void writeObject(java.io.ObjectOutputStream out)
     throws IOException
 private void readObject(java.io.ObjectInputStream in)
     throws IOException, ClassNotFoundException;

See also here: Java Serialization with non serializable parts for more tips and tricks.

A: I finally found the solution. Thanx @Greg and the other comment that has now been deleted. The solution is that instead of extending these objects we can make stub objects. As i was calling super from constructor the x and y fields were inherited from base class that is not serializable. so they were not serialized and there values were not sent.
so i mofidfied my class as per your suggestions
public class MyPointF implements Serializable {

/**
 *
 */
private static final long serialVersionUID = -455530706921004893L;

public float x;
public float y;

public MyPointF(float x, float y) {
    this.x = x;
    this.y = y;
}
}


Q: Chrome DevTools "isSystemKey" Debugger Attribute While looking into chrome.debugger.sendCommand documentation, I came across an attribute, isSystemKey. I wonder whether this could be used to verify whether a key is typed by a human or program (similar to the isTrusted event attribute), but there doesn't appear to be any documentation on it, in the linked URL or elsewhere. Not a mention of its usage, as far as I can see.
So what does this boolean attribute do?
Some example code to illustrate, given a character c, a tab id tab_id and the debugger currently attached to that same tab:
let options = {
    'key': c,
    'type': 'keyDown',
    'nativeVirtualKeyCode': c.charCodeAt(),
    'windowsVirtualKeyCode': c.charCodeAt(),
    'macVirtualKeyCode': c.charCodeAt(),
    'isSystemKey': true // What does this change, compared to its falsy default?
}
// Pressing key
chrome.debugger.sendCommand({tabId: tab_id}, "Input.dispatchKeyEvent", options, () => {
    // Releasing key
    options.type = 'keyUp';
    chrome.debugger.sendCommand({tabId: tab_id}, "Input.dispatchKeyEvent", options, () => {
        // Detaching debugger
        chrome.debugger.detach({tabId: tab_id});
    });
});


Q: Is instabot.py safe to use? I am unfamiliar with the instaboy.py python package. I am wondering if there are any security issues with this package like possibly getting information leaked. I am wondering how does the API work if there are a lot of people using this package. Wouldn't you need your own personal Instagram API token? I am confused by the whole concept and if anyone could explain even just a little bit it will be much appreciated.

A: Bots are now easily detected by Instagram. Your account could be banned for 3 days, 7 days, 30 days or definitively if Instagram detects too many attempts
Usually bots simulate a browser via Sellenium and then create a "browse like a human" bot to create likes, follow, unfollow, etc.


Q: Refreshing SBT project in Intellij Idea switches Java to 7 I was having a Play 2.4.2 scala project built with J7 in IntelliJ Idea, then I switched the project to Play 2.5.0 with J8. I have modified J7->J8 everywhere I could think of, but for some reason, when I refresh project in SBT projects window in Intellij Idea (and it also refreshes it automatically when I change build.sbt), it sets Java version back to 7 (both options Project SDK and Project language level: in Project Structure window are set back)
I've probably missed some option, but I cannot find anything that still points to J7. Any idea?
I've tried to put this in build.sbt, but it did not fix the issue:
scalacOptions ++= Seq("-target:jvm-1.8")

Sbt compiles project fine if it is compiled SBT terminal, but I prefer to use IntelliJ Idea run option.

A: We're looking into it. Meanwhile, one workaround is editing .idea/sbt.xml and change the jdk option line to <option name="jdk" value="1.8" /> (or whatever you named the SDK in your project structure) and then refreshing your project.
Update: The latest Nightlies of the Scala plugin change how the project JDK is set, which should solve this.

A: IntelliJ has a closed ticket for this issue: https://youtrack.jetbrains.com/issue/SCL-6823
I have created a new ticket:
https://youtrack.jetbrains.com/issue/SCL-10631


Q: Where is the Upgrade Path for C# 6.0? Is it safe yet? I maintain a large number of projects, all currently written in .Net 4.5 / c# 5.  I'm interested in upgrading to C# 6.0, but cannot find any documentation on the safety of doing so.
From what I've read, upgrading to VS 2015 / C# 6 / .Net 4.6 means building our code using Roslyn / RyuJit.  (Or with msbuild 14, which uses Roslyn under the hood).
Roslyn, however, has a massive amount of open issues currently: https://github.com/dotnet/roslyn/issues/7278  Many of which are guaranteed to impact our codebase.
Similarly, RyuJit appears to be completely unstable, as recently as 6 months ago (http://nickcraver.com/blog/2015/07/27/why-you-should-wait-on-dotnet-46/)
I simply cannot find any documentation, anywhere, on safely upgrading to C# 6.0 / .Net 4.6, and yet find it extremely strange that these things are already released to RTM and VS 2015 with so many bugs out in the open.
Help?

A:
Many of which are guaranteed to impact our codebase.

I wouldn't be so sure. We are building not just Roslyn with itself, but the rest of Visual Studio, the entire .NET Framework, Windows, ASP.NET, and more with Roslyn, and have been doing so for two years now. We did test passes where we literally downloaded thousands of projects from GitHub so we could verify that code that built with the old compiler would build with the new compiler. We take compatibility with the old compilers very, very seriously.

with so many bugs out in the open.

There's a few things to know about that bug count:

*

*That includes not just the compiler, but also IDE, refactorings, debugger, and a lot of other components.

*That count includes bugs for features that haven't shipped yet. For example, a few days ago we started testing a new compiler feature that we hope to ship in C# 7, and filed 30-40 bugs on various IDE features that need to be updated to know about it.

*We file bugs for things that don't affect you. For example, any time we have a problem with one of our automated tests, we file a bug. Any time somebody realizes "huh, we could clean this up", we file a bug. We even use "issues" to discuss future language proposals as a forum, rather than a bug itself. Right now I have an issue against me which is to write a blog post that needs to be written.

*Some of these aren't actually bad bugs; they include issues like "I wish the compiler gave better error messages."

*Many of them involve running Roslyn on Linux or Mac, which is still actively under development.

If we filter to the actual list of "compiler" bugs and filter out compiler bugs for features that haven't shipped, the count is much much smaller.
And the most important bit:

*There were always bugs, in every release of the compiler. The compiler is a piece of software being written by humans, so it is by definition not perfect. We're just choosing to air our dirty laundry on GitHub instead of hiding it behind our firewall!

This is of course not to say that you won't hit a bug, but we've tried our best to make Roslyn as best a compiler as we can, with the best compatibility we can. If we had to write a document that said "here's all the ways your code isn't compatible", that would mean we failed at that. As usual, always test a bit of stuff before deploying, but that's no different than anything else.


Q: Android FTP connection problems Hi I have been trying for two days to get a simple ftp connection to transfer a small xml file. I have tried lots of different examples of code, but all seem to give the same errors.
Main FTP class code:

public class MyFTPClientFunctions {

    public FTPClient mFTPClient = null;

    public boolean ftpConnect(String host, String username, String password, int port) {
        try {
                mFTPClient = new FTPClient();
                // connecting to the host
                mFTPClient.connect(host, port);
            // now check the reply code, if positive mean connection success
            if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
                // login using username & password
                boolean status = mFTPClient.login(username, password);

                mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
                        mFTPClient.enterLocalPassiveMode();
                   return status;
            }

        //Log.d(TAG, "Error: could not connect to host " + host);
        } catch (SocketException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    private Context getApplicationContext() {
        return null;
    }

}

Main Activity code to send

send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //set up FTP file transfer here

                MyFTPClientFunctions ftpSend = new MyFTPClientFunctions();

                ftpSend.ftpConnect("xxxxxx.asuscomm.com","admin","xxxxxxxxxx",21);

            }

LogCat messages

06-22 12:09:21.460  17329-17329/com.example.rats.moham_2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.rats.moham_2, PID: 17329
    android.os.NetworkOnMainThreadException
            at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
            at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
            at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
            at java.net.InetAddress.getByName(InetAddress.java:305)
            at org.apache.commons.net.SocketClient.connect(SocketClient.java:203)
            at com.example.rats.moham_2.MyFTPClientFunctions.ftpConnect(MyFTPClientFunctions.java:25)
            at com.example.rats.moham_2.MainActivity$3.onClick(MainActivity.java:155)
            at android.view.View.performClick(View.java:4780)
            at android.view.View$PerformClick.run(View.java:19866)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

A: This Exception is usualy thrown, if you are using the network on the main thread.
Please use Async Tasks.


Q: MongoDB options in connection string are being interpreted as the database name I am trying to set the maxPoolSize via connection string in MongoDB following this piece of documentation. Here is my connection string:
mongodb://localhost:27017/databaseName?maxPoolSize=200

However, instead of having the database databaseName with the maxPoolSize equals to 200, I'm getting a database called databaseName?maxPoolSize=200. This is, Mongo is getting everything (name + options) as the database name.
Some info:

*

*Mongo version: 3.2.10

*Connecting using Morphia 1.1.0

I will be happy to provide any further information.

A: if you are doing
MongoClient client = new MongoClient(
"mongodb://localhost:27017/databaseName?maxPoolSize=200");

then dont do that, instead do as following,
MongoClient client = new MongoClient(
new MongoClientURI(
"mongodb://localhost:27017/databaseName?maxPoolSize=200"));

because you need to tell mongo that you are passing some options along the connection string.
if you think i misunderstood your question. please post the piece of code where you are trying to get a connection.

A: You can try something like this.
MongoClientURI uri = new MongoClientURI("mongodb://localhost:27017/databaseName?maxPoolSize=200");
MongoClient mongoClient = new MongoClient(uri);
Morphia morphia = new Morphia();
Datastore datastore = morphia.createDatastore(mongoClient, "dbname");

Alternatively
MongoClientOptions.Builder options = new MongoClientOptions.Builder();
//set your connection option here.
options.connectionsPerHost(200); //max pool size
MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017), options.build());
Morphia morphia = new Morphia();
Datastore datastore = morphia.createDatastore(mongoClient, "dbname");


Q: VS Code crashes when I close windows PowerShell I mostly open VS Code with "code." command from powershell. But today when I opened the VS Code and closed the Powershell VS Code also crashed:

Error Message:
(node:4628) Electron: Loading non-context-aware native module in renderer: '\?\C:\Users\MuhammadQasim\AppData\Local\Programs\Microsoft VS Code\resources\app\node_modules.asar.unpacked\spdlog\build\Release\spdlog.node'. This is deprecated, see https://github.com/electron/electron/issues/18397.
(node:9792) Electron: Loading non-context-aware native module in renderer: '\?\C:\Users\MuhammadQasim\AppData\Local\Programs\Microsoft VS Code\resources\app\node_modules.asar.unpacked\spdlog\build\Release\spdlog.node'. This is deprecated, see https://github.com/electron/electron/issues/18397.


Q: How do I validate $_GET to allow only specific key Let's say my current URL is
http://domain.com/category/cars/?page=2

How do I validate on this page to allow only $_GET['page']?
If user type on URL something below, will go to error page.
http://domain.com/category/cars/?page=2&bar=foo
http://domain.com/category/cars/?foo=bar&page=2
http://domain.com/category/cars/?foo=bar&bar=foo

Let me know..

A: Well, you could use:
if( count($_GET) > 1 || !isset($_GET['page'])) { /*error*/ }

A: You should care only of GET/POST variables used in your application. Validate and escape them accordingly, check if they're set. The rest should be ignored - you don't need to care of them and display errors.

A:     $allowedKeys = array('page');

    $_GET = array_intersect_key($_GET, array_flip($allowedKeys));

You won't have to worry about your undesired parameters and values, as they will not be accepted via the $_GET method. With the above code, the only allowed $_GET parameters is 'page'

A: I might do this:
<?php
if ($_GET)
  {
    foreach($_GET as $key=>$value)
      {
        if($key!='page')
          {
            $error=true;
          }
      }
  }
?>


Q: How do I check if a value is changed a certain amount within a second? I'm monitoring the Pitch and Roll Values in my application and i want to monitor to see if they change by 5 degrees within a second and then run a process. Currently my code looks like this:
 CMAttitude *attitude;
CMDeviceMotion *motion = scoringManage.deviceMotion;
attitude = motion.attitude;
basePitch = degrees(attitude.pitch);
baseRoll = degrees(attitude.roll);

if((pitchfloat >= basePitch+5) || (pitchfloat <= basePitch-5)) {

}
if((rollfloat >= baseRoll+5) || (rollfloat <= baseRoll-5)) {

}

That is called by:
yprTime = [NSTimer scheduledTimerWithTimeInterval:(1.0/1.0) target:self selector:@selector(yprscore) userInfo:nil repeats:YES];

This process runs every second along with my timer but when the value is changed it will run that loop many times.
The Problem is that the if statements run like 20 times too many within that second.

A: if you only want it to run once the value is changed you need to set up a BOOL. Within your if pitch > 5 statement setup another if that checks that BOOL
if((pitchfloat >= basePitch+5) || (pitchfloat <= basePitch-5)) {
 if (firstTimeBOOLCheckisTrue == NO) {

 firstTimeBOOLCheckisTrue = YES;

 [self doSomething];
    }
}

(void *)doSomething{

if (imReadytoCheckPitchAgain == YES){
firstTimeBOOLCheckisTrue = NO;

}


Q: Reading in a table with non-standard row names in R? I have a .txt file that looks like this:
       xyz ghj asd qwe
a / b:  1   2   3   4
c / d:  5   6   7   8
e / f:  9   10  11  12
        ...
        ...

I'm trying to use read.table(header = T) but it seems to be misinterpreting the row name. Is there a way to deal with this in read.table() or should I just use readLines()

A: There is no option to just skip a few characters in each row using a read.table option.
Instead, you can call read.table twice, once for all the data after the first row, and the second time for the header.
Where your data are in a file called "test.txt", you would do:
library(magrittr)
tmp <- read.table(file="test.txt", sep="", stringsAsFactors = FALSE, skip=1)[, -c(1:3)] %>%
         setNames(read.table(file="test.txt", sep="", stringsAsFactors = FALSE, nrows=1))

> tmp
  xyz ghj asd qwe
1   1   2   3   4
2   5   6   7   8
3   9  10  11  12
>

Package magrittr is what gives you the pipe operator %>% that allows you to read the data and the header separately, but put them together in a single line. If you have a sufficiently-new R version you can use the |> operator instead, without the magrittr package.


Q: Difference between use of sleep thread and refresh page in php as server event source I have built a chat application using server sent events .But sse are not supported across all browsers.I was planning to use long polling ajax for polling source page for browser which do not support sse.
What the server page does is check db for new messages and output it using echo statement.
By refreshing page every X seconds using header("refresh: X;");
I saw another approach by which the
while(1){

    echo statemenst....
    echo statemenst....

    sleep(5);
    }

So my question is: If I sent ajax request with a very large waiting time will it receive response If  header("refresh: X;"); is used .Or I need to use the infinite loop?.And if page refreshes will the requests to that page that are waiting for response get affected in someway ?
 function waitForMsg(){
        /* This requests the url "msgsrv.php"
        When it complete (or errors)*/
        $.ajax({
            type: "GET",
            url: "msgsrv.php",

            async: true, /* If set to non-async, browser shows page as "Loading.."*/
            cache: false,
            timeout:50000, /* Timeout in ms */

            success: function(data){ /* called when request to barge.php completes */
                addmsg("new", data); /* Add response to a .msg div (with the "new" class)*/
                setTimeout(
                    waitForMsg, /* Request next message */
                    1000 /* ..after 1 seconds */
                );
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                addmsg("error", textStatus + " (" + errorThrown + ")");
                setTimeout(
                    waitForMsg, /* Try again after.. */
                    15000); /* milliseconds (15seconds) */
            }
        });
    };


Q: Create list of dictionaries when values of original dictionary are lists I have a dictionary where the values for each key are a list. I would like to extract a key value pair for each key in the dictionary with its corresponding element value from the list, and then store individual dictionaries in a new list.
So, if I have a simple dictionary like the following:
my_dict = {'Folder': ['2021-03-12_020000', '2021-03-12_020000', '2021-03-12_020000'],
           'Filename': ['2021-03-12_020000-frame79.jpg', '2021-03-12_020000-frame1.jpg', '2021-03-
                       12_020000-frame39.jpg'],
           'Labeler': ['Labeler 2', 'Labeler 2', 'Labeler 1']}

My desired output list would be a list of dictionaries, where each dictionary has the keys from my_dict with the corresponding value from the original values lists in my_dict:
final_list = [{'Folder':'2021-03-12_020000', 'Filename': '2021-03-12_020000-frame79.jpg', 'Labeler': 'Labeler 2'},
            {'Folder':'2021-03-12_020000', 'Filename': '2021-03-12_020000-frame1.jpg', 'Labeler': 'Labeler 2'},
            {'Folder':'2021-03-12_020000', 'Filename': '2021-03-12_020000-frame39.jpg', 'Labeler': 'Labeler 1'}]

A: for dynamic key and value:
my_dict = {'Folder': ['2021-03-12_020000', '2021-03-12_020000', '2021-03-12_020000'],
           'Filename': ['2021-03-12_020000-frame79.jpg', '2021-03-12_020000-frame1.jpg', '2021-03- 12_020000-frame39.jpg'],
           'Labeler': ['Labeler 2', 'Labeler 2', 'Labeler 1']}

new_dict = {}
for key in my_dict:
    for idx, value in enumerate(my_dict[key]):
        if idx not in new_dict:
            new_dict[idx] = [(key,value)]
        else:
            new_dict[idx].append((key,value))
new_list = []
for key,value in new_dict.items():
    new_list.append(dict(value))

print(new_list)

output
[{'Folder': '2021-03-12_020000', 'Filename': '2021-03-12_020000-frame79.jpg', 'Labeler': 'Labeler 2'}, {'Folder': '2021-03-12_020000', 'Filename': '2021-03-12_020000-frame1.jpg', 'Labeler': 'Labeler 2'}, {'Folder': '2021-03-12_020000', 'Filename': '2021-03- 12_020000-frame39.jpg', 'Labeler': 'Labeler 1'}]

A: You can use zip for the task:
my_dict = {
    "Folder": ["2021-03-12_020000", "2021-03-12_020000", "2021-03-12_020000"],
    "Filename": [
        "2021-03-12_020000-frame79.jpg",
        "2021-03-12_020000-frame1.jpg",
        "2021-03-12_020000-frame39.jpg",
    ],
    "Labeler": ["Labeler 2", "Labeler 2", "Labeler 1"],
}

final_list = [
    {"Folder": a, "Filename": b, "Labeler": c}
    for a, b, c in zip(
        my_dict["Folder"], my_dict["Filename"], my_dict["Labeler"]
    )
]

print(final_list)

Prints:
[
    {
        "Folder": "2021-03-12_020000",
        "Filename": "2021-03-12_020000-frame79.jpg",
        "Labeler": "Labeler 2",
    },
    {
        "Folder": "2021-03-12_020000",
        "Filename": "2021-03-12_020000-frame1.jpg",
        "Labeler": "Labeler 2",
    },
    {
        "Folder": "2021-03-12_020000",
        "Filename": "2021-03-12_020000-frame39.jpg",
        "Labeler": "Labeler 1",
    },
]

A: Here is code assuming all items are inter related.
my_dict = {'Folder': ['2021-03-12_020000', '2021-03-12_020000', '2021-03-12_020000'],
           'Filename': ['2021-03-12_020000-frame79.jpg', '2021-03-12_020000-frame1.jpg', '2021-03- 12_020000-frame39.jpg'],
           'Labeler': ['Labeler 2', 'Labeler 2', 'Labeler 1']}

result_dict = []

for i, (folder, filename, labler) in enumerate(zip(my_dict['Folder'], my_dict['Filename'], my_dict['Labeler'])):
    result_dict.append({"Folder":folder,'Filename':filename,"Labeler":labler })

print(result_dict)

output:
[
  {
    "Folder": "2021-03-12_020000",
    "Filename": "2021-03-12_020000-frame79.jpg",
    "Labeler": "Labeler 2"
  },
  {
    "Folder": "2021-03-12_020000",
    "Filename": "2021-03-12_020000-frame1.jpg",
    "Labeler": "Labeler 2"
  },
  {
    "Folder": "2021-03-12_020000",
    "Filename": "2021-03- 12_020000-frame39.jpg",
    "Labeler": "Labeler 1"
  }
]


Q: MVC View Lookup Caching. How long is it cached? and where is it cached? We are optimising a site and have read about the issue of the initial view lookup taking a long time. Subsequent lookups of the views are then much faster. Mini-profiler shows that a lot of the time is in the initial find view (I know I can use a ~ path to reduce this) and whatever else is done at this stage.
Where is the caching done? How long are view lookups etc cached? Can I see what is cached? Can we do anything to cause it to pre-load so there isn't a delay?
We have many views that are often not visited for hours and I don't want sudden peaks and troughs in performance.
We are using Azure and have a number of web role instances. Can I assume that each web role has its own cache of the view lookup? Can we centralise the caching so that it only occurs once per application?
Also I read MVC4 is faster at finding views? Does anyone have any figures?

A: The default cache is 15min and is stored in the HttpContext.Cache, this is all managed by the System.Web.Mvc.DefaultViewLocationCache class. Since this uses standard ASP.NET caching you could use a custom cache provider that gets its cache from WAZ AppFabric Cache or the new caching preview (there is one on NuGet: http://nuget.org/packages/Glav.CacheAdapter). Using a shared cache will make sure that only 1 instance needs to do the work of resolving the view. Or you could go and build your own cache provider.
Running your application in release mode, clearing unneeded view engines, writing the exact path instead of simply calling View, ... are all ways to speed up the view lookup process. Read more about it here:

*

*http://samsaffron.com/archive/2011/08/16/Oh+view+where+are+thou+finding+views+in+ASPNET+MVC3+

*http://blogs.msdn.com/b/marcinon/archive/2011/08/16/optimizing-mvc-view-lookup-performance.aspx
You can pre-load the view locations by adding a key for each view to the cache. You should format it as follows (where this is the current VirtualPathProviderViewEngine):
string.Format((IFormatProvider) CultureInfo.InvariantCulture, ":ViewCacheEntry:{0}:{1}:{2}:{3}:{4}:", (object) this.GetType().AssemblyQualifiedName, (object) prefix, (object) name, (object) controllerName, (object) areaName);

I don't have any figures if MVC4 is faster, but it looks like the DefaultViewLocationCache code is the same as for MVC3.

A: To increase my cachetime to 24 hours  I used the following in the Global.asax
    var viewEngine = new RazorViewEngine
                         {ViewLocationCache = new DefaultViewLocationCache(TimeSpan.FromHours(24))};
    //Only allow Razor view to improve for performance
    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(viewEngine);

Also this article ASP.NET MVC Performance Issues with Render Partial was also interesting.
Will look at writing my own ViewLocationCache to take advantage of shared Azure caching.


Q: Embedded Google Map in modal is showing blank until window resizes manually I have a google map that is embedded into a modal, but when clicking to open the modal, the map appears blank.

After googling i thought i found a solution using jquery to resize the window again but it doesnt seem to work.
The current code i'm using:
component.html:

          Map's and Directions

component.css
#map {
  width: 100vw;
  height: 100vh;
  max-width: 100%;
  margin: 0;
  padding: 0;
}

component.ts
    export class AppComponent implements OnInit {
  title = 'app';

  modalActions = new EventEmitter<string|MaterializeAction>();

  ngOnInit() {
    var mapProp = {
          center: new google.maps.LatLng(-34.397, 150.644),
          zoom: 11,
          mapTypeId: google.maps.MapTypeId.ROADMAP
      };
    var map = new google.maps.Map(document.getElementById("map"), mapProp);
    $(document).ready(function() {
        google.maps.event.addListener(map, "idle", function(){
            google.maps.event.trigger(map, 'resize');
        });
    });
  }
}

index.html

Can anyone see what im missing?
I m doing the app in angular 2 btw


Q: Join table, for which the table name has to be grabbed in the same query This question is not to discuss if the setup of the DB is as it should be, i'm not happy with how it is, but it is how it is and a refactor will not be done by the DBA at this moment.
What i am looking for is a way to join a table, for which i do not in advance know the table name but it is in the table i want to do the join against.
So:

TABEL transactions
trans_id  autherizer
001Bar    payment_provider_a
001Foo    payment_provider_b

TABLE payment_provider_a
trans_id  amount
001Bar    50

TABLE payment_provider_b
trans_id  amount
001Foo    50

The table names are fictional, but the setup is identical. There is a transaction table, which stores an transaction_id and a payment_provider string name (with a lot of additional data, which is not relevant for the question).
Would there be anyway to get all the data from the transaction table and in that query do directly a join on the payment_provider table, for which we only now what that table can be from the transaction table.
I have tagged it with PHP as well, since i want to make the call with PDO. Whole PHP snippets are not required, but if you insist ;). A push in the right direction for the query it self would be sufficient. I am aware that i am lacking the example of what i have tried. But to be honest i haven't tried that much because i can't really think of something, it's the first time i am in this kind of need for such a query.

A: Not overly clean, but you can try this:
SELECT * FROM transactions t JOIN
    (
        SELECT 'payment_provider_a' AS name,* FROM payment_provider_a
    UNION
        SELECT 'payment_provider_b' AS name,* FROM payment_provider_b
    ) p ON t.payment_provider = p.name AND t.trans_id=p.trans_id

Note that all payment_provider_x tables must have the same number and types of columns. Otherwise you'll need to select only the fields that are actually common (there are ways around this if needed).


Q: Debugging visual basic dll library from asp.net hosted in IIS I have the following problem.
I have some project written in Visual Basic (not Visual Basic .NET but simple Visual Basic - sic!). I can compile it and generate a dll.
Then inside my web application I add reference to this dll library. When I run my web application hosted in default Visual Studio server, everything is fine and I can debug my Visual Basic project. However, when I host my web application in IIS then I can't. Code does not stop in my breakpoint.
My asp.net catch the exception when I try to execute some method from the mentioned library which is something like:
Unable to cast COM object of type 'xxx' to interface type 'yyy'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{4C2875B5-3265-306B-9C74-1BEC98986B1A}' failed due to the following error: Error loading type library/DLL. (Exception from HRESULT: 0x80029C4A (TYPE_E_CANTLOADLIBRARY)).

Can someone please help me because I've been struggling for 2 days without success.

A: Are you debugging using "Attach to Process"?
First determine the w3wp.exe process:
For IIS6

*

*Start > Run > Cmd

*Go To Windows > System32

*Run cscript iisapp.vbs

*You will get the list of Running
Worker ProcessID and the Application
Pool Name.

For IIS7

*

*Start > Run > Cmd

*Go To Windows > System32 > Inetsrv

*Run appcmd list wp
Note the Process ID (PID).
Next in Visual Studio:

*

*Debug > Attach to Process...

*Find the w3wp.exe with the right PID and attach

Your breakpoints should work.


Q: Get a a process window handle by click in C# At the moment, I can get a list of running processes with a main window using System.Diagnostics.Process.GetProcesses() and executing a simple LINQ query.
Then, I can import user32.dll and the SetWindowPos function and I manipulate other processes' window parameters.
Ok, it works. Now I'd like to select a window of a process, let's say calc.exe, by clicking it. In other words, I'd like to obtain a Process object (and then the MainWindowHandle) with a hook that catches the process name when I click on its window.
How can I achieve this?

A: I don't know how this is done in C#, but you have also tagged this question WinAPI so I can help there. In WinAPI, it can be done like so:
#include <stdio.h>
#include <Windows.h>
#include <Psapi.h>
#pragma comment(lib, "Psapi.lib")

int main(void)
{
  /* Hacky loop for proof of concept */
  while(TRUE) {
    Sleep(100);

    if(GetAsyncKeyState(VK_F12)) {
      break;
    }

    if(GetAsyncKeyState(VK_LBUTTON)) {
      HWND  hwndPt;
      POINT pt;

      if(!GetCursorPos(&pt)) {
        wprintf(L"GetCursorPos failed with %d\n", GetLastError());
        break;
      }

      if((hwndPt = WindowFromPoint(pt)) != NULL) {
        DWORD  dwPID;
        HANDLE hProcess;

        GetWindowThreadProcessId(hwndPt, &dwPID);

        hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, dwPID);

        if(hProcess == NULL) {
          wprintf(L"OpenProcess failed with error: %d\n", GetLastError());
        } else {
          wchar_t lpFileName[MAX_PATH];
          DWORD   dwSize = _countof(lpFileName);

          QueryFullProcessImageName(hProcess, 0, lpFileName, &dwSize);
          wprintf(L"%s\n", lpFileName);

          CloseHandle(hProcess);
        }
      }
    }
  }

  return EXIT_SUCCESS;
}

Example result:

In this case, I am simply polling to get the mouse click. A more proper way would be to use some sort of windows hook.

A: As Mike Kwan said, you'll be better of writing a hook though both approaches have their own drawbacks, but bjarneds already did a good work on this. Have a look @ DotNET Object Spy. It's written in C# and will serve for your needs and more.
You should also note that using hooks are becoming redundant by the day. Depending on what you want to do, other winapis like GetForegroundWindow might serve better.


Q: Concurrency about Hibernate first level cache Background: We have a distributed system running same web application on multiple machines. Application on each machine will w/r data to one database (the database is Oracle cluster). We have a load balancer in front of those web application servers (pls ignore the web server for now).
Problem: We have a feature, e.g. shopping cart, will save a shopping item into a customer's cart. The code should like:
1: Load cart by Hibernate
2: if [Shopping item exists in Cart]
   3: update quantity
   else
   4: add new cartItem

We met concurrency problem here. If multiple users login with same customer account, and add shopping item to their cart at the same time, duplicate cart item will appear.
Because Hibernate using First level cache (aka session cache), and each session cache the data when the transaction begin. Sessions does not know other sessions have added same shopping item in step 2, if other sessions completed between step 1 and step.
We do not use Second level cache for now, since it will not improve too much performance. Still, second level cache does not seemed to be a solution here, since Hibernate will read First level catch at first.
Anyone solved this kind of problem before?


Q: how to send image in pushplugin in BigPictureStyle method? I am developing a cordova application, I would like to know how to send image in pushplugin like BigPictureStyle as done by flipkart myntra and all ..
there is a pull request https://github.com/phonegap-build/PushPlugin/pull/498
for the same but how to implement this?
how to send the payload so as to show the image in the notification bar.

A: Install the modified plugin

*

*Clone locally and pull the changes

*

*Clone PushPlugin locally
git clone https://github.com/phonegap-build/PushPlugin.git

*Add a remote to the repository where the modifications are
git remote add bigpicture-repo https://github.com/ajoyoommen/PushPlugin.git

*Then fetch the changes
git fetch bigpicture-repo

*Merge the changes you just fetched (from the remote) into you master
git merge bigpicture-repo/master

OR

*Directly clone my repository containing the feature
git clone https://github.com/ajoyoommen/PushPlugin

Uninstall the old plugin
cordova plugin remove com.phonegap.plugins.PushPlugin

Install the new plugin from your filesystem
cordova plugin add /home/myname/Documents/PushPlugin

Send messages from your server to your application. If the payload has bigPicture in it, with a URL, that image will be downloaded and displayed in a Big Picture style notification.


Q: .Net 3.5 Winforms Basic Dialog with Label Autosize for custom text contents I want a form containing:
+----------------------------------------+
| Dialog Title                          X|
+----------------------------------------+
+----------------------------------------+
|icon   |                                |
|32x32px| One-line label (Heading)       |
|       +--------------------------------+
|       |                                |
|       | Message label with auto-wrap   |
|       | text according to any given    |
|       | string.                        |
+-------+--------------------------------+
| row for dialog buttons...              |
+----------------------------------------+

I'll gladly answer any questions; the basic idea is still simple (though I cannot get it to work): Given any message string containing possible newlines the dialog (a Form) should keep its width but grow vertically depending on the message.
Any way how this can be done?

A: I think the component that you will find most useful is TableLayoutPanel. Find it under “Containers” in the Toolbox. Set the TableLayoutPanel’s Dock = Fill.
You can use it to lay out the controls in columns and rows. Once a control is inside the TableLayoutPanel, you can use the ColumnSpan property on such a control to span it across multiple columns; I’d use this for the button row at the bottom, i.e. make a new panel for the button row and put the buttons inside that. For the icon, of course, use RowSpan instead.
Experiment with various values of Anchor, AutoSize  and AutoSizeMode for some of the controls, especially the message label that you want to grow automatically. If you set the TableLayoutPanel and the Form to AutoSize = true, then the window will grow automatically with the text contents.

A: You could try handling the TextChanged event of the label and measure the size of the string using something like this:
Graphics g = Graphics.FromHwnd(this.Handle);
SizeF s = g.MeasureString(yourLabel.Text, yourLabel.Font, yourLabel.Width);

After this, knowing the sizes of the other controls you can modify the size of the window accordingly. I am assuming that you only want to resize the window vertically.

A: Try a TableLayoutPanel for the layout and set its Dock property to Fill to occupy the entire Form. Then plop your "one-line" and "message" labels into their respective cells and set their Dock properties to Fill to occupy the entire cell.
If you really want to resize the entire Form to fit any message at runtime, you may have to use Graphics.MeasureString to determine the area you need to contain the string and then resize the form to contain that area.

A: Create your own new Form and show it as a dialog box. You can put whatever/however you want on that form.
Here you have a tutorial that will show you how to do the hardest part.

A: You might try to ask for the position of the last character
TextBox box = new TextBox();
box.Text = "...";
var positionOfLastCharacter = box.GetPositionFromCharIndex(box.TextLength);

The you can calculate the necessary height of the textbox and the form.
Edit: That will give you the top left corner of the last character, you should add 10px or so to make the last line fit.


Q: Python-docx header / footer error from docx import Document

d = Document('/tmp/doc_with_header.docx')

d.sections[0].headers[0].add_paragraph(text='moar header')
d.save('/tmp/moar_headers.docx')

this is the code
here is the error
AttributeError: 'Section' object has no attribute 'header'

A: Looks like, you've got this solution from this page, yeah? Unfortunately, it's not the actual documentation, but only API suggestion, for further implementation. Just promises and nothing more at the moment=\


Q: Using Math.Round(ReportItems!category.Value,MidpointRounding.AwayFromZero) returns incorrect value I am using
=Math.Round(ReportItems!category.Value,MidpointRounding.AwayFromZero)

in a tablix row, which results incorrect value.
5.48 is rounding to 5
Instead, I would like to see 5.48 as 6.

A: What you are asking for is not rounding away from zero, it is Ceiling for positive numbers and Floor for negative numbers.

A: MidpointRounding.AwayFromZero Is a way of defining how the midpoint value is handled.  The midpoint is X.5.  So, 4.5 is rounded to 5, rather than 4, which is what would happen in the case of MidpointRounding.ToEven.  Round is completely correct.
If you want to write a function that rounds all non-integer values to the next highest integer then that operation is Math.Ceiling, not Round.


Q: Subscription' is not assignable to type I'm having a problem getting a service to display results on page.  The error is the subscribing method returns a subscription type and I'm stuck trying to get it to a products array.  The products are in a json file.
Setup:
I'm trying to learn Angular 2 by going through a tutorial.  The tutorial is dated and I'm using the latest version of angular (ng -v = @angular/cli: 1.4.2).  I used ng new and ng generate to setup app.
product-list.component.ts
export class ProductListComponent implements OnInit {

  pageTitle = 'Product List';
  imageWidth = 50;
  imageMargin = 2;
  showImage = false;
  listFilter = '';
  products: IProductList[];
  subscription: Subscription;
  errorMessage = '';

  constructor(private _productListService: ProductListService) {
  }

  ngOnInit() {
**// ERROR - 'Subscription' is not assignable to type 'IProductList[]'**
    this.products = this._productListService.getProducts()  // ******** ERROR ******
      .subscribe(
        products => this.products = products,
        error => this.errorMessage = <any>error);
  }

product-list.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import { IProductList } from './product-list';

@Injectable()
export class ProductListService {
  private _productListUrl = 'api/product-list/product-list.json';

  constructor(private _http: Http) { }

  getProducts(): Observable<IProductList[]> {
    return this._http.get(this._productListUrl)
            .map((response: Response) => <IProductList[]>response.json())
            .do(data => console.log('All: ' + JSON.stringify(data)))
            .catch(this.handleError);
  }

  private handleError(error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server Error');
  }
}

product-list.component.html

      {{product.productName}}
      {{product.productCode | lowercase }}
      {{product.releaseDate}}
      {{product.price | currency:'USD':true:'1.2-2' }}
      <app-ai-star [rating] = 'product.starRating'
           (ratingClicked)='onRatingClicked($event)'></app-ai-star>

A: The problem is that you want to make your subscription = to the getProducts() call.
ngOnInit() {
    this.subscription = this._productListService.getProducts() // subscription created here
      .subscribe(
        products => this.products = products, // value applied to products here
        error => this.errorMessage = <any>error);
  }

A: The value of this.products is assigned in subscribe(). You can ignore the returned subscription object as in code snippet below.
ngOnInit() {
    this._productListService.getProducts()
      .subscribe(
        products => this.products = products,
        error => this.errorMessage = <any>error);
  }


Q: how to use distinct keyword to filter object i have a project list where i can get all details about projects. In project class,i have object of customer in project ,  i just want to filter that list according to customer. how can i do this .
public ICollection<Project> GetProjectBasicDetailsByProjectTypeCustomerID(ProjectType projectType, string custName, string cordinatorName, string projectName)
    {
        oLog.Debug("Started");
        ISession session = DataAccessLayerHelper.OpenReaderSession();
        ITransaction transaction = null;
        ICollection<Project> projectList = null;
        try
        {
            transaction = session.BeginTransaction();
            ICriteria criteria = session.CreateCriteria(typeof(Project),"Project")
                .CreateAlias("Project.customer","customer",NHibernate.SqlCommand.JoinType.InnerJoin)
                .CreateAlias("Project.Coordinator", "Coordinator", NHibernate.SqlCommand.JoinType.InnerJoin)
                .Add(Restrictions.Eq("Project.ProjectType", projectType));

            projectList = criteria.List<Project>().ToList();

            session.Flush();
            transaction.Commit();
        }
        catch (Exception ex)
        {
            if (transaction != null && transaction.IsActive)
                transaction.Rollback();
            oLog.Error(ex);
        }
        finally
        {
            if (transaction != null)
                transaction.Dispose();

            if (session != null && session.IsConnected)
                session.Close();
        }
        oLog.Debug("End");
        return projectList;
    }

A: If I understand you correctly you would like to get the distinct customers from your projects ?
In this case I think something like this should work (this should give you the dictinct project IDs from this criteria - maybe there is a way to get the projects directly - but I can't test this right now:
ICriteria criteria = session.CreateCriteria(typeof(Project),"Project")
                .SetProjection(Projections.Distinct(Projections.Property("project.Id")))
                .CreateAlias("Project.customer","customer",NHibernate.SqlCommand.JoinType.InnerJoin)
                .CreateAlias("Project.Coordinator", "Coordinator", NHibernate.SqlCommand.JoinType.InnerJoin)
                .Add(Restrictions.Eq("Project.ProjectType", projectType));


Q: LNK1104: cannot open file 'wxbase28d.lib' I am trying to compile existing project created using wxWidgets library.
I successfully compiled wxWidgets 2.8.12 library.
Now, I am trying to compile my project.
But I get error:
fatal error LNK1104: cannot open file 'wxbase28d.lib'

Afterwards I added some variables in settings like:
C/C++->Preprocessor Definitions:
WIN32;__WXMSW__;_WINDOWS;_DEBUG;__WXDEBUG__;_CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)

VC++ Directories->Include Directories:
D:\instantclient_12_1\sdk\include;$(WXWIN)\lib\vc_lib\mswd;$(WXWIN)\include;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSdkDir)include;$(FrameworkSDKDir)\include;

Linker->General->Additional Library Directories:
$(WXWIN)\lib\vc_lib;E:\app\vasyl\product\11.1.0\db_1\OCI\lib\MSVC\vc71;$(WXDIR284)\lib\vc_lib;%(AdditionalLibraryDirectories)

Resources->General->Additional Include directories:
$(WXWIN)\include;c:\wxMSW284\include;$(WXDIR284)\include;%(AdditionalIncludeDirectories)

Now, the situation is like this:
1>MSVCRTD.lib(MSVCR100D.dll) : error LNK2005: _free already defined in LIBCMTD.lib(dbgfree.obj)
1>MSVCRTD.lib(MSVCR100D.dll) : error LNK2005: _malloc already defined in LIBCMTD.lib(dbgmalloc.obj)
1>MSVCRTD.lib(MSVCR100D.dll) : error LNK2005: _realloc already defined in LIBCMTD.lib(dbgrealloc.obj)
1>MSVCRTD.lib(MSVCR100D.dll) : error LNK2005: _memmove already defined in LIBCMTD.lib(memmove.obj)
1>MSVCRTD.lib(MSVCR100D.dll) : error LNK2005: _tolower already defined in LIBCMTD.lib(tolower.obj)
1>MSVCRTD.lib(MSVCR100D.dll) : error LNK2005: _isalpha already defined in LIBCMTD.lib(_ctype.obj)
1>MSVCRTD.lib(MSVCR100D.dll) : error LNK2005: _isdigit already defined in LIBCMTD.lib(_ctype.obj)
1>MSVCRTD.lib(MSVCR100D.dll) : error LNK2005: _isspace already defined in LIBCMTD.lib(_ctype.obj)
1>MSVCRTD.lib(MSVCR100D.dll) : error LNK2005: _strtol already defined in LIBCMTD.lib(strtol.obj)
1>MSVCRTD.lib(MSVCR100D.dll) : error LNK2005: _strtoul already defined in LIBCMTD.lib(strtol.obj)
1>MSVCRTD.lib(MSVCR100D.dll) : error LNK2005: __strtoi64 already defined in LIBCMTD.lib(strtoq.obj)
1>MSVCRTD.lib(MSVCR100D.dll) : error LNK2005: __strtoui64 already defined in LIBCMTD.lib(strtoq.obj)
1>MSVCRTD.lib(MSVCR100D.dll) : error LNK2005: __errno already defined in LIBCMTD.lib(dosmap.obj)
1>MSVCRTD.lib(MSVCR100D.dll) : error LNK2005: __vsprintf_p already defined in LIBCMTD.lib(vsnprnc.obj)
...
...
etc.

Can someone help me spot what am I doing wrong?

A: You're using different CRT settings (static vs DLL) for your project and the library. Make sure to (re)build both of them using the same option, either /MD[d] or /MT[d].

A: There are many possible causes for this linker error. First adress to check is MSDN: https://msdn.microsoft.com/en-us/library/ts7eyw4s.aspx
What is $(WXWIN) and how does it differ from $(WXDIR284)? It seems, you include wxWidgets path twice...


Q: Finding record which doesn't contain some value in array fields I am using sequelize + typescript over node (with postgresql db) and I have the following model:
id: number,
someField: string,
arr1: number[],
arr2: number[]

and I'm trying to find all records in which arr1 and arr2 don't contain a certain value.
As far as I've seen my only option in one query is a mix between Op.not and Op.contains,
so I've tried the following queries:
/// Number 1
where: {
            arr1: {
                [Op.not] : {[Op.contains]: [someValue]}
            },
            arr2: {
                 [Op.not] : {[Op.contains]: [soemValue]}
            }
        },
/// Number 2
where: {
            [Op.not]: [
                 {arr1: {[Op.contains]: [someValue]}},
                 {arr2: {[Op.contains]: [someValue]}}
             ]
         },

Now, number 1 does compile in typescript but when trying to run it the following error returns:
{
    "errorId": "db.failure",
    "message": "Database error occurred",
    "innerError":
    {
        "name": "SequelizeValidationError",
        "errors":
        [
            {
                "message": "{} is not a valid array",
                "type": "Validation error",
                "path": "arr1",
                "value": {},
                "origin": "FUNCTION",
                "instance": null,
                "validatorKey": "ARRAY validator",
                "validatorName": null,
                "validatorArgs": []
            }
        ]
    }
}

So I tried number 2, which didn't compile at all with the following TS error:
Type '{ [Op.not]: ({ arr1: { [Op.contains]: [number]; }; } | { arr2: { [Op.contains]: [number]; }; })[]; }' is not assignable to type 'WhereOptions<any>'.
  Types of property '[Op.not]' are incompatible.
    Type '({ arr1: { [Op.contains]: [number]; }; } | { arr2: { [Op.contains]: [number]; }; })[]' is not assignable to type 'undefined'

So the question is what am I doing wrong, or in other words, how can I make that query without querying all records and filter using code
Thanks!

A: You have to use notIn and not contain maybe then it will work:

Official Docs: https://sequelize.org/master/manual/model-querying-basics.html

where: {
        arr1: {
               [Op.notIn]: someValueArray
        },
        arr2: {
               [Op.notIn]: someValueArray
        }
     },

A: Apparently the second option is the correct one, but what was incorrect was the types of sequelize, @ts-ignore fixes the problem


Q: Error when getting row().data() from indexed db I tried to get the row data using
row(index).data()
Where index is the row index.
I get the data initially pushed to the table. But the update I do in "columnDefs" render() function is not reflected.
The value I return in render() function is reflecting in table but it is not got in row().data()
please see the screenshot value in table but it is null in the console. I have consoled row().data(). [1]: https://i.stack.imgur.com/5IP56.png
please see I have returned value 10 for the column in "columnDefs" render() function and the value has come in table. [2]: https://i.stack.imgur.com/9YMnq.png

A: I fixed the issue like this.
columnDefs: [
{
"targets": [],
"render": function(data, type, row) {
            row[5] = row[2] * $(row[3]).val();
            return row[5];
         }
}]

what I did previously was like:
columnDefs: [
{
"targets": [],
"render": function(data, type, row) {
            value = row[2] * $(row[3]).val();
            return value;
         }
}]

here new value is returned and it will be visible in table but the row data wont be updated. If we update row[] array we will get the update in row().data().


Q: Cryptic error messages with npm and node I'm following facebook's tutorial on getting started with React Native (https://facebook.github.io/react-native/docs/tutorial.html#hello-world), but I can't get the react-native-cli to install. Any help interpreting the error messages? Obviously it says to unlink something, but I don't know what it is linked to that it shouldn't be linked to.
Running as root seems to do something, but zsh still won't recognize the react-native command.
➜  ~  npm install -g react-native-cli
npm ERR! Darwin 14.3.0
npm ERR! argv "node" "/usr/local/bin/npm" "install" "-g" "react-native-cli"
npm ERR! node v0.12.4
npm ERR! npm  v2.10.1
npm ERR! path /Users/bbarclay/.node/bin/react-native
npm ERR! code EACCES
npm ERR! errno -13

npm ERR! Error: EACCES, unlink '/Users/bbarclay/.node/bin/react-native'
npm ERR!     at Error (native)
npm ERR!  { [Error: EACCES, unlink '/Users/bbarclay/.node/bin/react-native']
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   path: '/Users/bbarclay/.node/bin/react-native' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.
npm ERR! error rolling back Error: EACCES, unlink '/Users/bbarclay/.node    /bin/react-native'
npm ERR! error rolling back     at Error (native)
npm ERR! error rolling back  { [Error: EACCES, unlink '/Users/bbarclay/.node/bin/react-native']
npm ERR! error rolling back   errno: -13,
npm ERR! error rolling back   code: 'EACCES',
npm ERR! error rolling back   path: '/Users/bbarclay/.node/bin/react-native' }

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/bbarclay/npm-debug.log
➜  ~  sudo npm install -g react-native-cli
Password:
/Users/bbarclay/.node/bin/react-native -> /Users/bbarclay/.node/lib/node_modules/react-native-cli/index.js
react-native-cli@0.1.4 /Users/bbarclay/.node/lib/node_modules/react-native-cli
└── prompt@0.2.14 (revalidator@0.1.8, pkginfo@0.3.0, read@1.0.6, winston@0.8.3, utile@0.2.1)
➜  ~  react-native init AwesomeProject
zsh: command not found: react-native

A: Add the admin permission to .npm home directory.
sudo chown -R $(whoami) ~/.npm